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

#
4
# EMULAB-LGPL
5
# Copyright (c) 2000-2005 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh 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

    #
61
    # The ID of this stack
62 63 64
    # 
    $self->{STACKID} = $stack_id;

65 66 67 68 69 70 71 72 73 74
    #
    # 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;

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

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

85 86 87 88 89 90 91 92 93 94 95 96 97
    #
    # 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;

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    #
    # 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) {
120
	    (/65\d\d/ || /40\d\d/ || /45\d\d/ || /29\d\d/ || /55\d\d/)
121
		    && do {
122
		use snmpit_cisco;
123
		$device = new snmpit_cisco($devicename,$self->{DEBUG});
124 125 126 127
		if (!$device) {
		    die "Failed to create a device object for $devicename\n";
		} else {
		    $self->{DEVICES}{$devicename} = $device;
128
		    if ($devicename eq $self->{LEADERNAME}) {
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
			$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
144
	use snmpit_cisco;
145 146
	my $type = getDeviceType($self->{LEADERNAME});
	$self->{LEADER} = new snmpit_cisco($self->{LEADERNAME}, $self->{DEBUG});
Robert Ricci's avatar
Robert Ricci committed
147
    }
148 149 150 151 152 153 154 155 156

    bless($self,$class);

    return $self;
}

#
# List all VLANs on all switches in the stack
#
157
# usage: listVlans(self)
158 159 160 161 162 163 164 165 166 167 168 169
#
# 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;

    #
170
    # We need to 'collate' the results from each switch by putting together
171 172 173 174 175 176 177
    # 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;
178 179
	    ${$vlans{$vlan_id}}[0] = $vlan_number;
	    push @{${$vlans{$vlan_id}}[1]}, @$memberRef;
180 181 182 183 184 185 186 187
	}
    }

    #
    # 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
188
    foreach my $vlan (sort {tbsort($a,$b)} keys %vlans) {
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
	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;

    #
211
    # All we really need to do here is collate the results of listing the
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 242
    # 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;

243 244 245 246 247 248 249 250 251
    #
    # 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;
    }

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

    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
        #
283 284
        %trunks = getTrunks();
        @trunks = getTrunksFromSwitches(\%trunks, keys %switches);
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 331
        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;
                }
            }
        }
    }

332
    my %BumpedVlans = ();
333 334 335
    #
    # Perform the operation on each switch
    #
336 337 338 339 340 341 342 343 344 345 346 347
    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
	#
348
	$errors += $device->setPortVlan($vlan_number,@{$map{$devicename}});
349 350 351 352 353 354 355 356 357 358

	#
	# 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;
	}
359 360
    }

361
    if ($vlan_id ne 'default') {
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 390
	# 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);
		}
	    }
	}
391 392
    }

393 394 395 396
    return $errors;
}

#
397 398 399
# 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.
400
#
401
# usage: createVlan(self, vlan identfier, port list)
402 403 404 405
#
# returns: 1 on success
# returns: 0 on failure
#
Robert Ricci's avatar
Robert Ricci committed
406
sub createVlan($$$;$$$) {
407 408
    my $self = shift;
    my $vlan_id = shift;
Robert Ricci's avatar
Robert Ricci committed
409 410
    my @ports = @{shift()};
    my @otherargs = @_;
411

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

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

453 454 455 456 457 458 459 460 461
    #
    # We need to add the ports to VLANs at the stack level, since they are
    # not necessarily on the leader
    #
    if ($okay && @ports) {
	if ($self->setPortVlan($vlan_id,@ports)) {
	    $okay = 0;
	}
    }
462 463

    return $okay;
464 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
}

#
# 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
    #
508
    if ($self->{LEADER}->findVlan($vlan_id,1)) {
509 510 511 512 513 514 515
	return 1;
    } else {
	return 0;
    }

}

516 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
#
# 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;

}

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
#
# 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);
}

564 565 566 567
#
# 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.
#
568
# usage: removeVlan(self, vlan identifiers)
569 570 571 572
#
# returns: 1 on success
# returns: 0 on failure
#
573
sub removeVlan($@) {
574
    my $self = shift;
575
    my @vlan_ids = @_;
576 577
    my $errors = 0;

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

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

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

608 609
    #
    # Now, we go through each device and remove all ports from the VLAN
610 611 612 613 614
    # 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)
615
    #
616
    my $vlan_removal_errors = 0;
617
    foreach my $devicename (sort {tbsort($b,$a)} keys %{$self->{DEVICES}}) {
618
	my $device = $self->{DEVICES}{$devicename};
619
	my @existant_vlans = ();
620
	my %vlan_numbers = $device->findVlans(@vlan_ids);
621 622 623 624 625 626
	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
	    #
627
	    if (defined $vlan_numbers{$vlan_id}) {
628
		push @existant_vlans, $vlan_numbers{$vlan_id};
629
	    }
630
	}
631

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

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

	#
	# 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.)
641 642 643 644
	# 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)
645
	#
646
	if (!$self->{VTP} && !$vlan_removal_errors) {
647
	    my $ok = $device->removeVlan(@existant_vlans);
648
	    if (!$ok) { $errors++; $vlan_removal_errors++; }
649
	}
650 651
    }

652
    if ($self->{VTP}) {
653
	#
654 655
	# For efficiency, we remove all VLANs from the leader in one function
	# call. This can save a _lot_ of locking and unlocking.
656
	#
657 658 659 660 661 662 663 664 665 666
	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;
		}
667 668
	    }

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

676
    return ($errors == 0);
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
}

#
# 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;
}

#
697
# Get port statistics for all devices in the stack
698 699 700 701 702
#
sub getStats($) {
    my $self = shift;

    #
703
    # All we really need to do here is collate the results of listing the
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    # 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;
}

720 721 722
#
# Turns on trunking on a given port, allowing only the given VLANs on it
#
723 724 725 726
# usage: enableTrunking2(self, port, equaltrunking, vlan identifier list)
#
# formerly was enableTrunking() without the predicate to decline to put
# the port in dual mode.
727 728 729 730
#
# returns: 1 on success
# returns: 0 on failure
#
731
sub enableTrunking2($$$@) {
732 733
    my $self = shift;
    my $port = shift;
734
    my $equaltrunking = shift;
735 736 737 738 739 740 741 742 743 744 745 746
    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;
    }
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    #
    # 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"; } 
	}
    }
773 774 775 776 777 778

    #
    # Simply make the appropriate call on the device
    #
    print "Enable trunking: Port is $port, native VLAN is $native_vlan_id\n"
	if ($self->{DEBUG});
779
    my $rv = $device->enablePortTrunking2($port, $vlan_number, $equaltrunking);
780 781 782 783 784 785 786 787

    #
    # If other VLANs were given, add them to the port too
    #
    if (@vlan_ids) {
	my @vlan_numbers;
	foreach my $vlan_id (@vlan_ids) {
	    #
788 789 790
	    # 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
791
	    #
792 793 794
	    my $error = $self->setPortVlan($vlan_id,$port);
	    if ($error) {
		warn "ERROR: could not add VLAN $vlan_id to trunk $port\n";
795 796 797 798
		next;
	    }
	    push @vlan_numbers, $vlan_number;
	}
Mike Hibler's avatar
Mike Hibler committed
799 800
	print "  add VLANs " . join(",",@vlan_numbers) . " to trunk\n"
	    if ($self->{DEBUG});
801 802 803 804 805 806 807 808 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 835 836 837 838
    }

    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;

}

839 840 841 842 843
#
# 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
844
# switches in a stack. Returns 1 on sucess, 0 on failure.
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
#
# 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.
	#
878
        @switches = $self->switchesWithPortsInVlan($vlan_number);
879 880 881 882 883 884 885
    }

    #
    # Next, get a list of the trunks that are used to move between these
    # switches
    #
    my @trunks = getTrunksFromSwitches(\%trunks,@switches);
886 887 888 889 890 891 892 893 894 895 896 897
    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 = @_;
898 899 900 901 902 903 904 905 906

    #
    # 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;
907 908 909 910 911 912 913 914 915

        #
        # 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;
        }

916 917 918 919 920
	if (!$self->{DEVICES}{$src}) {
	    warn "ERROR - Bad device $src found in setVlanOnTrunks!\n";
	    $errors++;
	} else {
	    #
921
	    # Trunks might be EtherChannels, find the ifIndex
922
	    #
923
            my $trunkIndex = $self->{DEVICES}{$src}->
924
                             getChannelIfIndex(@{ $$trunkref{$src}{$dst} });
925
            if (!defined($trunkIndex)) {
926 927
                warn "ERROR - unable to find channel information on $src ".
		     "for $src-$dst EtherChannel\n";
928 929 930 931
                $errors += 1;
            } else {
		if (!$self->{DEVICES}{$src}->
                        setVlansOnTrunk($trunkIndex,$value,$vlan_number)) {
932
                    warn "ERROR - unable to set trunk on switch $src\n";
933 934
                    $errors += 1;
                }
935
	    }
936 937 938 939 940 941
	}
	if (!$self->{DEVICES}{$dst}) {
	    warn "ERROR - Bad device $dst found in setVlanOnTrunks!\n";
	    $errors++;
	} else {
	    #
942
	    # Trunks might be EtherChannels, find the ifIndex
943
	    #
944
            my $trunkIndex = $self->{DEVICES}{$dst}->
945
                             getChannelIfIndex(@{ $$trunkref{$dst}{$src} });
946
            if (!defined($trunkIndex)) {
947 948
                warn "ERROR - unable to find channel information on $dst ".
		     "for $src-$dst EtherChannel\n";
949 950 951 952
                $errors += 1;
            } else {
		if (!$self->{DEVICES}{$dst}->
                        setVlansOnTrunk($trunkIndex,$value,$vlan_number)) {
953
                    warn "ERROR - unable to set trunk on switch $dst\n";
954 955
                    $errors += 1;
                }
956
	    }
957 958 959
	}
    }

960
    return (!$errors);
961 962
}

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
#
# 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};
978
	if ($device->vlanHasPorts($vlan_number)) {
979
	    push @switches, $devicename;
980 981 982 983 984
        }
    }
    return @switches;
}

985 986
# End with true
1;