snmpit_cisco_stack.pm 33.1 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3

#
4
# EMULAB-LGPL
5
# Copyright (c) 2000-2009 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6 7 8
# All rights reserved.
#

9 10 11
#
# snmpit module for a stack of Cisco Catalyst 6509 switches. The main purpose
# of this module is to contain knowledge of how to manage stack-wide operations
12
# (such as VLAN creation), and to collate the results of listing operations
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# on multiple switches
#

package snmpit_cisco_stack;
use strict;

$| = 1; # Turn off line buffering on output

use English;
use SNMP;
use snmpit_lib;

use libdb;

#
# Creates a new object. A list of devices that will be operated on is given
# so that the object knows which to connect to. A future version may not 
# require the device list, and dynamically connect to devices as appropriate
#
32
# usage: new(string name, string stack_id, int debuglevel, list of devicenames)
33 34
# returns a new object blessed into the snmpit_cisco_stack class
#
35
sub new($$$$$@) {
36 37 38 39 40 41

    # The next two lines are some voodoo taken from perltoot(1)
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $stack_id = shift;
42
    my $debuglevel = shift;
43
    my $uses_vtp = shift;
44 45 46 47 48 49 50 51 52 53
    my @devicenames = @_;

    #
    # Create the actual object
    #
    my $self = {};

    #
    # Set up some defaults
    #
54 55 56 57 58
    if (defined $debuglevel) {
	$self->{DEBUG} = $debuglevel;
    } else {
	$self->{DEBUG} = 0;
    }
59
    #
60
    # The ID of this stack
61 62 63
    # 
    $self->{STACKID} = $stack_id;

64 65 66 67 68 69 70 71 72 73
    #
    # The name of the leader of this stack. We fall back on the old behavior of
    # using the stack name as the leader if the leader is not set
    #
    my $leader_name = getStackLeader($stack_id);
    if (!$leader_name) {
	$leader_name = $stack_id;
    }
    $self->{LEADERNAME} = $leader_name;

74 75 76 77 78
    #
    # Store the list of devices we're supposed to operate on
    #
    @{$self->{DEVICENAMES}} = @devicenames;

79 80 81 82 83
    #
    # Whether or not this stack uses VTP to keep the VLANs synchronized
    #
    $self->{VTP} = $uses_vtp;

84 85 86 87 88 89 90 91 92 93 94 95 96
    #
    # We'll use this to store any special arguments for VLAN creation
    #
    $self->{VLAN_SPECIALARGS} = {};

    #
    # Set by default now - don't create VLANs on switches that don't need
    # them. We always create VLANs on the leader, so that it can be used as a
    # sort of global list of what VLANs are available, and is atomically
    # lockable.
    #
    $self->{PRUNE_VLANS} = 1;

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    #
    # Make a device-dependant object for each switch
    #
    foreach my $devicename (@devicenames) {
	print("Making device object for $devicename\n") if $self->{DEBUG};
	my $type = getDeviceType($devicename);
	my $device;

	#
	# Check to see if this is a duplicate
	#
	if (defined($self->{DEVICES}{$devicename})) {
	    warn "WARNING: Device $device was specified twice, skipping\n";
	    next;
	}

	#
	# We check the type for two reasons: We may have multiple types of
	# ciscos in the future, and for some sanity checking to make sure
	# we weren't given devicenames for devices that aren't ciscos
	#
	SWITCH: for ($type) {
119
	    (/65\d\d/ || /40\d\d/ || /45\d\d/ || /29\d\d/ || /55\d\d/ || /35\d\d/)
120
		    && do {
121
		use snmpit_cisco;
122
		$device = new snmpit_cisco($devicename,$self->{DEBUG});
123 124 125 126
		if (!$device) {
		    die "Failed to create a device object for $devicename\n";
		} else {
		    $self->{DEVICES}{$devicename} = $device;
127
		    if ($devicename eq $self->{LEADERNAME}) {
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
			$self->{LEADER} = $device;
		    }
		    last;
		}
	    };
	    die "Device $devicename is not of a known type, skipping\n";
	}

    }

    #
    # Check for the stack leader, and create it if it hasn't been so far
    #
    if (!$self->{LEADER}) {
	# XXX: For simplicity, we assume for now that the leader is a Cisco
Robert Ricci's avatar
Robert Ricci committed
143
	use snmpit_cisco;
144 145
	my $type = getDeviceType($self->{LEADERNAME});
	$self->{LEADER} = new snmpit_cisco($self->{LEADERNAME}, $self->{DEBUG});
Robert Ricci's avatar
Robert Ricci committed
146
    }
147 148 149 150 151 152 153 154 155

    bless($self,$class);

    return $self;
}

#
# List all VLANs on all switches in the stack
#
156
# usage: listVlans(self)
157 158 159 160 161 162 163 164 165 166 167 168
#
# returns: A list of VLAN information. Each entry is an array reference. The
#	array is in the form [id, ddep, members] where:
#		id is the VLAN identifier, as stored in the database
#		ddep is an opaque string that is device-dependant (mostly for
#			debugging purposes)
#		members is a reference to an array of VLAN members
#
sub listVlans($) {
    my $self = shift;

    #
169
    # We need to 'collate' the results from each switch by putting together
170 171 172 173 174 175 176
    # the results from each switch, based on the VLAN identifier
    #
    my %vlans = ();
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	foreach my $line ($device->listVlans()) {
	    my ($vlan_id, $vlan_number, $memberRef) = @$line;
177 178
	    ${$vlans{$vlan_id}}[0] = $vlan_number;
	    push @{${$vlans{$vlan_id}}[1]}, @$memberRef;
179 180 181 182 183 184 185 186
	}
    }

    #
    # Now, we put the information we've found in the format described by
    # the header comment for this function
    #
    my @vlanList;
Robert Ricci's avatar
Robert Ricci committed
187
    foreach my $vlan (sort {tbsort($a,$b)} keys %vlans) {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
	push @vlanList, [$vlan, @{$vlans{$vlan}}];
    } 
    return @vlanList;
}

#
# List all ports on all switches in the stack
#
# usage: listPorts(self)
#
# returns: A list of port information. Each entry is an array reference. The
#	array is in the form [id, enabled, link, speed, duplex] where:
#		id is the port identifier (in node:port form)
#		enabled is "yes" if the port is enabled, "no" otherwise
#		link is "up" if the port has carrier, "down" otherwise
#		speed is in the form "XMbps"
#		duplex is "full" or "half"
#
sub listPorts($) {
    my $self = shift;

    #
210
    # All we really need to do here is collate the results of listing the
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    # ports on all devices
    #
    my %portinfo = (); 
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	foreach my $line ($device->listPorts()) {
	    my $port = $$line[0];
	    if (defined $portinfo{$port}) {
		warn "WARNING: Two ports found for $port\n";
	    }
	    $portinfo{$port} = $line;
	}
    }

    return map $portinfo{$_}, sort {tbsort($a,$b)} keys %portinfo;
}

#
# Puts ports in the VLAN with the given identifier. Contacts the device
# appropriate for each port.
#
# usage: setPortVlan(self, vlan_id, list of ports)
# returns: the number of errors encountered in processing the request
#
sub setPortVlan($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @ports = @_;

    my $errors = 0;

242 243 244 245 246 247 248 249 250
    #
    # Grab the VLAN number
    #
    my $vlan_number = $self->{LEADER}->findVlan($vlan_id);
    if (!$vlan_number) {
	print STDERR "ERROR: VLAN with identifier $vlan_id does not exist!\n";
	return 1;
    }

251 252 253 254
    #
    # Split up the ports among the devices involved
    #
    my %map = mapPortsToDevices(@ports);
255 256
    my %trunks;
    my @trunks;
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

    if ($self->{PRUNE_VLANS}) {
        #
        # Use this hash like a set to find out what switches might be involved
        # in this VLAN
        #
        my %switches;
        foreach my $switch (keys %map) {
            $switches{$switch} = 1;
        }

	#
	# Find out which ports are already in this VLAN - we might be adding
        # to an existing VLAN
        # TODO - provide a way to bypass this check for new VLANs, to speed
        # things up a bit
	#
        foreach my $switch ($self->switchesWithPortsInVlan($vlan_number)) {
            $switches{$switch} = 1;
        }

        #
        # Find out every switch which might have to transit this VLAN through
        # its trunks
        #
282 283
        %trunks = getTrunks();
        @trunks = getTrunksFromSwitches(\%trunks, keys %switches);
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        foreach my $trunk (@trunks) {
            my ($src,$dst) = @$trunk;
            $switches{$src} = $switches{$dst} = 1;
        }

        #
        # Create the VLAN (if it doesn't exist) on every switch involved
        #
        foreach my $switch (keys %switches) {
            #
            # Check to see if the VLAN already exists on this switch
            #
            my $dev = $self->{DEVICES}{$switch};
            if (!$dev) {
                warn "ERROR: VLAN uses switch $switch, which is not in ".
                    "this stack\n";
                $errors++;
                next;
            }
            if ($dev->vlanNumberExists($vlan_number)) {
                if ($self->{DEBUG}) {
                    print "Vlan $vlan_id already exists on $dev\n";
                }
            } else {
                #
                # Check to see if we had any special arguments saved up for
                # this VLAN
                #
                my @otherargs = ();
                if (exists $self->{VLAN_SPECIALARGS}{$vlan_id}) {
                    @otherargs = @{$self->{VLAN_SPECIALARGS}{$vlan_id}}
                }

                #
                # Create the VLAN
                #
                my $res = $dev->createVlan($vlan_id,$vlan_number);
                if ($res == 0) {
                    warn "Error: Failed to create VLAN $vlan_id ($vlan_number)".
                         " on $switch\n";
                    $errors++;
                    next;
                }
            }
        }
    }

331
    my %BumpedVlans = ();
332 333 334
    #
    # Perform the operation on each switch
    #
335 336 337 338 339 340 341 342 343 344 345 346
    foreach my $devicename (keys %map) {
	my $device = $self->{DEVICES}{$devicename};
    	if (!defined($device)) {
    	    warn "Unable to find device entry for $devicename - some ports " .
	    	"will not be set up properly\n";
    	    $errors++;
    	    next;
    	}

	#
	# Simply make the appropriate call on the device
	#
347
	$errors += $device->setPortVlan($vlan_number,@{$map{$devicename}});
348 349 350 351 352 353 354 355 356 357

	#
	# When making firewalls, may have to flush FDB entries from trunks
	#
	if (defined($device->{DISPLACED_VLANS})) {
	    foreach my $vlan (@{$device->{DISPLACED_VLANS}}) {
		$BumpedVlans{$vlan} = 1;
	    }
	    $device->{DISPLACED_VLANS} = undef;
	}
358 359
    }

360
    if ($vlan_id ne 'default') {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
	# if PRUNE were not in effect, then %trunks and @trunks
	# aren't valid.  If VTP weren't enforced however,
	# merely calling setVlanOnTrunks() with just the specified
	# ports would miss transit-only switches.
	# maybe the phrase at the top should be if (PRUNE || !VTP ..)
	# expecially if running VTP automatically creates the interswitch
	# trunks.
	# I'll let Rob R. decide what to do about that -- sklower.
	$errors += (!$self->setVlanOnTrunks2($vlan_number,1,\%trunks,@trunks));
    }

    #
    # When making firewalls, may have to flush FDB entries from trunks
    #
    foreach my $vlan (keys %BumpedVlans) {
	foreach my $devicename ($self->switchesWithPortsInVlan($vlan)) {
	    my $dev = $self->{DEVICES}{$devicename};
	    foreach my $neighbor (keys %{$trunks{$devicename}}) {
		my $trunkIndex = $dev->getChannelIfIndex(
				    @{$trunks{$devicename}{$neighbor}});
		if (!defined($trunkIndex)) {
		    warn "unable to find channel information on $devicename ".
			 "for $devicename-$neighbor EtherChannel\n";
		    $errors += 1;
		} else {
		    $dev->resetVlanIfOnTrunk($trunkIndex,$vlan);
		}
	    }
	}
390 391
    }

392 393 394 395
    return $errors;
}

#
396 397 398
# Creates a VLAN with the given VLAN identifier on the stack. If ports are
# given, puts them into the newly created VLAN. It is an error to create a
# VLAN that already exists.
399
#
400
# usage: createVlan(self, vlan identfier, port list)
401 402 403 404
#
# returns: 1 on success
# returns: 0 on failure
#
Robert Ricci's avatar
Robert Ricci committed
405
sub createVlan($$$;$$$) {
406 407
    my $self = shift;
    my $vlan_id = shift;
Robert Ricci's avatar
Robert Ricci committed
408 409
    my @ports = @{shift()};
    my @otherargs = @_;
410

411 412 413 414
    if (@otherargs) {
        $self->{VLAN_SPECIALARGS}{$vlan_id} = @otherargs;
    }

415
    #
416 417
    # What we do here depends on whether this stack uses VTP to synchronize
    # VLANs or not
418
    #
419
    my $vlan_number;
420 421 422 423 424

    # XXX temp, see doMakeVlans in snmpit.in
    if ($::next_vlan_tag)
	{ $vlan_number = $::next_vlan_tag; $::next_vlan_tag = 0; }

425
    if ($self->{VTP} || $self->{PRUNE_VLANS}) {
426 427 428 429
	#
	# We just need to create the VLAN on the stack leader
	#
	#
430
	$vlan_number = $self->{LEADER}->createVlan($vlan_id,$vlan_number,@otherargs);
431 432 433 434 435
    } else {
	#
	# We need to create the VLAN on all devices
	# XXX - should we do the leader first?
	#
436 437 438
	foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}){
	    print "Creating VLAN on switch $devicename ... \n"
		if $self->{DEBUG};
439
	    my $device = $self->{DEVICES}{$devicename};
Robert Ricci's avatar
Robert Ricci committed
440
	    my $res = $device->createVlan($vlan_id,$vlan_number,@otherargs);
441 442 443 444 445 446 447 448 449 450 451 452 453
	    if (!$res) {
		#
		# Ooops, failed. Don't try any more
		#
		last;
	    } else {
		#
		# Use the VLAN number we just got back for the other switches
		#
		$vlan_number = $res;
	    }
	}
    }
454

455 456 457 458
    #
    # We need to add the ports to VLANs at the stack level, since they are
    # not necessarily on the leader
    #
459
    if ($vlan_number && @ports) {
460
	if ($self->setPortVlan($vlan_id,@ports)) {
461
	    print STDERR "*** Failed to add ports to vlan\n";
462 463
	}
    }
464
    return return $vlan_number;
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
}

#
# Adds devices to an existing VLAN, in preparation for adding ports on these
# devices. It is an error to call this function on a VLAN that does not
# exist. It is _not_ an error to add a VLAN to a device on which it already
# exists.
#
# usage: addDevicesToVlan(self, vlan identfier, device list)
#
# returns: the number of errors encountered in processing the request
#
sub addDevicesToVlan($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @devicenames = @_; # Note: This is not used for Cisco switches

    #
    # This function is not needed on Cisco stacks, since all switches
    # share the same set of VLANs. We will, however, check to make sure
    # the VLAN really does exist
    #
    if (!$self->vlanExists($vlan_id)) {
	return 1;
    }

    return 0;
}

#
# Check to see if the given VLAN exists in the stack
#
# usage: vlanExists(self, vlan identifier)
#
# returns 1 if the VLAN exists
#         0 otherwise
#
sub vlanExists($$) {
    my $self = shift;
    my $vlan_id = shift;

    #
    # The leader holds the list of which VLANs exist
    #
509
    if ($self->{LEADER}->findVlan($vlan_id,1)) {
510 511 512 513 514 515 516
	return 1;
    } else {
	return 0;
    }

}

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
#
# Return a list of which VLANs from the input set exist on this stack
#
# usage: existantVlans(self, vlan identifiers)
#
# returns: a list containing the VLANs from the input set that exist on this
# 	stack
#
sub existantVlans($@) {
    my $self = shift;
    my @vlan_ids = @_;

    #
    # The leader holds the list of which VLANs exist
    #
    my %mapping = $self->{LEADER}->findVlans(@vlan_ids);

    my @existant = ();
    foreach my $vlan_id (@vlan_ids) {
	if (defined $mapping{$vlan_id}) {
	    push @existant, $vlan_id;
	}
    }

    return @existant;

}

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
#
# Given VLAN indentifiers from the database, finds the 802.1Q VLAN
# number for them. If no VLAN id is given, returns mappings for the entire
# stack.
#
# usage: findVlans($self, @vlan_ids)
#        returns a hash mapping VLAN ids to 802.1Q VLAN numbers
#
#
sub findVlans($@) {
    my $self = shift;
    my @vlan_ids = @_;
    my %mapping = ();

    #
    # For now, on Cisco, we only need to do this on the leader
    #
    return $self->{LEADER}->findVlans(@vlan_ids);
}

565 566 567 568
#
# Removes a VLAN from the stack. This implicitly removes all ports from the
# VLAN. It is an error to remove a VLAN that does not exist.
#
569
# usage: removeVlan(self, vlan identifiers)
570 571 572 573
#
# returns: 1 on success
# returns: 0 on failure
#
574
sub removeVlan($@) {
575
    my $self = shift;
576
    my @vlan_ids = @_;
577 578
    my $errors = 0;

579 580 581 582 583 584 585
    #
    # Exit early if no VLANs given
    #
    if (!@vlan_ids) {
	return 1;
    }

586
    my %vlan_numbers = $self->{LEADER}->findVlans(@vlan_ids);
587 588 589 590
    foreach my $vlan_id (@vlan_ids) {
	#
	# First, make sure that the VLAN really does exist
	#
591
	my $vlan_number = $vlan_numbers{$vlan_id};
592 593 594 595
	if (!$vlan_number) {
	    warn "ERROR: VLAN $vlan_id not found on switch!";
	    return 0;
	}
596

597
	#
598
	# Prevent the VLAN from being sent across trunks.
599
	#
600
	if (!$self->setVlanOnTrunks($vlan_number,0)) {
601
	    warn "ERROR: Unable to remove VLAN $vlan_number from trunks!\n";
602 603 604 605 606
	    #
	    # We can keep going, 'cause we can still remove the VLAN
	    #
	}
	
607 608
    }

609 610
    #
    # Now, we go through each device and remove all ports from the VLAN
611 612 613 614 615
    # on that device. Note the reverse sort order! This way, we do not
    # interfere with another snmpit processes, since createVlan tries
    # in 'forward' order (we will remove the VLAN from the 'last' switch
    # first, so the other snmpit will not see it free until it's been
    # removed from all switches)
616
    #
617
    my $vlan_removal_errors = 0;
618
    foreach my $devicename (sort {tbsort($b,$a)} keys %{$self->{DEVICES}}) {
619
	my $device = $self->{DEVICES}{$devicename};
620
	my @existant_vlans = ();
621
	my %vlan_numbers = $device->findVlans(@vlan_ids);
622 623 624 625 626 627
	foreach my $vlan_id (@vlan_ids) {

	    #
	    # Only remove ports from the VLAN if it exists on this
	    # device. Do it in one pass for efficiency
	    #
628
	    if (defined $vlan_numbers{$vlan_id}) {
629
		push @existant_vlans, $vlan_numbers{$vlan_id};
630
	    }
631
	}
632

633 634 635
	print "Removing ports on $devicename from VLANS " . 
	    join(",",@existant_vlans)."\n" if $self->{DEBUG};

636
	$errors += $device->removePortsFromVlan(@existant_vlans);
637 638 639 640 641

	#
	# If this stack doesn't use VTP, delete the VLAN, too, while
	# we're at it. If it does, we remove all VLANs down below (we can't
	# do it until the ports have been cleared from all switches.)
642 643 644 645
	# If there have been any errors removing VLANs from other switches,
	# we don't continue trying to remove them - this is in an attempt to
	# avoid ending up with VLANs that exist on switches in the stack but
	# NOT the 'master' (the first one we try to create them on)
646
	#
647
	if (!$self->{VTP} && !$vlan_removal_errors) {
648
	    my $ok = $device->removeVlan(@existant_vlans);
649
	    if (!$ok) { $errors++; $vlan_removal_errors++; }
650
	}
651 652
    }

653
    if ($self->{VTP}) {
654
	#
655 656
	# For efficiency, we remove all VLANs from the leader in one function
	# call. This can save a _lot_ of locking and unlocking.
657
	#
658 659 660 661 662 663 664 665 666 667
	if (!$errors) {
	    #
	    # Make a list of all the VLANs that really did exist
	    #
	    my @vlan_numbers;
	    my ($key, $value);
	    while (($key, $value) = each %vlan_numbers) {
		if ($value) {
		    push @vlan_numbers, $value;
		}
668 669
	    }

670 671 672 673
	    my $ok = $self->{LEADER}->removeVlan(@vlan_numbers);
	    if (!$ok) {
		$errors++;
	    }
674 675
	}
    }
676

677
    return ($errors == 0);
678 679
}

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
#
# Remove some ports from a single vlan,
#
# usage: removeSomePortsFromVlan(self, vlan identifier, port list)
#
# returns: 1 on success
# returns: 0 on failure
#
sub removeSomePortsFromVlan($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @ports = @_;
    my $errors = 0;

    my %vlan_numbers = $self->{LEADER}->findVlans($vlan_id);
    
    #
    # First, make sure that the VLAN really does exist
    #
    my $vlan_number = $vlan_numbers{$vlan_id};
    if (!$vlan_number) {
	warn "ERROR: VLAN $vlan_id not found on switch!";
	return 0;
    }

    #
    # Prevent the VLAN from being sent across trunks.
    #
    if (!$self->setVlanOnTrunks($vlan_number,0)) {
	warn "ERROR: Unable to remove VLAN $vlan_number from trunks!\n";
	#
	# We can keep going, 'cause we can still remove the VLAN
	#
    }

    #
    # Now, we go through each device and remove all ports from the VLAN
    # on that device. Note the reverse sort order! This way, we do not
    # interfere with another snmpit processes, since createVlan tries
    # in 'forward' order (we will remove the VLAN from the 'last' switch
    # first, so the other snmpit will not see it free until it's been
    # removed from all switches)
    #
    foreach my $devicename (sort {tbsort($b,$a)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	my %vlan_numbers = $device->findVlans($vlan_id);

	#
	# Only remove ports from the VLAN if it exists on this device.
	#
	next
	    if (!defined($vlan_numbers{$vlan_id}));
	    
	print "Removing ports on $devicename from VLAN $vlan_id\n"
	    if $self->{DEBUG};

	$errors += $device->removeSomePortsFromVlan($vlan_id, @ports);
    }
    return ($errors == 0);
}

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
#
# Set a variable associated with a port. 
# TODO: Need a list of variables here
#
sub portControl ($$@) { 
    my $self = shift;
    my $cmd = shift;
    my @ports = @_;
    my %portDeviceMap = mapPortsToDevices(@ports);
    my $errors = 0;
    # XXX: each
    while (my ($devicename,$ports) = each %portDeviceMap) {
	$errors += $self->{DEVICES}{$devicename}->portControl($cmd,@$ports);
    }
    return $errors;
}

#
759
# Get port statistics for all devices in the stack
760 761 762 763 764
#
sub getStats($) {
    my $self = shift;

    #
765
    # All we really need to do here is collate the results of listing the
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    # ports on all devices
    #
    my %stats = (); 
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	foreach my $line ($device->getStats()) {
	    my $port = $$line[0];
	    if (defined $stats{$port}) {
		warn "WARNING: Two ports found for $port\n";
	    }
	    $stats{$port} = $line;
	}
    }
    return map $stats{$_}, sort {tbsort($a,$b)} keys %stats;
}

782 783 784
#
# Turns on trunking on a given port, allowing only the given VLANs on it
#
785 786 787 788
# usage: enableTrunking2(self, port, equaltrunking, vlan identifier list)
#
# formerly was enableTrunking() without the predicate to decline to put
# the port in dual mode.
789 790 791 792
#
# returns: 1 on success
# returns: 0 on failure
#
793
sub enableTrunking2($$$@) {
794 795
    my $self = shift;
    my $port = shift;
796
    my $equaltrunking = shift;
797 798 799 800 801 802 803 804 805 806 807 808
    my @vlan_ids = @_;

    #
    # Split up the ports among the devices involved
    #
    my %map = mapPortsToDevices($port);
    my ($devicename) = keys %map;
    my $device = $self->{DEVICES}{$devicename};
    if (!defined($device)) {
	warn "ERROR: Unable to find device entry for $devicename\n";
	return 0;
    }
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    #
    # If !equaltrunking, the first VLAN given becomes the PVID for the trunk
    #
    my ($native_vlan_id, $vlan_number);
    if ($equaltrunking) {
	$native_vlan_id = "default";
	$vlan_number = 1;
    } else {
	$native_vlan_id = shift @vlan_ids;
	if (!$native_vlan_id) {
	    warn "ERROR: No VLAN passed to enableTrunking()!\n";
	    return 0;
	}
	#
	# Grab the VLAN number for the native VLAN
	#
	$vlan_number = $device->findVlan($native_vlan_id);
	if (!$vlan_number) {
	    warn "Native VLAN $native_vlan_id was not on $devicename";
	    # This is painful
	    my $error = $self->setPortVlan($native_vlan_id,$port);
	    if ($error) {
		    warn ", and couldn't add it\n"; return 0;
	    } else { warn "\n"; } 
	}
    }
835 836 837 838 839 840

    #
    # Simply make the appropriate call on the device
    #
    print "Enable trunking: Port is $port, native VLAN is $native_vlan_id\n"
	if ($self->{DEBUG});
841
    my $rv = $device->enablePortTrunking2($port, $vlan_number, $equaltrunking);
842 843 844 845 846 847 848 849

    #
    # If other VLANs were given, add them to the port too
    #
    if (@vlan_ids) {
	my @vlan_numbers;
	foreach my $vlan_id (@vlan_ids) {
	    #
850 851 852
	    # setPortVlan makes sure that the VLAN really does exist
	    # and will set up intervening trunks as well as adding the
	    # trunked port to that VLAN
853
	    #
854 855 856
	    my $error = $self->setPortVlan($vlan_id,$port);
	    if ($error) {
		warn "ERROR: could not add VLAN $vlan_id to trunk $port\n";
857 858 859 860
		next;
	    }
	    push @vlan_numbers, $vlan_number;
	}
Mike Hibler's avatar
Mike Hibler committed
861 862
	print "  add VLANs " . join(",",@vlan_numbers) . " to trunk\n"
	    if ($self->{DEBUG});
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    }

    return $rv;

}

#
# Turns off trunking for a given port
#
# usage: disableTrunking(self, ports)
#
# returns: 1 on success
# returns: 0 on failure
#
sub disableTrunking($$) {
    my $self = shift;
    my $port = shift;

    #
    # Split up the ports among the devices involved
    #
    my %map = mapPortsToDevices($port);
    my ($devicename) = keys %map;
    my $device = $self->{DEVICES}{$devicename};
    if (!defined($device)) {
	warn "ERROR: Unable to find device entry for $devicename\n";
	return 0;
    }

    #
    # Simply make the appropriate call on the device
    #
    my $rv = $device->disablePortTrunking($port);

    return $rv;

}

901 902 903 904 905
#
# Not a 'public' function - only needs to get called by other functions in
# this file, not external functions.
#
# Enables or disables (depending on $value) a VLAN on all appropriate
906
# switches in a stack. Returns 1 on sucess, 0 on failure.
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
#
# ONLY pass in @ports if you're SURE that they are the only ports in the
# VLAN - basically, only if you just created it. This is a shortcut, so
# that we don't have to ask all switches if they have any ports in the VLAN.
#
sub setVlanOnTrunks($$$;@) {
    my $self = shift;
    my $vlan_number = shift;
    my $value = shift;
    my @ports = @_;

    #
    # First, get a list of all trunks
    #
    my %trunks = getTrunks();

    #
    # Next, figure out which switches this VLAN exists on
    #
    my @switches;
    if (@ports) {
	#
	# I'd rather not have to go out to the switches to ask which ones
	# have ports in the VLAN. So, if they gave me ports, I'll just 
	# trust that those are the only ones in the VLAN
	#
	@switches = getDeviceNames(@ports);
    } else {
	#
	# Since this may be a hand-created (not from the database) VLAN, the
	# only way we can figure out which swtiches this VLAN spans is to
	# ask them all.
	#
940
        @switches = $self->switchesWithPortsInVlan($vlan_number);
941 942 943 944 945 946 947
    }

    #
    # Next, get a list of the trunks that are used to move between these
    # switches
    #
    my @trunks = getTrunksFromSwitches(\%trunks,@switches);
948 949 950 951 952 953 954 955 956 957 958 959
    return $self->setVlanOnTrunks2($vlan_number,$value,\%trunks,@trunks);
}
#
# Enables or disables (depending on $value) a VLAN on all the supplied
# trunks. Returns 1 on sucess, 0 on failure.
#
sub setVlanOnTrunks2($$$$@) {
    my $self = shift;
    my $vlan_number = shift;
    my $value = shift;
    my $trunkref = shift;
    my @trunks = @_;
960 961 962 963 964 965 966 967 968

    #
    # Now, we go through the list of trunks that need to be modifed, and
    # do it! We have to modify both ends of the trunk, or we'll end up wasting
    # the trunk bandwidth.
    #
    my $errors = 0;
    foreach my $trunk (@trunks) {
	my ($src,$dst) = @$trunk;
969 970 971 972 973 974 975 976 977

        #
        # For now - ignore trunks that leave the stack. We may have to revisit
        # this at some point.
        #
        if (!$self->{DEVICES}{$src} || !$self->{DEVICES}{$dst}) {
            next;
        }

978 979 980 981 982
	if (!$self->{DEVICES}{$src}) {
	    warn "ERROR - Bad device $src found in setVlanOnTrunks!\n";
	    $errors++;
	} else {
	    #
983
	    # Trunks might be EtherChannels, find the ifIndex
984
	    #
985
            my $trunkIndex = $self->{DEVICES}{$src}->
986
                             getChannelIfIndex(@{ $$trunkref{$src}{$dst} });
987
            if (!defined($trunkIndex)) {
988 989
                warn "ERROR - unable to find channel information on $src ".
		     "for $src-$dst EtherChannel\n";
990 991 992 993
                $errors += 1;
            } else {
		if (!$self->{DEVICES}{$src}->
                        setVlansOnTrunk($trunkIndex,$value,$vlan_number)) {
994
                    warn "ERROR - unable to set trunk on switch $src\n";
995 996
                    $errors += 1;
                }
997
	    }
998 999 1000 1001 1002 1003
	}
	if (!$self->{DEVICES}{$dst}) {
	    warn "ERROR - Bad device $dst found in setVlanOnTrunks!\n";
	    $errors++;
	} else {
	    #
1004
	    # Trunks might be EtherChannels, find the ifIndex
1005
	    #
1006
            my $trunkIndex = $self->{DEVICES}{$dst}->
1007
                             getChannelIfIndex(@{ $$trunkref{$dst}{$src} });
1008
            if (!defined($trunkIndex)) {
1009 1010
                warn "ERROR - unable to find channel information on $dst ".
		     "for $src-$dst EtherChannel\n";
1011 1012 1013 1014
                $errors += 1;
            } else {
		if (!$self->{DEVICES}{$dst}->
                        setVlansOnTrunk($trunkIndex,$value,$vlan_number)) {
1015
                    warn "ERROR - unable to set trunk on switch $dst\n";
1016 1017
                    $errors += 1;
                }
1018
	    }
1019 1020 1021
	}
    }

1022
    return (!$errors);
1023 1024
}

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
#
# Not a 'public' function - only needs to get called by other functions in
# this file, not external functions.
#
# Get a list of all switches that have at least one port in the given
# VLAN - note that is take a VLAN number, not a VLAN ID
#
# Returns a possibly-empty list of switch names
#
sub switchesWithPortsInVlan($$) {
    my $self = shift;
    my $vlan_number = shift;
    my @switches = ();
    foreach my $devicename (keys %{$self->{DEVICES}}) {
        my $device = $self->{DEVICES}{$devicename};
1040
	if ($device->vlanHasPorts($vlan_number)) {
1041
	    push @switches, $devicename;
1042 1043 1044 1045 1046
        }
    }
    return @switches;
}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
#
# Openflow enable function for Cisco stack
# Till now it just report an error.
#
# enableOpenflow(self, vlan_id)
# return # of errors
#
sub enableOpenflow($$) {
    my $self = shift;
    my $vlan_id = shift;
    
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1062 1063 1064 1065 1066 1067 1068 1069 1070
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1071
		print "Enabling Openflow on $devicename for VLAN $vlan_id".
1072
		    "..." if $self->{DEBUG};
1073 1074 1075

		my $ok = $device->enableOpenflow($vlan_number);
		if (!$ok) { $errors++; }
1076 1077 1078 1079 1080 1081 1082 1083
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
	}
    }
        
    return $errors;
}

#
# Disable Openflow
#
# disableOpenflow(self, vlan_id);
# return # of errors
#
sub disableOpenflow($$) {
    my $self = shift;
    my $vlan_id = shift;
    
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1104 1105 1106 1107 1108 1109 1110 1111 1112
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1113
		print "Disabling Openflow on $devicename for VLAN $vlan_id".
1114
		    "..." if $self->{DEBUG};
1115 1116 1117

		my $ok = $device->disableOpenflow($vlan_number);
		if (!$ok) { $errors++; }
1118 1119 1120 1121 1122 1123 1124 1125
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
	}
    }
        
    return $errors;
}

#
# Set Openflow controller on VLAN
#
# setController(self, vlan_id, controller);
# return # of errors
#
1138
sub setOpenflowController($$$) {
1139 1140 1141 1142 1143 1144 1145 1146
    my $self = shift;
    my $vlan_id = shift;
    my $controller = shift;
    
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1147 1148 1149 1150 1151 1152 1153 1154 1155
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1156
		print "Setting Openflow controller on $devicename for VLAN $vlan_id".
1157
		    "..." if $self->{DEBUG};
1158

1159
		my $ok = $device->setOpenflowController($vlan_number, $controller);
1160
		if (!$ok) { $errors++; }
1161 1162 1163 1164 1165 1166 1167 1168
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
	}
    }
        
    return $errors;
}

#
# Set Openflow listener on VLAN
#
# setListener(self, vlan_id, listener);
# return # of errors
#
# This function might be replaced by a enableListener(vlan_id)
# that sets the listener on switches automatically and returns
# the listener connection string.
#
1185
sub setOpenflowListener($$$) {
1186 1187 1188 1189 1190 1191 1192 1193
    my $self = shift;
    my $vlan_id = shift;
    my $listener = shift;
    
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1194 1195 1196 1197 1198 1199 1200 1201 1202
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1203
		print "Setting Openflow listener on $devicename for VLAN $vlan_id".
1204
		    "..." if $self->{DEBUG};
1205

1206
		my $ok = $device->setOpenflowListener($vlan_number, $listener);
1207
		if (!$ok) { $errors++; }
1208 1209 1210 1211 1212 1213 1214 1215 1216
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
	}	
1217 1218 1219 1220 1221
    }
        
    return $errors;
}

1222 1223 1224 1225

#
# Get used Openflow listener ports
#
1226 1227
# getUsedOpenflowListenerPorts(self, vlan_id)
#
1228 1229
sub getUsedOpenflowListenerPorts($$) {
    my $self = shift;
1230 1231
    my $vlan_id = shift;
    my %ports = ();
1232 1233 1234 1235

    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {		
		my %tmports = $device->getUsedOpenflowListenerPorts();
		@ports{ keys %tmports } = values %tmports;		
	    } else {
		#
		# YES this be an error because the VLAN is on it.
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
	    }
	}	
1254
    }
1255 1256

    return %ports;
1257 1258
}

1259 1260
# End with true
1;