snmpit_cisco.pm 59.8 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-2007 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6 7 8
# All rights reserved.
#

Mac Newbold's avatar
Mac Newbold committed
9 10 11
#
# snmpit module for Cisco Catalyst 6509 switches
#
12 13 14
# TODO: Standardize returning 0 on success/failure
# TODO: Fix uninitialized variable warnings in getStats()
#
Mac Newbold's avatar
Mac Newbold committed
15 16

package snmpit_cisco;
17
use strict;
Mac Newbold's avatar
Mac Newbold committed
18 19 20

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

Mac Newbold's avatar
Mac Newbold committed
21
use English;
Mac Newbold's avatar
Mac Newbold committed
22 23
use SNMP;
use snmpit_lib;
24
use Socket;
25
use libtestbed;
Mac Newbold's avatar
Mac Newbold committed
26

27 28 29 30 31 32
#
# These are the commands that can be passed to the portControl function
# below
#
my %cmdOIDs =
(
33 34 35 36 37 38 39 40
    "enable"  => ["ifAdminStatus","up"],
    "disable" => ["ifAdminStatus","down"],
    "1000mbit"=> ["portAdminSpeed","s1000000000"],
    "100mbit" => ["portAdminSpeed","s100000000"],
    "10mbit"  => ["portAdminSpeed","s10000000"],
    "full"    => ["portDuplex","full"],
    "half"    => ["portDuplex","half"],
    "auto"    => ["portAdminSpeed","autoDetect",
41 42
		 "portDuplex","auto"]
);
Mac Newbold's avatar
Mac Newbold committed
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57
#
# Ports can be passed around in three formats:
# ifindex: positive integer corresponding to the interface index (eg. 42)
# modport: dotted module.port format, following the physical reality of
#	Cisco switches (eg. 5.42)
# nodeport: node:port pair, referring to the node that the switch port is
# 	connected to (eg. "pc42:1")
#
# See the function convertPortFormat below for conversions between these
# formats
#
my $PORT_FORMAT_IFINDEX  = 1;
my $PORT_FORMAT_MODPORT  = 2;
my $PORT_FORMAT_NODEPORT = 3;
Mac Newbold's avatar
Mac Newbold committed
58

59 60 61
#
# Creates a new object.
#
62
# usage: new($classname,$devicename,$debuglevel,$community)
63 64
#        returns a new object, blessed into the snmpit_cisco class.
#
65
sub new($$$;$) {
Mac Newbold's avatar
Mac Newbold committed
66

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

71 72
    my $name = shift;
    my $debugLevel = shift;
73
    my $community = shift;
74

75 76 77 78
    #
    # Create the actual object
    #
    my $self = {};
Mac Newbold's avatar
Mac Newbold committed
79

80 81 82 83 84 85 86 87 88
    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
	$self->{DEBUG} = $debugLevel;
    } else {
	$self->{DEBUG} = 0;
    }
    $self->{BLOCK} = 1;
89
    $self->{BULK} = 1;
90
    $self->{NAME} = $name;
91

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    #
    # Get config options from the database
    #
    my $options = getDeviceOptions($self->{NAME});
    if (!$options) {
	warn "ERROR: Getting switch options for $self->{NAME}\n";
	return undef;
    }

    $self->{SUPPORTS_PRIVATE} = $options->{'supports_private'};
    $self->{MIN_VLAN}         = $options->{'min_vlan'};
    $self->{MAX_VLAN}         = $options->{'max_vlan'};

    if ($community) { # Allow this to over-ride the default
	$self->{COMMUNITY}    = $community;
    } else {
	$self->{COMMUNITY}    = $options->{'snmp_community'};
    }

    #
    # We have to change our behavior depending on what OS the switch runs
    #
114 115 116 117 118
    if (!($options->{'type'} =~ /^(\w+)(-modhack(-?))?(-ios)?$/)) {
	warn "ERROR: Incorrectly formatted switch type name: ",
	     $options->{'type'}, "\n";
	return undef;
    }
Robert Ricci's avatar
Robert Ricci committed
119
    $self->{SWITCHTYPE} = $1;
120 121 122 123 124
    if (!$self->{SWITCHTYPE}) {
	warn "ERROR: Unable to determine type of switch $self->{NAME} from " .
             "string '$options->{type}'\n";
	return undef;
    }
125

126
    if ($2) {
Robert Ricci's avatar
Robert Ricci committed
127 128 129 130 131 132
        $self->{NON_MODULAR_HACK} = 1;
    } else {
        $self->{NON_MODULAR_HACK} = 0;
    }

    if ($4) {
133 134 135 136
	$self->{OSTYPE} = "IOS";
    } else {
	$self->{OSTYPE} = "CatOS";
    }
137 138 139 140 141

    if ($self->{DEBUG}) {
	print "snmpit_cisco module initializing... debug level $self->{DEBUG}\n";
    }

142 143 144 145 146 147 148 149 150 151 152 153 154
    #
    # Find the class of switch - look for 4 digits in the switch type
    #
    if ($self->{SWITCHTYPE} =~ /(\d{2})\d{2}/) {
       $self->{SWITCHCLASS} = "${1}00";
    } else {
        warn "snmpit: Unable to determine switch class for $name\n";
        $self->{SWITCHCLASS} = "6500";
    }
    if ($self->{DEBUG}) {
	print "snmpit_cisco picked class $self->{SWITCHCLASS}\n";
    }

155 156 157 158 159 160
    #
    # Set up SNMP module variables, and connect to the device
    #
    $SNMP::debugging = ($self->{DEBUG} - 2) if $self->{DEBUG} > 2;
    my $mibpath = '/usr/local/share/snmp/mibs';
    &SNMP::addMibDirs($mibpath);
161 162 163 164 165
    # We list all MIBs we use, so that we don't depend on a correct .index file
    my @mibs = ("$mibpath/SNMPv2-SMI.txt", "$mibpath/SNMPv2-TC.txt",
	    "$mibpath/SNMPv2-MIB.txt", "$mibpath/IANAifType-MIB.txt",
	    "$mibpath/IF-MIB.txt", "$mibpath/RMON-MIB.txt",
	    "$mibpath/CISCO-SMI.txt", "$mibpath/CISCO-TC.txt",
Robert Ricci's avatar
Robert Ricci committed
166 167
	    "$mibpath/CISCO-VTP-MIB.txt", "$mibpath/CISCO-PAGP-MIB.txt",
	    "$mibpath/CISCO-PRIVATE-VLAN-MIB.txt");
168 169 170 171
	    
    if ($self->{OSTYPE} eq "CatOS") {
	push @mibs, "$mibpath/CISCO-STACK-MIB.txt";
    } elsif ($self->{OSTYPE} eq "IOS") {
172
	push @mibs, "$mibpath/CISCO-STACK-MIB.txt",
173 174
                    "$mibpath/CISCO-VLAN-MEMBERSHIP-MIB.txt",
                    "$mibpath/CISCO-CONFIG-COPY-MIB.txt";
175 176 177 178 179
    } else {
	warn "ERROR: Unsupported switch OS $self->{OSTYPE}\n";
	return undef;
    }

180 181 182 183 184
    if ($self->{SWITCHCLASS} == 2900) {
        # There is a special MIB with some 2900 stuff in it
	push @mibs, "$mibpath/CISCO-C2900-MIB.txt";
    }

185
    &SNMP::addMibFiles(@mibs);
186 187 188 189 190 191 192
    
    $SNMP::save_descriptions = 1; # must be set prior to mib initialization
    SNMP::initMib();		  # parses default list of Mib modules 
    $SNMP::use_enums = 1;	  # use enum values instead of only ints

    warn ("Opening SNMP session to $self->{NAME}...") if ($self->{DEBUG});
    $self->{SESS} =
193 194
	    new SNMP::Session(DestHost => $self->{NAME},Version => "2c",
		    Community => $self->{COMMUNITY});
195 196 197 198 199 200 201
    if (!$self->{SESS}) {
	#
	# Bomb out if the session could not be established
	#
	warn "ERROR: Unable to connect via SNMP to $self->{NAME}\n";
	return undef;
    }
Mac Newbold's avatar
Mac Newbold committed
202

203 204 205 206 207 208 209 210 211
    #
    # Connecting an SNMP session doesn't necessarily mean you can actually get
    # packets to and from the switch. Test that by grabbing an OID that should
    # be on every switch. Let it retry a bunch, to hide transient failures
    #

    my $OS_details = snmpitGetFatal($self->{SESS},["sysDescr",0],30);
    print "Switch $self->{NAME} is running $OS_details\n" if $self->{DEBUG};

212 213 214 215 216
    #
    # The bless needs to occur before readifIndex(), since it's a class 
    # method
    #
    bless($self,$class);
Mac Newbold's avatar
Mac Newbold committed
217

218
    $self->readifIndex();
Mac Newbold's avatar
Mac Newbold committed
219

220
    return $self;
Mac Newbold's avatar
Mac Newbold committed
221 222
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
#
# Set a variable associated with a port. The commands to execute are given
# in the cmdOIs hash above
#
# usage: portControl($self, $command, @ports)
#	 returns 0 on success.
#	 returns number of failed ports on failure.
#	 returns -1 if the operation is unsupported
#
sub portControl ($$@) {
    my $self = shift;

    my $cmd = shift;
    my @ports = @_;

    $self->debug("portControl: $cmd -> (@ports)\n");

    #
    # Find the command in the %cmdOIDs hash (defined at the top of this file)
    #
    if (defined $cmdOIDs{$cmd}) {
	my @oid = @{$cmdOIDs{$cmd}};
	my $errors = 0;

	#
	# Convert the ports from the format they were given in to the format
	# required by the command
	#
	my $portFormat;
	if ($cmd =~ /(en)|(dis)able/) {
	    $portFormat = $PORT_FORMAT_IFINDEX;
	} else { 
	    $portFormat = $PORT_FORMAT_MODPORT;
	}
	my @portlist = $self->convertPortFormat($portFormat,@ports);

	#
	# Some commands involve multiple SNMP commands, so we need to make
	# sure we get all of them
	#
	while (@oid) {
	    my $myoid = shift @oid;
	    my $myval = shift @oid;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

            # 
            # We have to do some translation to a different mib for 2900
            # switches
            #
            if ($self->{SWITCHCLASS} == 2900) {
                if ($myoid eq "portAdminSpeed") {
                    $myoid = "c2900PortAdminSpeed";
                } elsif ($myoid eq "portDuplex") {
                    $myoid = "c2900PortDuplexState";
                    # Have to translate the value too
                    if ($myval eq "full") { $myval = "fullduplex"; }
                    elsif ($myval eq "half") { $myval = "halfduplex"; }
                    elsif ($myval eq "auto") { $myval = "autoNegotiate"; }
                }
            }

283 284 285 286
	    $errors += $self->UpdateField($myoid,$myval,@portlist);
	}
	return $errors;

Mac Newbold's avatar
Mac Newbold committed
287
    } else {
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
	#
	# Command not supported
	#
	print STDERR "Unsupported port control command '$cmd' ignored.\n";
	return -1;
    }
}

#
# Convert a set of ports to an alternate format. The input format is detected
# automatically. See the declarations of the constants at the top of this
# file for a description of the different port formats.
#
# usage: convertPortFormat($self, $output format, @ports)
#        returns a list of ports in the specified output format
#        returns undef if the output format is unknown
#
# TODO: Add debugging output, better comments, more sanity checking
#
sub convertPortFormat($$@) {
    my $self = shift;
    my $output = shift;
    my @ports = @_;


    #
    # Avoid warnings by exiting if no ports given
    # 
    if (!@ports) {
	return ();
    }

    #
    # We determine the type by sampling the first port given
    #
    my $sample = $ports[0];
324
    if (!defined($sample)) {
325 326 327 328 329 330 331 332
	warn "convertPortFormat: Given a bad list of ports\n";
	return undef;
    }

    my $input;
    SWITCH: for ($sample) {
	(/^\d+$/) && do { $input = $PORT_FORMAT_IFINDEX; last; };
	(/^\d+\.\d+$/) && do { $input = $PORT_FORMAT_MODPORT; last; };
Robert Ricci's avatar
Robert Ricci committed
333 334
	(/^$self->{NAME}\.\d+\/\d+$/) && do { $input = $PORT_FORMAT_MODPORT;
		@ports = map {/^$self->{NAME}\.(\d+)\/(\d+)$/; "$1.$2";} @ports; last; };
335 336 337 338 339 340 341
	$input = $PORT_FORMAT_NODEPORT; last;
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
342
	$self->debug("Not converting, input format = output format\n",2);
343 344 345 346 347
	return @ports;
    }

    if ($input == $PORT_FORMAT_IFINDEX) {
	if ($output == $PORT_FORMAT_MODPORT) {
348
	    $self->debug("Converting ifindex to modport\n",2);
349 350
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
351
	    $self->debug("Converting ifindex to nodeport\n",2);
352
	    return map portnum($self->{NAME}.":".$self->{IFINDEX}{$_}), @ports;
353
	}
354 355
    } elsif ($input == $PORT_FORMAT_MODPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
356
	    $self->debug("Converting modport to ifindex\n",2);
357 358
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
359 360
	    $self->debug("Converting modport to nodeport\n",2);
	    return map portnum($self->{NAME} . ":$_"), @ports;
361
	}
362 363
    } elsif ($input == $PORT_FORMAT_NODEPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
364
	    $self->debug("Converting nodeport to ifindex\n",2);
365 366
	    return map $self->{IFINDEX}{(split /:/,portnum($_))[1]}, @ports;
	} elsif ($output == $PORT_FORMAT_MODPORT) {
367
	    $self->debug("Converting nodeport to modport\n",2);
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
	    return map { (split /:/,portnum($_))[1] } @ports;
	}
    }

    #
    # Some combination we don't know how to handle
    #
    warn "convertPortFormat: Bad input/output combination ($input/$output)\n";
    return undef;

}

#
# Obtain a lock on the VLAN edit buffer. This must be done before VLANS
# are created or removed. Will retry 5 times before failing
#
# usage: vlanLock($self)
#        returns 1 on success
#        returns 0 on failure
#
sub vlanLock($) {
    my $self = shift;

    my $EditOp = 'vtpVlanEditOperation'; # use index 1
    my $BufferOwner = 'vtpVlanEditBufferOwner'; # use index 1

    #
395
    # Try max_tries times before we give up, in case some other process just
396 397
    # has it locked. NOTE: snmpitSetWarn is going to retry something like
    # 10 times, so we don't need to try the look _too_ many times.
398 399
    #
    my $tries = 1;
400
    my $max_tries = 10;
401
    while ($tries <= $max_tries) {
402 403 404 405
    
	#
	# Attempt to grab the edit buffer
	#
406 407
	my $grabBuffer = snmpitSetWarn($self->{SESS},
            [$EditOp,1,"copy","INTEGER"]);
408 409 410 411 412 413 414

	#
	# Check to see if we were sucessful
	#
	$self->debug("Buffer Request Set gave " .
		(defined($grabBuffer)?$grabBuffer:"undef.") . "\n");
	if (! $grabBuffer) {
415
	    #
416 417
	    # Only print this message if we've tried at least twice, to
            # cut down on error messages
418
	    #
419
	    if ($tries >= 2) {
420
		print STDERR "$self->{NAME}: VLAN edit buffer request failed - " .
421
			     "try $tries of $max_tries.\n";
422 423 424 425 426 427 428 429 430 431 432 433 434
                #
                # Try to find out who is holding the lock. Let's only try a
                # couple times, since if it's failing due to an unresponsive
                # switch, there's no point in sending a ton of these get
                # requests.
                #
                my $owner = snmpitGetWarn($self->{SESS}, [$BufferOwner, 1], 2);
                if ($owner) {
                    print STDERR "$self->{NAME}: VLAN lock is held by $owner\n";
                } else {
                    print STDERR "$self->{NAME}: No owner of the VLAN lock\n";
                }

435
	    }
436

437 438 439 440 441
	} else {
	    last;
	}
	$tries++;

442
	sleep(3);
443 444
    }

445
    if ($tries > $max_tries) {
446 447 448 449 450
	#
	# Admit defeat and exit
	#
	print STDERR "ERROR: Failed to obtain VLAN edit buffer lock\n";
	return 0;
451
    } else {
452 453 454 455 456
	#
	# Set the owner of the buffer to be the machine we're running on
	#
	my $me = `/usr/bin/uname -n`;
	chomp $me;
457
	snmpitSetWarn($self->{SESS},[$BufferOwner,1,$me,"OCTETSTR"]);
458 459

	return 1;
460
    }
461

Mac Newbold's avatar
Mac Newbold committed
462 463
}

464 465 466 467 468 469
#
# Release a lock on the VLAN edit buffer. As part of releasing, applies the
# VLAN edit buffer.
#
# usage: vlanUnlock($self)
#
470
sub vlanUnlock($) {
471 472
    my $self = shift;

473 474 475
    #
    # OIDs of the operations we'll be using in this function
    #
476 477
    my $EditOp = 'vtpVlanEditOperation'; # use index 1
    my $ApplyStatus = 'vtpVlanApplyStatus'; # use index 1
478 479 480 481 482 483 484

    print "    Applying VLAN changes on $self->{NAME} ...";

    #
    # Send the command to apply what's in the edit buffer
    #
    my $ApplyRetVal = snmpitSetWarn($self->{SESS},[$EditOp,1,"apply","INTEGER"]);
485 486 487 488
    if (!defined($ApplyRetVal)) {
        $self->debug("Apply set: '$ApplyRetVal'\n");
    } else {
        $self->debug("Apply returned undef\n");
489 490
    }

491
    if (!defined($ApplyRetVal) || $ApplyRetVal != 1) {
492
        print " FAILED\n";
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
	warn("**** ERROR: Failure attempting to apply VLAN changes ($ApplyRetVal)\n");
    } else {

        #
        # No point in trying to do this part if the switch rejected our request
        # to apply the edit buffer changes.
        #
        # Loop waiting for the switch to tell us that it's finished applying the
        # edits
        #
        $ApplyRetVal = snmpitGetWarn($self->{SESS},[$ApplyStatus,1]);
        if (!defined($ApplyRetVal)) {
            $self->debug("Apply set: '$ApplyRetVal'\n");
        } else {
            $self->debug("Apply returned undef\n");
        }
        while ($ApplyRetVal eq "inProgress") { 
            # Rate-limit our polling
            select(undef,undef,undef,.1);
            $ApplyRetVal = snmpitGetWarn($self->{SESS},[$ApplyStatus,1]);
            $self->debug("Apply gave $ApplyRetVal\n");
            print ".";
        }

        #
        # Tell the caller what happened
        #
        if ($ApplyRetVal ne "succeeded") {
            print " FAILED\n";
            warn("**** ERROR: Failure applying VLAN changes: $ApplyRetVal\n");
        } else { 
            print " Succeeded\n";
            $self->debug("Apply Succeeded.\n");
        }
527
    }
528 529 530 531 532 533 534 535 536 537 538 539

    #
    # Try to release the lock, even if the previous part failed - we don't
    # want to keep holding it
    #
    my $snmpvar = [$EditOp,1,"release",'INTEGER'];
    my $RetVal = snmpitSetWarn($self->{SESS},$snmpvar);
    if (! $RetVal ) {
        warn("*** ERROR: Failed to unlock VLAN edit buffer\n");
        return 0;
    }
    $self->debug("Release: '$RetVal'\n");
540 541
    
    return $ApplyRetVal;
Mac Newbold's avatar
Mac Newbold committed
542 543
}

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
# 
# Check to see if the given (cisco-specific) VLAN number exists on the switch
#
# usage: vlanNumberExists($self, $vlan_number)
#        returns 1 if the VLAN exists, 0 otherwise
#
sub vlanNumberExists($$) {
    my $self = shift;
    my $vlan_number = shift;

    my $VlanName = "vtpVlanName";

    #
    # Just look up the name for this VLAN, and see if we get an answer back
    # or not
    #
560
    my $rv = snmpitGetWarn($self->{SESS},[$VlanName,"1.$vlan_number"]);
Robert Ricci's avatar
Robert Ricci committed
561
    if (!$rv or $rv eq "NOSUCHINSTANCE") {
562 563 564 565 566 567
	return 0;
    } else {
    	return 1;
    }
}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
#
# Given VLAN indentifiers from the database, finds the cisco-specific VLAN
# number for them. If not VLAN id is given, returns mappings for the entire
# switch.
# 
# usage: findVlans($self, @vlan_ids)
#        returns a hash mapping VLAN ids to Cisco VLAN numbers
#        any VLANs not found have NULL VLAN numbers
#
sub findVlans($@) { 
    my $self = shift;
    my @vlan_ids = @_;

    my $VlanName = "vtpVlanName"; # index by 1.vlan #

    #
    # Walk the tree to find the VLAN names
    # TODO - we could optimize a bit, since, if we find all VLAN, we can stop
    # looking, potentially saving us a lot of time. But, it would require a
    # more complex walk.
    #
    my %mapping = ();
    @mapping{@vlan_ids} = undef;
591
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},[$VlanName]);
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
    foreach my $rowref (@$rows) {
	my ($name,$vlan_number,$vlan_name) = @$rowref;
	#
	# We get the VLAN number in the form 1.number - we need to strip
	# off the '1.' to make it useful
	#
	$vlan_number =~ s/^1\.//;

	$self->debug("Got $name $vlan_number $vlan_name\n",2);
	if (!@vlan_ids || exists $mapping{$vlan_name}) {
	    $self->debug("Putting in mapping from $vlan_name to $vlan_number\n",2);
	    $mapping{$vlan_name} = $vlan_number;
	}
    }

    return %mapping;
}

610 611
#
# Given a VLAN identifier from the database, find the cisco-specific VLAN
612 613
# number that is assigned to that VLAN. Retries several times (to account
# for propagation delays) unless the $no_retry option is given.
614
#
615
# usage: findVlan($self, $vlan_id,$no_retry)
616 617 618
#        returns the VLAN number for the given vlan_id if it exists
#        returns undef if the VLAN id is not found
#
619
sub findVlan($$;$) { 
620 621
    my $self = shift;
    my $vlan_id = shift;
622 623 624 625 626 627 628 629
    my $no_retry = shift;

    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
    } else {
	$max_tries = 10;
    }
630 631

    #
632 633
    # We try this a few time, with 1 second sleeps, since it can take
    # a while for VLAN information to propagate
634
    #
635 636
    foreach my $try (1 .. $max_tries) {

637 638 639
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
640 641
	}

642 643 644
	#
	# Wait before we try again
	#
645 646 647 648
	if ($try != $max_tries) {
	    $self->debug("VLAN find failed, trying again\n");
	    sleep 1;
	}
649
    }
650 651 652 653
    #
    # Didn't find it
    #
    return undef;
Mac Newbold's avatar
Mac Newbold committed
654 655
}

656 657
#
# Create a VLAN on this switch, with the given identifier (which comes from
658 659
# the database.) If $vlan_number is given, attempts to use it when creating
# the vlan - otherwise, picks its own Cisco-specific VLAN number.
660
#
661 662
# usage: createVlan($self, $vlan_id, $vlan_number, [,$private_type
# 		[,$private_primary, $private_port]])
663
#        returns the new VLAN number on success
664
#        returns 0 on failure
Robert Ricci's avatar
Robert Ricci committed
665 666 667
#        if $private_type is given, creates a private VLAN - if private_type
#        is 'community' or 'isolated', then the assocated primary VLAN and
#        promiscous port must also be given
668
#
Robert Ricci's avatar
Robert Ricci committed
669
sub createVlan($$;$$$) {
670 671
    my $self = shift;
    my $vlan_id = shift;
672
    my $vlan_number = shift;
673

Robert Ricci's avatar
Robert Ricci committed
674 675 676 677 678 679 680 681 682 683
    my ($private_type,$private_primary,$private_port);
    if (@_) {
	$private_type = shift;
	if ($private_type ne "primary") {
	    $private_primary = shift;
	    $private_port = shift;
	}
    } else {
	$private_type = "normal";
    }
684

Robert Ricci's avatar
Robert Ricci committed
685 686 687 688 689 690 691

    my $okay = 1;

    my $VlanType = 'vtpVlanEditType'; # vlan # is index
    my $VlanName = 'vtpVlanEditName'; # vlan # is index
    my $VlanSAID = 'vtpVlanEditDot10Said'; # vlan # is index
    my $VlanRowStatus = 'vtpVlanEditRowStatus'; # vlan # is index
692

693
    #
Robert Ricci's avatar
Robert Ricci committed
694
    # If they gave a VLAN number, make sure it doesn't exist
695 696 697 698 699 700 701 702
    #
    if ($vlan_number) {
	if ($self->vlanNumberExists($vlan_number)) {
	    print STDERR "ERROR: VLAN $vlan_number already exists\n";
	    return 0;
	}
    }
    
703
    #
704 705 706 707
    # We may have to do this multiple times - a few times, we've had the
    # Cisco give no errors, but fail to actually create the VLAN. So, we'll
    # make sure it gets created, and retry if it did not. Of course, we don't
    # want to try forever, though....
708
    #
709 710 711
    my $max_tries = 3;
    my $tries_remaining = $max_tries;
    while ($tries_remaining) {
712
	#
713
	# Try to wait out transient failures
714
	#
715 716 717 718 719 720
	if ($tries_remaining != $max_tries) {
	    print STDERR "VLAN creation failed, trying again " .
		"($tries_remaining tries left)\n";
	    sleep 5;
	}
	$tries_remaining--;
721

722 723 724
	if (!$self->vlanLock()) {
	    next;
	}
725

726
	if (!$vlan_number) {
727
	    #
728 729
	    # Find a free VLAN number to use. Get a list of all VLANs on the
            # switch, then look through for a free one
730
	    #
731 732 733 734 735 736 737 738 739 740 741 742 743 744
            my %vlan_mappings = $self->findVlans();

            #
            # Convert the mapping to a form we can use
            #
            my @vlan_numbers = values(%vlan_mappings);
            my @taken_vlans;
            foreach my $num (@vlan_numbers) {
                $taken_vlans[$num] = 1;
            }

            #
            # Pick a VLAN number
            #
745
	    $vlan_number = $self->{MIN_VLAN};
746 747 748
            while ($taken_vlans[$vlan_number]) {
                $vlan_number++;
            }
749
	    if ($vlan_number > $self->{MAX_VLAN}) {
750 751 752 753 754 755
		#
		# We must have failed to find one
		#
		print STDERR "ERROR: Failed to find a free VLAN number\n";
		next;
	    }
756
	}
757

758
	$self->debug("Using Row $vlan_number\n");
759

760 761 762 763 764
	#
	# SAID is a funky security identifier that _must_ be set for VLAN
	# creation to suceeed.
	#
	my $SAID = pack("H*",sprintf("%08x",$vlan_number + 100000));
765

766 767
	print "  Creating VLAN $vlan_id as VLAN #$vlan_number on " .
		"$self->{NAME} ... ";
768 769 770 771 772

	#
	# Perform the actual creation. Yes, this next line MUST happen all in
	# one set command....
	#
773 774
	my $RetVal = snmpitSetWarn($self->{SESS},
               [[$VlanRowStatus,"1.$vlan_number", "createAndGo","INTEGER"],
Robert Ricci's avatar
Robert Ricci committed
775 776 777
		[$VlanType,"1.$vlan_number","ethernet","INTEGER"],
		[$VlanName,"1.$vlan_number",$vlan_id,"OCTETSTR"],
		[$VlanSAID,"1.$vlan_number",$SAID,"OCTETSTR"]]);
778 779 780 781 782 783 784 785
	print "",($RetVal? "Succeeded":"Failed"), ".\n";

	#
	# Check for success
	#
	if (!$RetVal) {
	    print STDERR "VLAN Create '$vlan_id' as VLAN $vlan_number " .
		    "failed.\n";
Robert Ricci's avatar
Robert Ricci committed
786
	    $self->vlanUnlock();
787 788
	    next;
	} else {
Robert Ricci's avatar
Robert Ricci committed
789 790 791 792 793 794 795 796 797 798
	    #
	    # Handle private VLANs - Part I: Stuff that has to be done while we
	    # have the edit buffer locked
	    #
	    if ($self->{SUPPORTS_PRIVATE} && $private_type ne "normal") {
		#
		# First, set the private VLAN type
		#
		my $PVlanType = "cpvlanVlanEditPrivateVlanType";
		print "    Setting private VLAN type to $private_type ... ";
799 800
		$RetVal = snmpitSetWarn($self->{SESS},
                    [$PVlanType,"1.$vlan_number",$private_type, 'INTEGER']);
Robert Ricci's avatar
Robert Ricci committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
		print "",($RetVal? "Succeeded":"Failed"), ".\n";
		if (!$RetVal) {
		    $okay = 0;
		}
		if ($okay) {
		    #
		    # Now, if this isn't a primary VLAN, associate it with its
		    # primary VLAN
		    #
		    if ($private_type ne "primary") {
			my $PVlanAssoc = "cpvlanVlanEditAssocPrimaryVlan";
			my $primary_number = $self->findVlan($private_primary);
			if (!$primary_number) {
			    print "    **** Error - Primary VLAN " .
			    	"$private_primary could not be found\n";
			    $okay = 0;
			} else {
			    print "    Associating with $private_primary (#$primary_number) ... ";
819 820 821
			    $RetVal = snmpitSetWarn($self->{SESS},
                                [$PVlanAssoc,"1.$vlan_number",
                                 $primary_number,"INTEGER"]);
Robert Ricci's avatar
Robert Ricci committed
822 823 824 825 826 827 828 829 830
			    print "", ($RetVal? "Succeeded":"Failed"), ".\n";
			    if (!$RetVal) {
				$okay = 0;
			    }
			}
		    }
		}
	    }

831 832 833 834 835 836 837 838 839 840 841 842 843
	    $RetVal = $self->vlanUnlock();
	    $self->debug("Got $RetVal from vlanUnlock\n");

	    #
	    # Unfortunately, there are some rare circumstances in which it
	    # seems that we can't trust the switch to tell us the truth.
	    # So, let's use findVlan to see if it really got created.
	    #
	    if (!$self->findVlan($vlan_id)) {
		print STDERR "*** Switch reported success, but VLAN did not " .
			     "get created - trying again\n";
		next;	     
	    }
Robert Ricci's avatar
Robert Ricci committed
844 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
	    if ($self->{SUPPORTS_PRIVATE} && $private_type ne "normal" &&
		$private_type ne "primary") {

		#
		# Handle private VLANs - Part II: Set up the promiscuous port -
		# this has to be done after we release the edit buffer
		#

		my $SecondaryPort = 'cpvlanPromPortSecondaryRemap';

		my ($ifIndex) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,
		    $private_port);

		if (!$ifIndex) {
		    print STDERR "    **** ERROR - unable to find promiscous " .
			"port $private_port!\n";
		    $okay = 0;
		}

		if ($okay) {
		    print "    Setting promiscuous port to $private_port ... ";

		    #
		    # Get the existing bitfield used to maintain the mapping
		    # for the port
		    #
870 871
		    my $bitfield = snmpitGetFatal($self->{SESS},
                        [$SecondaryPort,$ifIndex]);
Robert Ricci's avatar
Robert Ricci committed
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
		    my $unpacked = unpack("B*",$bitfield);

		    #
		    # Put this into an array of 1s and 0s for easy manipulation
		    # We have to pad this out to 128 bits, because it's given
		    # back as the empty string if no bits are set yet.
		    #
		    my @bits = split //,$unpacked;
		    foreach my $bit (0 .. 127) {
			if (!defined $bits[$bit]) {
			    $bits[$bit] = 0;
			}
		    }

		    $bits[$vlan_number] = 1;

		    # Pack it back up...
		    $unpacked = join('',@bits);

		    $bitfield = pack("B*",$unpacked);

		    # And save it back...
894 895
		    $RetVal = snmpitSetFatal($self->{SESS},
                        [$SecondaryPort,$ifIndex,$bitfield, "OCTETSTR"]);
Robert Ricci's avatar
Robert Ricci committed
896 897 898 899
		    print "", ($RetVal? "Succeeded":"Failed"), ".\n";

		}
	    }
900 901 902 903 904
	    if ($okay) {
		return $vlan_number;
	    } else {
		return 0;
	    }
905
	}
906
    }
907 908 909 910

    print STDERR "*** Failed to create VLAN $vlan_id after $max_tries tries " .
		 "- giving up\n";
    return 0;
911 912 913
}

#
914 915
# Put the given ports in the given VLAN. The VLAN is given as a cisco-specific
# VLAN number
916
#
917
# usage: setPortVlan($self, $vlan_number, @ports)
918 919 920 921 922
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub setPortVlan($$@) {
    my $self = shift;
923
    my $vlan_number = shift;
924 925 926 927
    my @ports = @_;

    my $errors = 0;

928
    if (!$self->vlanNumberExists($vlan_number)) {
929 930
	print STDERR "ERROR: VLAN $vlan_number does not exist on switch"
	. $self->{NAME} . "\n";
931 932 933 934
	return 1;
    }

    #
Robert Ricci's avatar
Robert Ricci committed
935 936
    # If this switch supports private VLANs, check to see if the VLAN we're
    # putting it into is a secondary private VLAN
937
    #
Robert Ricci's avatar
Robert Ricci committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    my $privateVlan = 0;
    if ($self->{SUPPORTS_PRIVATE}) {
	$self->debug("Checking to see if vlan is private ... ");
	my $PrivateType = "cpvlanVlanPrivateVlanType";
	my $type = snmpitGetFatal($self->{SESS},[$PrivateType,"1.$vlan_number"]);
	$self->debug("type is $type ... ");
	if ($type eq "community" ||  $type eq "isolated") {
	    $self->debug("It is\n");
	    $privateVlan = 1;
	} else {
	    $self->debug("It isn't\n");
	}
    }

    my $PortVlanMemb;
953 954
    my $format;
    if ($self->{OSTYPE} eq "CatOS") {
Robert Ricci's avatar
Robert Ricci committed
955 956 957 958 959 960 961
	if (!$privateVlan) {
	    $PortVlanMemb = "vlanPortVlan"; #index is ifIndex
	    $format = $PORT_FORMAT_MODPORT;
	} else {
	    $PortVlanMemb = "cpvlanPrivatePortSecondaryVlan";
	    $format = $PORT_FORMAT_IFINDEX;
	}
962
    } elsif ($self->{OSTYPE} eq "IOS") {
Robert Ricci's avatar
Robert Ricci committed
963
	$PortVlanMemb = "vmVlan"; #index is ifIndex
964 965 966
	$format = $PORT_FORMAT_IFINDEX;
    }

967 968 969 970 971
    #
    # We'll keep track of which ports suceeded, so that we don't try to
    # enable/disable, etc. ports that failed.
    #
    my @okports = ();
972 973
    my ($index, $retval);
    my %BumpedVlans = ();
974

975 976 977 978
    foreach my $port (@ports) {
	$self->debug("Putting port $port in VLAN $vlan_number\n");
	#
	# Check to see if it's a trunk ....
979
	#
980 981 982 983
	($index) = $self->convertPortFormat($PORT_FORMAT_IFINDEX, $port);
	$retval = snmpitGetWarn($self->{SESS},
			["vlanTrunkPortDynamicState",$index]);
	if (!$retval) {
984 985 986
	    $errors++;
	    next;
	}
987 988 989 990 991
	if (!(($retval eq "on") || ($retval eq "onNoNegotiate"))) {
	    #
	    # Convert ports to the correct format
	    #
	    ($index) = $self->convertPortFormat($format, $port);
992

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	    # 
	    # Make sure the port didn't get mangled in conversion
	    #
	    if (!defined $index) {
		print STDERR "Port not found, skipping\n";
		$errors++;
		next;
	    }
	    my $snmpvar = [$PortVlanMemb,$index,$vlan_number,'INTEGER'];
	    #
	    # Check to see if we are already in a VLAN
	    #
	    $retval = snmpitGet($self->{SESS},[$PortVlanMemb,$index]);
	    if (($retval ne "NOSUCHINSTANCE") &&
		("$retval" ne "$vlan_number") && ("$retval" ne "1")) {
		$BumpedVlans{$retval} = 1;
	    }
	    #
	    # Do the acutal SNMP command
	    #
	    $retval = snmpitSetWarn($self->{SESS},$snmpvar);
	} else {
	    #
	    # We're here if it a trunk
	    #
	    $retval = $self->setVlansOnTrunk($port, 1, $vlan_number);
	}
1020
	if (!$retval) {
1021 1022
	    $errors++;
	    next;
Mac Newbold's avatar
Mac Newbold committed
1023
	} else {
1024
	    push @okports, $port;
Mac Newbold's avatar
Mac Newbold committed
1025
	}
1026 1027 1028 1029 1030 1031 1032
    }

    #
    # Ports going into VLAN 1 are being taken out of circulation, so we
    # disable them. Otherwise, we need to make sure they get enabled.
    #
    if ($vlan_number == 1) {
1033 1034
	$self->debug("Disabling " . join(',',@okports) . "...");
	if ( my $rv = $self->portControl("disable",@okports) ) {
1035 1036 1037 1038
	    print STDERR "Port disable had $rv failures.\n";
	    $errors += $rv;
	}
    } else {
1039 1040
	$self->debug("Enabling "  . join(',',@okports) . "...");
	if ( my $rv = $self->portControl("enable",@okports) ) {
1041 1042 1043 1044
	    print STDERR "Port enable had $rv failures.\n";
	    $errors += $rv;
	}
    }
Mac Newbold's avatar
Mac Newbold committed
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054
    # When removing things from the control vlan for a firewall,
    # need to tell stack to shake things up to flush FDB on neighboring
    # switches.
    #
    my @bumpedlist = keys ( %BumpedVlans );
    if (@bumpedlist) {
	@{$self->{DISPLACED_VLANS}} = @bumpedlist;
    }

1055
    return $errors;
1056 1057
}

1058
#
1059 1060
# Remove all ports from the given VLANs, which are given as Cisco-specific
# VLAN numbers
1061
#
1062
# usage: removePortsFromVlan(self,int vlans)
1063 1064 1065
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
1066
sub removePortsFromVlan($@) {
1067
    my $self = shift;
1068
    my @vlan_numbers = @_;
1069 1070

    #
1071
    # Make sure the VLANs actually exist
1072
    #
1073 1074 1075
    foreach my $vlan_number (@vlan_numbers) {
	if (!$self->vlanNumberExists($vlan_number)) {
	    print STDERR "ERROR: VLAN $vlan_number does not exist\n";
1076 1077
	    return 1;
	}
1078 1079
    }

1080 1081 1082 1083
    #
    # Make a hash of the vlan number for easy lookup later
    #
    my %vlan_numbers = ();
1084
    @vlan_numbers{@vlan_numbers} = @vlan_numbers;
1085

1086 1087 1088
    #
    # Get a list of the ports in the VLAN
    #
1089 1090 1091 1092 1093 1094
    my $VlanPortVlan;
    if ($self->{OSTYPE} eq "CatOS") {
	$VlanPortVlan = "vlanPortVlan"; #index is ifIndex
    } elsif ($self->{OSTYPE} eq "IOS") {
	$VlanPortVlan = "vmVlan"; #index is ifIndex
    }
1095
    my @ports;
1096 1097 1098 1099

    #
    # Walk the tree to find VLAN membership
    #
1100
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},[$VlanPortVlan]);
1101
    foreach my $rowref (@$rows) {
1102 1103 1104
	my ($name,$modport,$port_vlan_number) = @$rowref;
	$self->debug("Got $name $modport $port_vlan_number\n");
	if ($vlan_numbers{$port_vlan_number}) {
1105
	    push @ports, $modport;
Mac Newbold's avatar
Mac Newbold committed
1106 1107 1108
	}
    }

1109 1110
    $self->debug("About to remove ports " . join(",",@ports) . "\n");
    if (@ports) {
1111
	return $self->setPortVlan(1,@ports);
Mac Newbold's avatar
Mac Newbold committed
1112
    } else {
1113
	return 0;
Mac Newbold's avatar
Mac Newbold committed
1114
    }
1115 1116 1117 1118 1119
}

#
# Remove the given VLAN from this switch. This presupposes that all of its
# ports have already been removed with removePortsFromVlan(). The VLAN is
1120
# given as a Cisco-specific VLAN number
1121 1122 1123 1124 1125 1126
#
# usage: removeVlan(self,int vlan)
#	 returns 1 on success
#	 returns 0 on failure
#
#
1127
sub removeVlan($@) {
1128
    my $self = shift;
1129
    my @vlan_numbers = @_;
1130

1131 1132
    my $errors = 0;

1133
    foreach my $vlan_number (@vlan_numbers) {
Robert Ricci's avatar