snmpit_force10.pm 59.1 KB
Newer Older
1 2 3
#!/usr/bin/perl -w

#
4 5
# Copyright (c) 2013,2014 University of Utah and the Flux Group.
# Copyright (c) 2006-2014 Universiteit Gent/iMinds, Belgium.
Kirk Webb's avatar
Kirk Webb committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Copyright (c) 2004-2006 Regents, University of California.
# 
# {{{EMULAB-LGPL
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
# License for more details.
# 
# You should have received a copy of the GNU Lesser General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
26 27 28
#

#
Kirk Webb's avatar
Kirk Webb committed
29
# snmpit module for Force10 switches
30 31 32 33
#

package snmpit_force10;
use strict;
34
use Data::Dumper;
35 36 37 38 39 40

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

use English;
use SNMP;
use snmpit_lib;
41
use Port;
42
use force10_expect;
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

#
# These are the commands that can be passed to the portControl function
# below
#
my %cmdOIDs =
(
	"enable"  => ["ifAdminStatus","up"],
	"disable" => ["ifAdminStatus","down"],
);

#
# Force10 Chassis configuration info
#
my $ChassisInfo = {
    "force10c300" => {
        "moduleSlots"           => 8,   # Max # of modules in chassis
        "maxPortsPerModule"     => 48,  # Max # of ports in any module
        "bitmaskBitsPerModule"  => 224, # Number of bits per module
    },
    "force10e1200" => {
        "moduleSlots"           => 14,  # Max # of modules in chassis
        "maxPortsPerModule"     => 48,  # Max # of ports in any module
        "bitmaskBitsPerModule"  => 96,  # Number of bits per module
    },
68 69
    "force10s55" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
70 71
        "maxPortsPerModule"     => 64,  # Max # of ports in any module
        "bitmaskBitsPerModule"  => 768, # Number of bits per module
72
    },
73 74 75
    "force10-z9000" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
        "maxPortsPerModule"     => 128, # Max # of ports in any module
76
        "bitmaskBitsPerModule"  => 1024, # Number of bits per module
77
    },
78 79 80 81 82
    "force10-s6000" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
        "maxPortsPerModule"     => 128, # Max # of ports in any module
        "bitmaskBitsPerModule"  => 1024, # Number of bits per module
    },
83 84 85
};

#
86 87 88
# FTOS does not allow purely numeric administrative VLAN names
# (dot1qVlanStaticName) (by design...)  So we prepend some
# alphabetical characters when setting, end strip them when getting
89 90 91
#
my $vlanStaticNamePrefix = "emuID";

92 93 94 95
# Enterprise OIDs for port aggregations
my $OID_AGGINDEX = ".1.3.6.1.4.1.6027.3.2.1.1.1.1.3";
my $OID_AGGPLIST = ".1.3.6.1.4.1.6027.3.2.1.1.1.1.6";

96 97 98 99 100 101 102 103 104 105 106 107 108 109
#
# Ports can be passed around in three formats:
# ifindex : positive integer corresponding to the interface index
#           (eg. 311476282 for gi 8/35)
# modport : dotted module.port format, following the physical reality of
#           Force10 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;
110
my $PORT_FORMAT_PORT     = 3;
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

#
# Creates a new object.
#
# usage: new($classname,$devicename,$debuglevel,$community)
#        returns a new object, blessed into the snmpit_force10 class.
#
sub new($$$;$) {

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

    my $name = shift;                       # the name of the switch, e.g. e1200a
    my $debugLevel = shift;
    my $community = shift;

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

    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
		$self->{DEBUG} = $debugLevel;
    } else {
		$self->{DEBUG} = 0;
    }
    $self->{BLOCK} = 1;
    $self->{CONFIRM} = 1;
    $self->{NAME} = $name;

145 146 147
    # List of ports in trunk mode - used as a secondary check.
    $self->{TRUNKS} = {};

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    #
    # 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->{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'};
    }

    #
    # Get devicetype from database
    #
    my $devicetype = getDeviceType($self->{NAME});
    $self->{TYPE}=$devicetype;

172 173 174 175
    # Dynamically determined size of vlan PortSet bit vectors 
    # (see bottom of readifIndex()).
    $self->{PORTSET_NUMBYTES} = 0; 

176 177 178 179 180
    #
    # set up hashes for pending vlans
    #
    $self->{IFINDEX} = {};     # Used for converting modport to ifIndex (somtimes called iid; e.g. 345555002) and vice versa
    $self->{PORTINDEX} = {};   # Will contain elements for experimental "interfaces" only (no VLANs, no Mgmgnt ifaces); format: ifIndex => ifDescr
181
    $self->{POIFINDEX} = {};   # Port channel ifindex map.
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

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


    #
    # 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);
    &SNMP::addMibFiles("$mibpath/SNMPv2-SMI.txt", "$mibpath/SNMPv2-TC.txt", 
	               "$mibpath/SNMPv2-MIB.txt", "$mibpath/IANAifType-MIB.txt",
		       "$mibpath/IF-MIB.txt",
		       "$mibpath/SNMP-FRAMEWORK-MIB.txt",
		       "$mibpath/SNMPv2-CONF.txt",
		       "$mibpath/BRIDGE-MIB.txt",
		       "$mibpath/P-BRIDGE-MIB.txt",
201 202
		       "$mibpath/Q-BRIDGE-MIB.txt",
		       "$mibpath/EtherLike-MIB.txt");
203 204 205 206 207 208
    $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});

209 210 211
    $self->{SESS} = new SNMP::Session(DestHost => $self->{NAME},Version => '2c',
				      Timeout => 4000000, Retries=> 12,
				      Community => $self->{COMMUNITY});
212 213 214 215 216

    if (!$self->{SESS}) {
	#
	# Bomb out if the session could not be established
	#
217 218
	warn "ERROR: Unable to connect via SNMP to $self->{NAME}\n";
	return undef;
219 220
    }

221 222
    # Grab our expect object (Ugh... Why Force10, why?)
    # This does not immediately connect to the switch.
223 224
    if (exists($options->{"username"}) && exists($options->{"password"})) {
	my $swcreds = $options->{"username"} . ":" . $options->{"password"};
225 226 227 228 229 230 231 232 233 234 235
	$self->{EXP_OBJ} = force10_expect->new($self->{NAME},$debugLevel,
					       $swcreds);
	if (!$self->{EXP_OBJ}) {
	    warn "Could not create Expect object for $self->{NAME}\n";
	    return undef;
	}
    } else {
	warn "WARNING: No credentials found for force10 switch $self->{NAME}\n";
	warn "\tPortchannel manipulation will not be possible!\n";
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249
    #
    # 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};

    #
    # The bless needs to occur before readifIndex(), since it's a class 
    # method
    #
    bless($self,$class);

250
    if (!$self->readifIndex()) {
Kirk Webb's avatar
Kirk Webb committed
251
	warn "ERROR: Unable to process ifindex table on $self->{NAME}\n";
252 253
	return undef;
    }
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    
    return $self;
}

#
# Prints out a debugging message, but only if debugging is on. If a level is
# given, the debuglevel must be >= that level for the message to print. If
# the level is omitted, 1 is assumed
#
# Usage: debug($self, $message, $level)
#
sub debug($$;$) {
    my $self = shift;
    my $string = shift;
    my $debuglevel = shift;
    if (!(defined $debuglevel)) {
	    $debuglevel = 1;
    }
    if ($self->{DEBUG} >= $debuglevel) {
	    print STDERR $string;
    }
}

277 278 279
##############################################################################
## Internal / Utility Functions Section
##
280 281 282 283 284 285 286 287 288 289

#
# Reads the IfIndex table from the switch, for SNMP functions that use 
# IfIndex rather than the module.port style. Fills out the objects IFINDEX
# and PORTINDEX members
#
# usage: readifIndex(self)
#        returns nothing but sets instance variable IFINDEX
#
sub readifIndex($) {
290
    my $self = shift;
291
    my $vlan1ifIndex = 0;
Kirk Webb's avatar
Kirk Webb committed
292 293
    my $id = "$self->{NAME}::readifIndex()";
    $self->debug("$id:\n",2);
294
        
295
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},["ifDescr"]);
296
    
297
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
298 299
	warn "$id: ERROR: No interface description rows returned ".
	     "while attempting to build ifindex table.\n";
300 301
	return 0;
    }
302

303
    foreach my $result (@{$rows}) {
304
	my ($name,$iid,$descr) = @{$result};
305
	$self->debug("got $name, $iid, descr $descr\n",2);
306
	if ($name ne "ifDescr") {
Kirk Webb's avatar
Kirk Webb committed
307
	    warn "$id: WARNING: Foreign snmp var returned: $name";
308 309 310 311
	    return 0;
	}
	
	# will match "GigabitEthernet 9/47" but not "Vlan 123"
312
	if ($descr =~ /(\w*)\s*(\d+)\/(\d+)\/?(\d+)?$/) {
313 314
	    my $type = $1;
	    my $module = $2;
315
	    my $port = defined($4) ? $4 : $3;
316
	    # Note: Force10 modules and ports start at 0 instead of 1.
317
	    my $modport = "${module}.${port}";
318 319 320 321 322 323 324 325 326
	    my $ifIndex = $iid;
	    
	    # exclude e.g. ManagementEthernet ports
	    if ( $descr !~ /management/i) {
		$self->{IFINDEX}{$modport} = $ifIndex;
		$self->{IFINDEX}{$ifIndex} = $modport;
		$self->{PORTINDEX}{$ifIndex} = $descr;
		$self->debug("mod $module, port $port, modport $modport, descr $descr\n",2);
	    }
327
	}
328 329 330 331 332 333 334
	elsif ($descr =~ /port-channel (\d+)/i) {
	    my $ifIndex = $iid;
	    my $poNum = $1;
	    $self->{POIFINDEX}{$ifIndex} = "Po$poNum";
	    $self->{POIFINDEX}{"Po$poNum"} = $ifIndex;
	    $self->debug("Port-channel $poNum, ifindex $ifIndex\n",2);
	}
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	elsif ($descr =~ /vlan 1/i) {
	    # Used below to dynamically determine switch's PortSet size.
	    $vlan1ifIndex = $iid;
	}
    }

    # Figure out the size of the vlan PortSet bit vectors.
    if ($vlan1ifIndex) {
	my $pset = $self->getMemberBitmask($vlan1ifIndex);
	if ($pset) {
	    $self->{PORTSET_NUMBYTES} = length($pset);
	    $self->debug("$id: Detected PortSet bit vector size (in bytes):".
			 " $self->{PORTSET_NUMBYTES}\n");
	} else {
	    warn "$id: Unable to fetch egress membership PortSet for Vlan 1".
		 " - can't determine PortSet size!\n";
	    return 0;
	}
    } else {
	warn "$id: Unable to find ifIndex for Vlan 1 - can't determine ".
	     "PortSet size!\n";
	return 0;
357 358 359 360
    }

    # success
    return 1;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
}

#
# 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 = @_;
Kirk Webb's avatar
Kirk Webb committed
378
    my $id = "$self->{NAME}::convertPortFormat()";
379 380 381 382 383 384 385 386 387 388 389 390 391

    #
    # 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];
    if (!defined($sample)) {
Kirk Webb's avatar
Kirk Webb committed
392
		warn "$id: ERROR: Given a bad list of ports\n";
393 394 395 396 397
		return undef;
    }

    my $input;
    SWITCH: for ($sample) {
398 399 400
	(Port->isPort($_)) && do { $input = $PORT_FORMAT_PORT; last; };
	(/^\d+$/) && do { $input = $PORT_FORMAT_IFINDEX; last; };
	(/^\d+\.\d+$/) && do { $input = $PORT_FORMAT_MODPORT; last; };
Kirk Webb's avatar
Kirk Webb committed
401
	warn "$id: ERROR: Unrecognized input sample: $sample\n";
402
	return undef;
403 404 405 406 407 408
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
409 410
	$self->debug("Not converting, input format = output format\n",2);
	return @ports;
411 412 413
    }

    if ($input == $PORT_FORMAT_IFINDEX) {
414 415 416 417 418 419 420 421 422 423
	if ($output == $PORT_FORMAT_MODPORT) {
	    $self->debug("Converting ifindex to modport\n",2);
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_PORT) {
	    $self->debug("Converting ifindex to Port\n",2);
	    return map {Port->LookupByStringForced(
			    Port->Tokens2TripleString(
				$self->{NAME},
				split(/\./,$self->{IFINDEX}{$_})))} @ports;
	}
424
    } elsif ($input == $PORT_FORMAT_MODPORT) {
425 426 427 428 429 430 431 432 433 434 435 436 437
	if ($output == $PORT_FORMAT_IFINDEX) {
	    $self->debug("Converting modport to ifindex\n",2);
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_PORT) {
	    $self->debug("Converting modport to Port\n",2);
	    return map {Port->LookupByStringForced(
			    Port->Tokens2TripleString(
				$self->{NAME},
				split(/\./,$_)))} @ports;
	}
    } elsif ($input == $PORT_FORMAT_PORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
	    $self->debug("Converting Port to ifindex\n",2);
Kirk Webb's avatar
Kirk Webb committed
438 439
	    return map $self->{IFINDEX}{$_->switch_card() .".". 
					$_->switch_port()}, @ports;
440 441
	} elsif ($output == $PORT_FORMAT_MODPORT) {
	    $self->debug("Converting Port to modport\n",2);
Kirk Webb's avatar
Kirk Webb committed
442
	    return map $_->switch_card() .".". $_->switch_port(), @ports;
443
	}
444 445 446 447 448
    }

    #
    # Some combination we don't know how to handle
    #
Kirk Webb's avatar
Kirk Webb committed
449
    warn "$id: ERROR: Bad input/output combination ($input/$output)\n";
450 451 452
    return undef;
}

453 454 455 456 457 458 459
#
# Internal function which converts a bitmask (a binary string) to a list 
# of switch ports (ifIndexes)
#
sub convertBitmaskToIfindexes($$) {
    my $self = shift;
    my $bitmask = shift;
Kirk Webb's avatar
Kirk Webb committed
460
    my $id = "$self->{NAME}::convertBitmaskToIfindexes()";
461 462 463 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

    # Store switch config in local vars for code readability
    my $type                 = $self->{TYPE};
    my $moduleSlots          = $ChassisInfo->{$type}->{moduleSlots};
    my $maxPortsPerModule    = $ChassisInfo->{$type}->{maxPortsPerModule};
    my $bitmaskBitsPerModule = $ChassisInfo->{$type}->{bitmaskBitsPerModule};

    my @ifIndexes;
                                                          
    # start at module 0
    my $mod = 0;                                          
    while ($mod < $moduleSlots) {
        # start at port 0
        my $port = 0;

        # loop over until maxports.  Not usefull to loop over
        # the padding bits, cause some switches use _a lot_ of
        # these bits !!
        while ($port < $maxPortsPerModule) {

            my $offset = 
                # start index for first port of the module
                $mod * $bitmaskBitsPerModule
                # start index for first port of the block of 8
                # ports containing the current port
                + (int($port / 8) * 8)
                # the offset we're actually looking for
                + (7 - ($port % 8));

            if ( vec($bitmask,$offset,1) ) { 
                push @ifIndexes, $self->{IFINDEX}{"${mod}.${port}"};
            }
            $port++;
        }
        $mod++;
    }

    return \@ifIndexes;
}

#
# Internal function which converts a list of switch ports (ifIndexes) to a
# bitmask (a binary string)
#
sub convertIfindexesToBitmask($@) {
    my $self = shift;
    my $ifIndexes = shift;
Kirk Webb's avatar
Kirk Webb committed
508
    my $id = "$self->{NAME}::convertIfindexesToBitmask()";
509 510 511 512 513 514 515

    # Store switch config in local vars for code readability
    my $type                 = $self->{TYPE};
    my $moduleSlots          = $ChassisInfo->{$type}->{moduleSlots};
    my $maxPortsPerModule    = $ChassisInfo->{$type}->{maxPortsPerModule};
    my $bitmaskBitsPerModule = $ChassisInfo->{$type}->{bitmaskBitsPerModule};

516 517
    # Create an all-zero (empty) PortSet bit vector.
    my $bitmask = pack("H*", '00' x $self->{PORTSET_NUMBYTES});
518 519 520 521 522 523 524 525 526 527

    # Convert all ifIndexes to modport format and parse modport information
    # to find out vec() offset and set the right bit
    my @modports = $self->convertPortFormat($PORT_FORMAT_MODPORT,@$ifIndexes);

    foreach my $modport (@modports) {
        $modport =~ /(\d+)\.(\d+)/;
        my $mod  = $1;
        my $port = $2;

528 529 530

	$self->debug("$id: modport $modport\n");

531 532
        if ( $port >= $maxPortsPerModule )
        {
Kirk Webb's avatar
Kirk Webb committed
533
            warn "$id: WARNING: Cannot set port larger than maxport.\n";
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
            next;
        }

        
        my $offset = 
            # start index for first port of the module
            $mod * $bitmaskBitsPerModule
            # start index for first port of the block of 8
            # ports containing the current port
            + (int($port / 8) * 8)
            # the offset we're actually looking for
            + (7 - ($port % 8));

        vec($bitmask, $offset, 1) = 0b1;
    }
    
    # All set!
    return $bitmask;
}

#
# Internal function which compares two bitmasks of equal length
# and returns the number of differing bits
#
# usage: bitmasksDiffer($bitmask1, $bitmask2) 
#
sub bitmasksDiffer($$$) {
	my $self = shift;
	my $bm1 = shift;
	my $bm2 = shift;
	
Kirk Webb's avatar
Kirk Webb committed
565 566
	my $id = "$self->{NAME}::bitmasksDiffer()";
	
567 568 569 570 571 572 573 574 575
	my $differingBits = 0;
	my $bm1unp = unpack('B*', $bm1);
	my @bm1unp = split //, $bm1unp; 
	my $bm2unp = unpack('B*', $bm2);
	my @bm2unp = split //, $bm2unp;
	
	if ( $#bm1unp == $#bm2unp ) { # must be of equal length
		for my $i (0 .. $#bm1unp) {
			if ($bm1unp[$i] != $bm2unp[$i]) {
Kirk Webb's avatar
Kirk Webb committed
576
				$self->debug("$id: bit with index $i differs!\n");
577 578 579 580 581 582 583
				$differingBits++;
			}
		}

		return $differingBits;
	}
	else {
Kirk Webb's avatar
Kirk Webb committed
584 585 586
		warn "$id: WARNING: bitmasks to compare have ".
		     "differing length: \$bm1 has last index $#bm1unp ".
		     "and \$bm2 has last index $#bm2unp\n";
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
		return ( $#bm1unp > $#bm2unp ? $#bm1unp : $#bm2unp);
	}
}

#
# Internal function which checks if all set bits in a bitmask are set or not in
# another one. Both bitmasks must be of equal length.
# 
# Returns 0 if all bits of interest conform, otherwise returns the number of
# non-conforming bits
#
# usage: checkBits($requestedStatus, $bitsOfInterest, $bitmaskToInvestigate)
#        $requestedStatus can be "on" or "off"
#
sub checkBits($$$$) {
    my $self = shift;
    my $reqStatus = shift;
    my $bm1 = shift; # reference bitmask, defining which bits need to be checked
    my $bm2 = shift; # bitmask to investigate
Kirk Webb's avatar
Kirk Webb committed
606 607

    my $id = "$self->{NAME}::checkBits()";
608 609 610 611 612 613 614 615 616 617 618
    
    my $differingBits = 0;
    my $bm1unp = unpack('B*', $bm1);
    my @bm1unp = split //, $bm1unp; 
    my $bm2unp = unpack('B*', $bm2);
    my @bm2unp = split //, $bm2unp;
    
    if ( $#bm1unp == $#bm2unp ) { # must be of equal length
	if ($reqStatus eq "on") {
	    for my $i (0 .. $#bm1unp) {
		if ($bm1unp[$i]) { # if bit is set
619 620
   		    $self->debug("checkBits(\"on\"): bit with index $i is set!\n");

621
		    if ($bm1unp[$i] != $bm2unp[$i]) {
Kirk Webb's avatar
Kirk Webb committed
622
			$self->debug("checkBits(\"on\"): bit with index $i isn't set in the other bitmask, while it should be!\n");
623 624 625 626 627 628 629 630
			$differingBits++;
		    }
		}
	    }
	} elsif ($reqStatus eq "off") {
	    for my $i (0 .. $#bm1unp) {
		if ($bm1unp[$i]) { # if bit is set
		    if ($bm1unp[$i] == $bm2unp[$i]) {
Kirk Webb's avatar
Kirk Webb committed
631
			$self->debug("checkBits(\"off\"): bit with index $i is set in the other bitmask, while it shouldn't be!\n");
632 633 634 635 636
			$differingBits++;
		    }
		}
	    }			
	} else {
Kirk Webb's avatar
Kirk Webb committed
637
	    warn "$id: ERROR: invalid requested status argument: $reqStatus\n";
638 639 640 641 642
	    return ($#bm1unp + 1);
	}
	
	return $differingBits;
    } else {
Kirk Webb's avatar
Kirk Webb committed
643
	warn "$id: ERROR: input bitmasks are of differing length!\n";
Kirk Webb's avatar
Kirk Webb committed
644
	$self->debug("$id: \$bm1 has last index $#bm1unp and \$bm2 has last index $#bm2unp\n");
645 646 647 648 649 650
	return ( $#bm1unp > $#bm2unp ? $#bm1unp + 1 : $#bm2unp + 1);
    }
}

# Utility function to add a static string prefix to an Emulab vlan id.
# FTOS does not allow purely numeric vlan names.
651 652
sub stripVlanPrefix($) {
    my $vlname = shift;
653

654 655 656
    if ($vlname =~ /^$vlanStaticNamePrefix(\d+)$/) {
	return $1;
    } else {
657
	return $vlname;
658 659
    }
}
660

661 662
# Utility function to strip the static string prefix from a vlan name,
# giving the original Emulab vlan id.
663 664 665 666 667 668
sub addVlanPrefix($) {
    my $vlname = shift;
    
    return $vlanStaticNamePrefix.$vlname;
}

669 670

# Utility function for looking up ifindex for a vlan
671 672 673 674 675
# usage: getVlanIfindex($self,$vlan_number)
#        $self - reference to "this" object
#        $vlan_number - native switch vlan number to lookup (vlan tag)
# returns: the ifindex of given vlan number, or a hash with all vlans if
#          the keyword "ALL" is given.  undef on failure / not found.
676 677
sub getVlanIfindex($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
678
    my $id = "$self->{NAME}::getVlanIfindex()";
679

680
    my %results = ();
681 682 683
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},["ifDescr"]);
    
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
684
	warn "$id: ERROR: No interface description rows returned (snmp).";
685
	return undef;
686 687 688 689 690
    }

    foreach my $result (@{$rows}) {
	my ($name,$iid,$descr) = @{$result};

691 692 693
	next unless $descr =~ /vlan\s+(\d+)/i;
	my $curvlnum = $1;

Kirk Webb's avatar
Kirk Webb committed
694
	$self->debug("$id: got $name, $iid, descr $descr\n",2);
Kirk Webb's avatar
Kirk Webb committed
695

696
	if ($vlan_number eq "ALL") {
Kirk Webb's avatar
Kirk Webb committed
697
	    $results{$iid} = $curvlnum;
698 699
	}
	elsif ($curvlnum == $vlan_number) {
700 701 702 703
	    return $iid;
	}
    }

704 705 706 707
    if ($vlan_number eq "ALL") {
	return %results;
    }

708
    # Not found.
709 710 711 712 713 714 715
    return undef;
}

# Utility function that grabs the port membership bitmask for a vlan.
# usage: getMemberBitmask($self, $vlan_ifindex)
# returns: bitmask as returned from switch via snmp (packed vector), 
#          or undef on failure.
Kirk Webb's avatar
Kirk Webb committed
716 717 718 719 720 721 722 723
sub getMemberBitmask($$;$) {
    my ($self, $vlidx, $both) = @_;
    my $id = "$self->{NAME}::getMemberBitmask()";

    my $ebitmask = snmpitGetWarn($self->{SESS},["dot1qVlanStaticEgressPorts",
						$vlidx]);
    my $ubitmask = snmpitGetWarn($self->{SESS},["dot1qVlanStaticUntaggedPorts",
						$vlidx]);
724

Kirk Webb's avatar
Kirk Webb committed
725 726
    if (!$ebitmask || !$ubitmask) {
	warn "$id: ERROR: problem fetching current membership bitmask for vlan with ifindex $vlidx\n";
727 728 729
	return undef;
    }

Kirk Webb's avatar
Kirk Webb committed
730 731 732 733 734
    if ($both) {
	return ($ebitmask, $ubitmask);
    }

    return $ebitmask;
735 736
}

737 738
#
# Utility function to punch in the egress and untagged port memberships
Kirk Webb's avatar
Kirk Webb committed
739 740
# for the given vlan number (tag).  $onoff tells the function how to check
# the resulting membership list ("on" - add; "off" - remove).
741 742 743 744 745 746 747 748 749 750
#
# usage: setPortMembership($self, $onoff, $eportmask, $uportmask, $vlifindex)
#        $self - reference to "this" object.
#        $onoff - check for addition ("on") or removal ("off") ports.
#        $eportmask - packed bitmask to use with dot1qVlanStaticEgressPorts
#        $uportmask - packed bitmask to use with dot1qVlanStaticUntaggedPorts
#        $vlifindex - ifindex of vlan to operate on.
#
# returns: number of ports that failed to be (un)set.
#
Kirk Webb's avatar
Kirk Webb committed
751 752
sub setPortMembership($$$$$) {
        my ($self, $onoff, $eportmask, $uportmask, $vlifindex) = @_;
Kirk Webb's avatar
Kirk Webb committed
753
	my $id = "$self->{NAME}::setPortMembership()";
Kirk Webb's avatar
Kirk Webb committed
754

Kirk Webb's avatar
Kirk Webb committed
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
	# Sanity checks
	if (!defined($onoff) || !defined($eportmask) || 
	    !defined($uportmask) || !defined($vlifindex)) {
	    warn "$id: ERROR: required parameters missing to call.";
	    return -1;
	}

	if (length($eportmask) != length($uportmask)) {
	    warn "$id: ERROR: egress and untagged portsets are different sizes!";
	    return -1;
	}

	if ($onoff ne "on" && $onoff ne "off") {
	    warn "$id: \$onoff must be either 'on' or 'off'";
	    return -1;
	}

	if ($vlifindex !~ /^\d+$/) {
	    warn "$id: vlan ifindex is not a number: $vlifindex\n";
	    return -1;
	}

Kirk Webb's avatar
Kirk Webb committed
777 778 779
	# Grab the number of bits set in the untagged port mask.
	my $setcount = unpack("%32b*", $uportmask);

Kirk Webb's avatar
Kirk Webb committed
780 781 782 783
	$self->debug("$id: Setting membership for vlan with ".
		     "ifindex $vlifindex\n");
	$self->debug("$id: Validate membership state to be: $onoff\n");

Kirk Webb's avatar
Kirk Webb committed
784 785
	# The egress ports and untagged ports have to be updated
	# simultaneously.
Kirk Webb's avatar
Kirk Webb committed
786 787 788 789 790 791 792 793
	my $snmpvars = new SNMP::VarList(
	    ["dot1qVlanStaticEgressPorts", $vlifindex, 
	     $eportmask, "OCTETSTR"], 
	    ["dot1qVlanStaticUntaggedPorts", $vlifindex, 
	     $uportmask, "OCTETSTR"]);

	# XXX: Can't use snmpitSetWarn since these port set operations
	# routinely return an "undoFailed" status on the Force10
794
	# platform (even when successful).  Not sure why this happens...
Kirk Webb's avatar
Kirk Webb committed
795
	my $status = $self->{SESS}->set($snmpvars);
Kirk Webb's avatar
Kirk Webb committed
796

797 798
	# Since the return value cannot be trusted, we do our own
	# little investigation to see if the set command succeeded.
Kirk Webb's avatar
Kirk Webb committed
799
	if (!defined($status)) {
Kirk Webb's avatar
Kirk Webb committed
800
	    $self->debug("$id: Error setting port membership: $self->{SESS}->{ErrorStr}\n");
Kirk Webb's avatar
Kirk Webb committed
801
	}
Kirk Webb's avatar
Kirk Webb committed
802 803 804 805

	# Get the current membership bitmask for this vlan
	my $newmask = $self->getMemberBitmask($vlifindex);
	if (!defined($newmask)) {
Kirk Webb's avatar
Kirk Webb committed
806
		warn "$id: ERROR: failed to get current ".
807
		     "membership bitmask for vlan with ifindex $vlifindex\n";
Kirk Webb's avatar
Kirk Webb committed
808 809 810
		return $setcount;
	}
	
Kirk Webb's avatar
Kirk Webb committed
811 812 813 814
	# Should return 0 if everything is alright, no. of failed
	# ports otherwise
	my $checkmask = $onoff eq "on" ? $eportmask : $uportmask;
	my $failcount = $self->checkBits($onoff, $checkmask, 
Kirk Webb's avatar
Kirk Webb committed
815 816 817
					 $newmask);

	if ($failcount) {
Kirk Webb's avatar
Kirk Webb committed
818
		warn "$id: Could not manipulate $failcount ".
819
		     "ports in vlan with ifindex $vlifindex!\n";
Kirk Webb's avatar
Kirk Webb committed
820 821 822 823 824
	}

	return $failcount; # should be 0
}

825 826 827 828 829 830 831
# Remove the input ports from any VLAN they might be in, except for the
# default vlan.
sub removePortsFromAllVlans($$@) {
    my ($self, $tagged_only, @ports) = @_;
    my $id = "$self->{NAME}::removePortsFromAllVlans";
    my $errors = 0;

832 833
    $self->debug("$id: entering\n");

834 835 836 837 838 839 840
    # Bail now if the list of ports is empty.
    if (!@ports) {
	$self->debug("$id: called with empty port list... ".
		     "Returning success!\n");
	return 0;
    }

841 842 843 844
    my @ifindexes = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
    my $portmask = $self->convertIfindexesToBitmask(\@ifindexes);
    my %vlifindexes = $self->getVlanIfindex("ALL");
    while (my ($vlifidx, $vlnum) = each %vlifindexes) {
845 846
        $self->debug("$id: Attempting to remove @ports from ".
			 "vlan number $vlnum\n");
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
	# vlan 1 is the default vlan; we don't touch it in removal
	# operations.  Membership in the default vlan is handled
	# automagically on the Force10 platform.
	next if ($vlnum == 1);

	# Only attempt a removal operation if any of the ports appear
	# in the current member list.  If only removal of tagged ports
	# was requested, adjust the mask to check against accordingly.
	my ($emask, $umask) = $self->getMemberBitmask($vlifidx,1);
	my $checkmask = $emask;
	my $rmports = \@ports;
	if ($tagged_only) {
	    # see comments in removeSomePortsFromVlan()
	    $checkmask = $portmask & ($emask ^ $umask);
	    $rmports = $self->convertBitmaskToIfindexes($checkmask);
	} 
	if ($self->checkBits("off", $portmask, $checkmask)) {
	    $self->debug("$id: Attempting to remove @ports from ".
			 "vlan number $vlnum\n");
	    $errors += $self->removeSomePortsFromVlan($vlnum, @{$rmports});
	}
    }

    return $errors;
}

873 874 875 876
##############################################################################
## Snmpit API Module Methods Section
##

877 878 879 880 881 882 883 884 885
#
# List all ports on the device
#
# usage: listPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
#
sub listPorts($) {
    my $self = shift;
Kirk Webb's avatar
Kirk Webb committed
886
    my $id = "$self->{NAME}::listPorts()";
887

888
    my %Nodeports = ();
889 890 891 892 893 894 895 896 897 898
    my %Able = ();
    my %Link = ();
    my %speed = ();
    my %duplex = ();

    my ($ifIndex, $status);

    #
    # Get the port configuration, including ifOperStatus (really up or down),
    # duplex, speed / whether or not it is autoconfiguring
899
    #			
900 901
    foreach $ifIndex (keys %{$self->{PORTINDEX}}) {

902 903 904 905
	#
	# Skip ports that don't seem to have anything interesting attached
	#
	my ($port) = $self->convertPortFormat($PORT_FORMAT_PORT, $ifIndex);
906
	my $nodeport = $port->getOtherEndPort();
907 908 909 910 911 912 913
	if (!defined($port) || !defined($nodeport) || 
	    $port->toString() eq $nodeport->toString()) {
	    $self->debug("Port $port not connected, skipping\n");
	    next;
	}
	$Nodeports{$ifIndex} = $nodeport;

914
	if ($status = snmpitGetWarn($self->{SESS},["ifAdminStatus",
915 916 917
						   $ifIndex])) {
	    $Able{$ifIndex} = ( $status =~ /up/ ? "yes" : "no" );
	}
918
    	
919
	if ($status = snmpitGetWarn($self->{SESS},["ifOperStatus",
920 921 922
						   $ifIndex])) {
	    $Link{$ifIndex} = $status;
	}
923
		
924
	if ($status = snmpitGetWarn($self->{SESS},["dot3StatsDuplexStatus",
925 926 927 928 929
						   $ifIndex])) {
	    $status =~ s/Duplex//;
	    $duplex{$ifIndex} = $status;
	}
	
930
	if ($status = snmpitGetWarn($self->{SESS},["ifHighSpeed",
931 932 933 934 935
						   $ifIndex])) {
	    $speed{$ifIndex} = $status . "Mbps";
	}
    }
    
936 937 938 939 940
    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
941 942 943 944
    foreach my $ifIndex ( sort keys %Able ) {
	if (! defined ($speed{$ifIndex}) ) { $speed{$ifIndex} = " "; }
	if (! defined ($duplex{$ifIndex}) ) { $duplex{$ifIndex} = "full"; }
	push @rv, [$Nodeports{$ifIndex},$Able{$ifIndex},$Link{$ifIndex},$speed{$ifIndex},$duplex{$ifIndex}];
945 946 947 948 949 950 951 952 953 954 955 956 957
    }
    return @rv;
}


#
# List all VLANs on the device
#
# usage: listVlans($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
sub listVlans($) {
	my $self = shift;
Kirk Webb's avatar
Kirk Webb committed
958 959
	my $id = "$self->{NAME}::listVlans()";
	$self->debug("\n$id:\n",2);
960 961 962 963 964 965 966 967
	
	my %Names = ();
	my %Numbers = ();
	my %Members = ();

	# get list of vlan names from dot1qVlanStaticName (Q-BRIDGE-MIB)
	# and save these in %Names with the ifIndexes (iids) as the key
	# (unlike ethernet ports, vlans aren't static, so this is done from
968
	# scratch each time instead of being stored in a hash by the constructor
969
	my ($results) = snmpitBulkwalkWarn($self->{SESS}, ["dot1qVlanStaticName"]);
970 971

	# $name should always be "dot1qVlanStaticName"
972 973
	foreach my $result (@{$results}) {
	    my ($name,$iid,$vlanname) = @{$result};
Kirk Webb's avatar
Kirk Webb committed
974
	    $self->debug("$id: got $name, $iid, name $vlanname\n",2);
975
	    if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
976
		warn "$id: WARNING: unexpected oid: $name\n";
977 978 979 980 981 982 983
		next;
	    }

	    # Must strip the prefix required on the Force10 to get the vlan id
	    # as known by Emulab.
	    $vlanname = stripVlanPrefix($vlanname);
	    $Names{$iid} = $vlanname;
984 985 986 987 988 989 990 991 992 993
	}
	
	my ($ifIndex, $status);
	
	# get corresponding VLAN numbers
	# (i.e. the "real" vlan tags as known by the switch, called 
	# "cisco-specific" in the snmpit_cisco.pm module;
	# with "vlan id" they mean the vlan name as known in the 
	# database = the administrative name in the switch, not the tag)
	foreach $ifIndex (keys %Names) {
994 995 996 997 998
	    if ($status = snmpitGetWarn($self->{SESS},
					["ifDescr",$ifIndex])) {
		if ($status =~ /^Vlan\s(\d+)$/) {
		    $Numbers{$ifIndex} = $1;
		} else {
Kirk Webb's avatar
Kirk Webb committed
999
		    warn "$id: ERROR: Unable to parse out vlan tag for ifindex $ifIndex\n";
1000
		    return undef;
1001
		}
1002
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1003
		warn "$id: ERROR: Unable to get vlan tag for ifindex $ifIndex\n";
1004 1005
		return undef;
	    }
1006 1007 1008 1009 1010
	}
	
	# get corresponding port bitmaps from dot1qVlanStaticEgressPorts
	# and find out the corresponding port ifIndexes
	foreach $ifIndex (keys %Names) {
1011 1012 1013
	    my $membermask = $self->getMemberBitmask($ifIndex);
	    if (defined($membermask)) {
		my $indexes = $self->convertBitmaskToIfindexes($membermask);
1014 1015 1016
		my @ports = $self->convertPortFormat($PORT_FORMAT_PORT, 
						     @{$indexes});
		$Members{$ifIndex} = \@ports;
1017
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1018
		warn "$id: ERROR: Unable to get port membership for ifindex $ifIndex\n";
1019 1020
		return undef;
	    }
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
	}
	
	# create array to return to caller
	my @vlanInfo = ();
	foreach $ifIndex (sort {$a <=> $b} keys %Names) {
		push @vlanInfo, [$Names{$ifIndex},$Numbers{$ifIndex},
			$Members{$ifIndex}];
	}
	$self->debug(join("\n",(map {join ",", @$_} @vlanInfo))."\n");
	
	return @vlanInfo;
}

# 
# Check to see if the given "real" VLAN number (i.e. tag) exists on the switch
#
# usage: vlanNumberExists($self, $vlan_number)
#        returns 1 if the 802.1Q VLAN tag exists, 0 otherwise
#
sub vlanNumberExists($$) {
1041
    my ($self, $vlan_number) = @_;
1042

1043 1044 1045
    # resolve the vlan number to an ifindex.  If no result, then no vlan...
    if (defined($self->getVlanIfindex($vlan_number))) {
	return 1;
1046
    } else {
1047
    	return 0;
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    }
}

#
# 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 = @_;
Kirk Webb's avatar
Kirk Webb committed
1063 1064
    my %vlanmap = ();
    my $id = "$self->{NAME}::findVlans()";
1065 1066 1067

    # Build a mapping from vlan ifindex to vlan number.  Have to do this
    # each time since the set of vlans varies over time.
Kirk Webb's avatar
Kirk Webb committed
1068
    my %vlidx2num = $self->getVlanIfindex("ALL");
1069
    
1070
    # Grab the list of vlans.
Kirk Webb's avatar
Kirk Webb committed
1071
    my ($results) = snmpitBulkwalkWarn($self->{SESS}, ["dot1qVlanStaticName"]);
1072

1073 1074
    foreach my $result (@{$results}) {
	my ($name,$iid,$vlanname) = @{$result};
1075
	$self->debug("findVlans(): got $name, $iid, name $vlanname\n",2);
1076
	if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
1077
	    warn "$id: WARNING: unexpected oid: $name\n";
1078
	    next;
1079 1080
	}

1081 1082 1083 1084 1085 1086 1087
	# Must strip the prefix required on the Force10 to get the vlan id
	# as known by Emulab.
	$vlanname = stripVlanPrefix($vlanname);
	
	# add to hash if theres no @vlan_ids list (requesting all) or if the
	# vlan is actually in the list
	if ( (! @vlan_ids) || (grep {$_ eq $vlanname} @vlan_ids) ) {
Kirk Webb's avatar
Kirk Webb committed
1088
	    $vlanmap{$vlanname} = $vlidx2num{$iid};
1089 1090 1091
	}
    }

Kirk Webb's avatar
Kirk Webb committed
1092
    return %vlanmap;
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
}

#
# Given a VLAN identifier from the database, find the "cisco-specific VLAN
# number" that is assigned to that VLAN (= VLAN tag). Retries several times (to
# account for propagation delays) unless the $no_retry option is given.
#
# usage: findVlan($self, $vlan_id,$no_retry)
#        returns the VLAN number for the given vlan_id if it exists
#        returns undef if the VLAN id is not found
#
sub findVlan($$;$) { 
1105 1106 1107 1108 1109 1110 1111
    my $self = shift;
    my $vlan_id = shift;
    my $no_retry = shift;
    
    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
1112
    } else {
1113
	$max_tries = 10;
1114 1115
    }

1116 1117 1118
    # We try this a few times, with 1 second sleeps, since it can take
    # a while for VLAN information to propagate
    foreach my $try (1 .. $max_tries) {
1119

1120 1121 1122 1123
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
	}
1124

1125 1126
	# Wait before we try again
	if ($try < $max_tries) {
Kirk Webb's avatar
Kirk Webb committed
1127
	    $self->debug("findVlan: failed, trying again\n");
1128
	    sleep 1;
1129
	}
1130
    }
1131

1132 1133
    # Didn't find it
    return undef;
1134 1135
}

1136 1137 1138 1139 1140 1141
#
# Determine if a VLAN has any members 
# (Used by stack->switchesWithPortsInVlan())
#
sub vlanHasPorts($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
1142
    my $id = "$self->{NAME}::vlanHasPorts()";
1143 1144 1145

    my $vlifindex = $self->getVlanIfindex($vlan_number);
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1146
	warn "$id: ERROR: Could not lookup vlan index for vlan: $vlan_number\n";
1147 1148 1149 1150 1151
	return 0;
    }

    my $membermask = $self->getMemberBitmask($vlifindex);
    if (!defined($membermask)) {
Kirk Webb's avatar
Kirk Webb committed
1152
	warn "$id: ERROR: Could not get membership bitmask for blan: $vlan_number\n";
1153 1154
	return 0;
    }
1155
    my $setcount = unpack("%32b*", $membermask);
1156 1157 1158 1159

    return $setcount ? 1 : 0;
}

1160 1161
#
# Create a VLAN on this switch, with the given identifier (which comes from
1162
# the database) and given 802.1Q tag number ($vlan_number). 
1163
#
1164
# usage: createVlan($self, $vlan_id, $vlan_number)
1165 1166 1167
#        returns the new VLAN number on success
#        returns 0 on failure
#
1168 1169 1170 1171 1172 1173
sub createVlan($$$) {
    my $self = shift;
    
    # as known in db and as will be saved in administrative vlan
    # name on switch
    my $vlan_id = shift;
1174

1175 1176
    # 802.1Q vlan tag
    my $vlan_number = shift; 
Kirk Webb's avatar
Kirk Webb committed
1177 1178

    my $id = "$self->{NAME}::createVlan()";
1179
	
1180 1181
    # Check to see if the requested vlan number already exists.
    if ($self->vlanNumberExists($vlan_number)) {
Kirk Webb's avatar
Kirk Webb committed
1182
	warn "$id: ERROR: VLAN $vlan_number already exists\n";
1183 1184
	return 0;
    }
1185

1186 1187 1188 1189 1190 1191
    # Create VLAN
    my $RetVal = snmpitSetWarn($self->{SESS},["dot1qVlanStaticRowStatus", 
					      $vlan_number, "createAndGo", 
					      "INTEGER"]);
    # $RetVal will be undefined if the set failed, or "1" if it succeeded.
    if (! defined($RetVal) )  { 
Kirk Webb's avatar
Kirk Webb committed
1192
	warn "$id: ERROR: VLAN Create id '$vlan_id' as VLAN $vlan_number failed.\n";
1193 1194
	return 0;
    }
1195 1196 1197

    # trying to use static ifindex offsets for vlans is unreliable.
    my $vlifindex = $self->getVlanIfindex($vlan_number);
1198
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1199
	warn "$id: ERROR: Could not lookup ifindex for vlan number: $vlan_number\n";
1200 1201
	return 0;
    }
1202 1203 1204 1205 1206 1207
    
    # Set administrative name to vlan_id as known in emulab db.
    # Prepend a string to the numeric id as Force10 doesn't allow all numberic
    # for a vlan name.
    $vlan_id = addVlanPrefix($vlan_id);
    $RetVal = snmpitSetWarn($self->{SESS},["dot1qVlanStaticName", 
1208
					   $vlifindex,
1209 1210 1211 1212 1213
					   $vlan_id,
					   "OCTETSTR"]);
    
    # $RetVal will be undefined if the set failed, or "1" if it succeeded.
    if (! defined($RetVal) )  { 
Kirk Webb's avatar
Kirk Webb committed
1214
	warn "$id: ERROR: Setting VLAN name to '$vlan_id' failed, ".
1215 1216
	     "but VLAN $vlan_number was created! ".
	     "Manual cleanup required.\n";
1217 1218
	return 0;
    }
1219

1220
    return $vlan_number;
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
}

#
# Put the given ports in the given VLAN. The VLAN is given as an 802.1Q 
# tag number. (so NOT as a vlan_id from the database!)
#
# usage: setPortVlan($self, $vlan_number, @ports)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure
#
sub setPortVlan($$@) {
1232
    my ($self, $vlan_number, @ports) = @_;
Kirk Webb's avatar
Kirk Webb committed
1233
    my $id = "$self->{NAME}::setPortVlan";
1234

1235 1236
    $self->debug("id: entering\n");

1237 1238 1239 1240 1241 1242 1243
    # Get the vlan's ifindex now.  No point in doing anything more if it
    # doesn't exist!
    my $vlanIfindex = $self->getVlanIfindex($vlan_number);
    if (!$vlanIfindex) {
	warn "$id: ERROR: Could not find ifindex for vlan $vlan_number\n";
	return scalar(@ports);
    }
1244

1245 1246 1247
    # Convert the list of input ports into the two formats we need here.
    # Hopefully the incoming list contains port objects already - otherwise
    # we are in for DB queries.
1248
    my @portlist = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
Kirk Webb's avatar
Kirk Webb committed
1249
    my @portobjs = $self->convertPortFormat($PORT_FORMAT_PORT, @ports);
1250 1251
    $self->debug("id: input ports: " . join(",",@ports) . "\n");
    $self->debug("id: as ifIndexes: " . join(",",@portlist) . "\n");
1252

Kirk Webb's avatar
Kirk Webb committed
1253 1254 1255 1256 1257
    if (scalar(@portlist) != scalar(@portobjs)) {
	warn "$id: ERROR: Port object list length is different than ifindex list length for the same set of input ports!\n";
	return scalar(@ports);
    }

1258
    # Create a bitmask from this ifIndex list
1259
    my $portmask = $self->convertIfindexesToBitmask(\@portlist);
1260

Kirk Webb's avatar
Kirk Webb committed
1261 1262 1263 1264 1265
    # Look at DB state (via Port objects) to determine which ports are
    # in trunk mode.  Create the "untagged" bitmask from those that
    # are not.
    my $i = 0;
    my @uportlist = ();
1266
    my @upobjs = ();
Kirk Webb's avatar
Kirk Webb committed
1267
    foreach my $pobj (@portobjs) {
1268 1269
	if ($pobj->tagged() == 0 && 
	    !exists($self->{TRUNKS}->{$portlist[$i]})) {
1270
	    $self->debug("id: Adding port $pobj as untagged to $vlan_number\n",2);
Kirk Webb's avatar
Kirk Webb committed
1271
	    push @uportlist, $portlist[$i];
1272
	    push @upobjs, $pobj;
Kirk Webb's avatar
Kirk Webb committed
1273 1274 1275
	}
	$i++;
    }
1276
    my $uportmask = $self->convertIfindexesToBitmask(\@uportlist);
1277

1278 1279 1280 1281 1282
    # Zap the untagged ports from any vlan that they are currently in
    # (aside from the default).  Otherwise, the subsequent set operation
    # might fail.
    my $tagged_only = 0;
    $self->removePortsFromAllVlans($tagged_only, @upobjs);
Kirk Webb's avatar
Kirk Webb committed
1283

1284 1285 1286 1287 1288 1289 1290 1291 1292
    # Mix in the membership already set up on the target vlan.  Doing this
    # avoids accidentally removing tagged ports when adding new ports to the
    # vlan (zeros written to a port's bit in both vectors will remove it from
    # the vlan if it's a tagged member).
    my ($vlebits, $vlubits) = $self->getMemberBitmask($vlanIfindex,1);
    my $ebits = $portmask | $vlebits;
    my $ubits = $uportmask | $vlubits;

    return $self->setPortMembership("on", $ebits, $ubits, $vlanIfindex);
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
}

# Removes and disables some ports in a given VLAN. The VLAN is given as a VLAN
# 802.1Q tag value.  Ports are known to be regular ports and not trunked.
#
# usage: removeSomePortsFromVlan(self,vlan,@ports)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
sub removeSomePortsFromVlan($$@) {
	my $self = shift;
	my $vlan_number = shift;
	my @ports = @_;
1305
	my $id = "$self->{NAME}::removeSomePortsFromVlan()";
1306

Kirk Webb's avatar
Kirk Webb committed
1307 1308 1309
	# VLAN 1 is default VLAN, that's where all ports are supposed to go
	# so trying to remove them there doesn't make sense
	if ($vlan_number == 1) {
Kirk Webb's avatar
Kirk Webb committed
1310
	    warn "$id: WARNING: Attempt made to remove @ports from default VLAN 1\n";
Kirk Webb's avatar
Kirk Webb committed
1311 1312
	    return 0;
	}
1313 1314 1315 1316

	# Run the port list through portmap to find the ports on the switch that
	# we are concerned with
	my @portlist = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
Kirk Webb's avatar
Kirk Webb committed
1317 1318
	$self->debug("$id: removing ports from vlan $vlan_number: @ports\n");
	$self->debug("$id: port ifIndexes: @portlist\n");
1319 1320 1321
	
	# Create a bitmask from this ifIndex list
	my $bitmaskToRemove = $self->convertIfindexesToBitmask(\@portlist);
Kirk Webb's avatar
Kirk Webb committed
1322 1323

	# Create an all-zero bitmask of the appropriate length.
1324
	my $allZeroBitmask = "00000000" x length($bitmaskToRemove);
Kirk Webb's avatar
Kirk Webb committed
1325 1326
        $allZeroBitmask = pack("B*", $allZeroBitmask);

1327
	# Get the vlan's ifindex.
1328
	my $vlanIfindex = $self->getVlanIfindex($vlan_number);
1329
	if (!defined($vlanIfindex)) {
Kirk Webb's avatar
Kirk Webb committed
1330
	    warn "$id: ERROR: Could not get ifindex for vlan number $vlan_number!\n";
1331 1332
	    return scalar(@ports);
	}
1333

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
	# Warning - wacky bitmath ahead! Removing a port from a vlan is
	# done differently for tagged vs. untagged ports.  To remove a tagged
	# port, the port's bit needs to be '0' in both egress and untagged
	# PortSets.  To remove an untagged port, the port's egress bit must
	# be a '0', while the untagged bit must be a '1'.  Gross.
	my ($curEbits, $curUbits) = $self->getMemberBitmask($vlanIfindex,1);
	# The set of currently tagged ports have a '1' in the egress
	# PortSet and a '0' in the untagged PortSet.  Tagged ports
	# have a '1' in both sets, and non-members are '0' in both. XOR!
	my $tagBits = $curEbits ^ $curUbits;
	# Set the egress PortSet to zeros where we are removing ports, but
	# set to '1' for tagged ports that are not to be removed. gawd.
	my $eBits = ($bitmaskToRemove & $tagBits) ^ $tagBits;
	# To create the untagged PortSet, we clear the tagged port
	# bits in the input PortSet, leaving just the untagged ports
	# with their bits set.
	my $uBits = $curUbits & $bitmaskToRemove;

	return $self->setPortMembership("off", $eBits, $uBits, $vlanIfindex);
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
}


#
# Remove the given VLANs from this switch. Removes all ports from the VLAN,
# so it's not necessary to call removePortsFromVlan() first. The VLAN is
# given as a 802.1Q VLAN tag number (so NOT as a vlan_id from the database!)
#
# usage: removeVlan(self,int vlan)
#	 returns 1 on success
#	 returns 0 on failure
#
sub removeVlan($@) {
	my $self = shift;
	my @vlan_numbers = @_;
	my $errors = 0;
	my $DeleteOID = "dot1qVlanStaticRowStatus";
Kirk Webb's avatar
Kirk Webb committed
1370
	my $id = "$self->{NAME}::removeVlan()";
1371 1372

	foreach my $vlan_number (@vlan_numbers) {
1373 1374
	        # We won't remove vlan 1.
	        next if $vlan_number == 1;
1375
		# Calculate ifIndex for this VLAN
1376
		my $ifIndex = $self->getVlanIfindex($vlan_number);
1377
		if (!defined($ifIndex)) {
Kirk Webb's avatar
Kirk Webb committed
1378
		    warn "$id: ERROR: Problem looking up vlan ifindex for vlan number $vlan_number.\n";
1379 1380 1381
		    $errors++;
		    next;
		}
1382 1383 1384 1385 1386 1387
		
		# Perform the actual removal (no need to first remove all ports from
		# the VLAN)
		
		my $RetVal = undef;
		print "  Removing VLAN # $vlan_number ... ";
Kirk Webb's avatar
Kirk Webb committed
1388
		$RetVal = snmpitSetWarn($self->{SESS},
Kirk Webb's avatar
Kirk Webb committed
1389
				[$DeleteOID,$ifIndex,"destroy","INTEGER"]);
1390 1391
		# $RetVal should contain "0 but true" if successful	
		if ( defined($RetVal) ) { 
Kirk Webb's avatar
Kirk Webb committed
1392
			print "Removed VLAN $vlan_number on switch $self->{NAME}.\n";
1393
		} else {
Kirk Webb's avatar
Kirk Webb committed
1394
		    warn "$id: ERROR: Removal of VLAN $vlan_number failed.\n";
1395 1396
		    $errors++;
		    next;
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		}
	}
	
	return ($errors == 0) ? 1 : 0;
}

#
# Removes ALL ports from the given VLANS. Each VLAN is given as a VLAN
# 802.1Q tag value.
#
# usage: removePortsFromVlan(self,@vlan)
#	 returns 0 on sucess (!!!)
#	 returns the number of failed ports on failure.
#
sub removePortsFromVlan($@) {
1412 1413 1414
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
Kirk Webb's avatar
Kirk Webb committed
1415
    my $id = "$self->{NAME}::removePortsFromVlan()";
1416 1417

    foreach my $vlan_number (@vlan_numbers) {
Kirk Webb's avatar
Kirk Webb committed
1418
    	$self->debug("$id: attempting to remove all ports from vlan_number $vlan_number\n");
1419
    	
1420 1421 1422
	# VLAN 1 is default VLAN, that's where all ports are supposed to go
	# so trying to remove them there doesn't make sense
	if ($vlan_number == 1) {
Kirk Webb's avatar
Kirk Webb committed
1423
	    warn "$id: WARNING: Attempt made to remove all ports from default VLAN 1\n";
1424 1425
	    next;
	}
Kirk Webb's avatar
Kirk Webb committed
1426 1427