snmpit_force10.pm 59.5 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 335 336 337 338 339
	elsif ($descr =~ /Slot: (\d+) Port: (\d+)/) {
	    my $module = $1;
	    my $port = $2;

	    my $modport = "${module}.${port}";
	    my $ifIndex = $iid;
	    
	    $self->{IFINDEX}{$modport} = $ifIndex;
	    $self->{IFINDEX}{$ifIndex} = $modport;
	    $self->{PORTINDEX}{$ifIndex} = $descr;
	    $self->debug("mod $module, port $port, modport $modport, descr $descr\n",2);
	}
340 341 342 343 344 345 346
	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);
	}
347
	elsif ($descr =~ /vlan 1/i || $descr =~ /vl1/i) {
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	    # 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;
369 370 371 372
    }

    # success
    return 1;
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
}

#
# 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
390
    my $id = "$self->{NAME}::convertPortFormat()";
391 392 393 394 395 396 397 398 399 400 401 402 403

    #
    # 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
404
		warn "$id: ERROR: Given a bad list of ports\n";
405 406 407 408 409
		return undef;
    }

    my $input;
    SWITCH: for ($sample) {
410 411 412
	(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
413
	warn "$id: ERROR: Unrecognized input sample: $sample\n";
414
	return undef;
415 416 417 418 419 420
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
421 422
	$self->debug("Not converting, input format = output format\n",2);
	return @ports;
423 424 425
    }

    if ($input == $PORT_FORMAT_IFINDEX) {
426 427 428 429 430 431 432 433 434 435
	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;
	}
436
    } elsif ($input == $PORT_FORMAT_MODPORT) {
437 438 439 440 441 442 443 444 445 446 447 448 449
	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
450 451
	    return map $self->{IFINDEX}{$_->switch_card() .".". 
					$_->switch_port()}, @ports;
452 453
	} elsif ($output == $PORT_FORMAT_MODPORT) {
	    $self->debug("Converting Port to modport\n",2);
Kirk Webb's avatar
Kirk Webb committed
454
	    return map $_->switch_card() .".". $_->switch_port(), @ports;
455
	}
456 457 458 459 460
    }

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

465 466 467 468 469 470 471
#
# 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
472
    my $id = "$self->{NAME}::convertBitmaskToIfindexes()";
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

    # 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
520
    my $id = "$self->{NAME}::convertIfindexesToBitmask()";
521 522 523 524 525 526 527

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

528 529
    # Create an all-zero (empty) PortSet bit vector.
    my $bitmask = pack("H*", '00' x $self->{PORTSET_NUMBYTES});
530 531 532 533 534 535 536 537 538 539

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

540 541 542

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

543 544
        if ( $port >= $maxPortsPerModule )
        {
Kirk Webb's avatar
Kirk Webb committed
545
            warn "$id: WARNING: Cannot set port larger than maxport.\n";
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
            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
577 578
	my $id = "$self->{NAME}::bitmasksDiffer()";
	
579 580 581 582 583 584 585 586 587
	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
588
				$self->debug("$id: bit with index $i differs!\n");
589 590 591 592 593 594 595
				$differingBits++;
			}
		}

		return $differingBits;
	}
	else {
Kirk Webb's avatar
Kirk Webb committed
596 597 598
		warn "$id: WARNING: bitmasks to compare have ".
		     "differing length: \$bm1 has last index $#bm1unp ".
		     "and \$bm2 has last index $#bm2unp\n";
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
		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
618 619

    my $id = "$self->{NAME}::checkBits()";
620 621 622 623 624 625 626 627 628 629 630
    
    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
631 632
   		    $self->debug("checkBits(\"on\"): bit with index $i is set!\n");

633
		    if ($bm1unp[$i] != $bm2unp[$i]) {
Kirk Webb's avatar
Kirk Webb committed
634
			$self->debug("checkBits(\"on\"): bit with index $i isn't set in the other bitmask, while it should be!\n");
635 636 637 638 639 640 641 642
			$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
643
			$self->debug("checkBits(\"off\"): bit with index $i is set in the other bitmask, while it shouldn't be!\n");
644 645 646 647 648
			$differingBits++;
		    }
		}
	    }			
	} else {
Kirk Webb's avatar
Kirk Webb committed
649
	    warn "$id: ERROR: invalid requested status argument: $reqStatus\n";
650 651 652 653 654
	    return ($#bm1unp + 1);
	}
	
	return $differingBits;
    } else {
Kirk Webb's avatar
Kirk Webb committed
655
	warn "$id: ERROR: input bitmasks are of differing length!\n";
Kirk Webb's avatar
Kirk Webb committed
656
	$self->debug("$id: \$bm1 has last index $#bm1unp and \$bm2 has last index $#bm2unp\n");
657 658 659 660 661 662
	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.
663 664
sub stripVlanPrefix($) {
    my $vlname = shift;
665

666 667 668
    if ($vlname =~ /^$vlanStaticNamePrefix(\d+)$/) {
	return $1;
    } else {
669
	return $vlname;
670 671
    }
}
672

673 674
# Utility function to strip the static string prefix from a vlan name,
# giving the original Emulab vlan id.
675 676 677 678 679 680
sub addVlanPrefix($) {
    my $vlname = shift;
    
    return $vlanStaticNamePrefix.$vlname;
}

681 682

# Utility function for looking up ifindex for a vlan
683 684 685 686 687
# 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.
688 689
sub getVlanIfindex($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
690
    my $id = "$self->{NAME}::getVlanIfindex()";
691

692
    my %results = ();
693 694 695
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},["ifDescr"]);
    
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
696
	warn "$id: ERROR: No interface description rows returned (snmp).";
697
	return undef;
698 699 700 701 702
    }

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

703
	next unless ($descr =~ /vlan\s+(\d+)/i || $descr =~ /vl(\d+)/i);
704 705
	my $curvlnum = $1;

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

708
	if ($vlan_number eq "ALL") {
Kirk Webb's avatar
Kirk Webb committed
709
	    $results{$iid} = $curvlnum;
710 711
	}
	elsif ($curvlnum == $vlan_number) {
712 713 714 715
	    return $iid;
	}
    }

716 717 718 719
    if ($vlan_number eq "ALL") {
	return %results;
    }

720
    # Not found.
721 722 723 724 725 726 727
    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
728 729 730 731 732 733 734 735
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]);
736

Kirk Webb's avatar
Kirk Webb committed
737 738
    if (!$ebitmask || !$ubitmask) {
	warn "$id: ERROR: problem fetching current membership bitmask for vlan with ifindex $vlidx\n";
739 740 741
	return undef;
    }

Kirk Webb's avatar
Kirk Webb committed
742 743 744 745 746
    if ($both) {
	return ($ebitmask, $ubitmask);
    }

    return $ebitmask;
747 748
}

749 750
#
# Utility function to punch in the egress and untagged port memberships
Kirk Webb's avatar
Kirk Webb committed
751 752
# for the given vlan number (tag).  $onoff tells the function how to check
# the resulting membership list ("on" - add; "off" - remove).
753 754 755 756 757 758 759 760 761 762
#
# 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
763 764
sub setPortMembership($$$$$) {
        my ($self, $onoff, $eportmask, $uportmask, $vlifindex) = @_;
Kirk Webb's avatar
Kirk Webb committed
765
	my $id = "$self->{NAME}::setPortMembership()";
Kirk Webb's avatar
Kirk Webb committed
766

Kirk Webb's avatar
Kirk Webb committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
	# 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
789 790 791
	# Grab the number of bits set in the untagged port mask.
	my $setcount = unpack("%32b*", $uportmask);

Kirk Webb's avatar
Kirk Webb committed
792 793 794 795
	$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
796 797
	# The egress ports and untagged ports have to be updated
	# simultaneously.
Kirk Webb's avatar
Kirk Webb committed
798 799 800 801 802 803 804 805
	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
806
	# platform (even when successful).  Not sure why this happens...
Kirk Webb's avatar
Kirk Webb committed
807
	my $status = $self->{SESS}->set($snmpvars);
Kirk Webb's avatar
Kirk Webb committed
808

809 810
	# 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
811
	if (!defined($status)) {
Kirk Webb's avatar
Kirk Webb committed
812
	    $self->debug("$id: Error setting port membership: $self->{SESS}->{ErrorStr}\n");
Kirk Webb's avatar
Kirk Webb committed
813
	}
Kirk Webb's avatar
Kirk Webb committed
814 815 816 817

	# Get the current membership bitmask for this vlan
	my $newmask = $self->getMemberBitmask($vlifindex);
	if (!defined($newmask)) {
Kirk Webb's avatar
Kirk Webb committed
818
		warn "$id: ERROR: failed to get current ".
819
		     "membership bitmask for vlan with ifindex $vlifindex\n";
Kirk Webb's avatar
Kirk Webb committed
820 821 822
		return $setcount;
	}
	
Kirk Webb's avatar
Kirk Webb committed
823 824 825 826
	# 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
827 828 829
					 $newmask);

	if ($failcount) {
Kirk Webb's avatar
Kirk Webb committed
830
		warn "$id: Could not manipulate $failcount ".
831
		     "ports in vlan with ifindex $vlifindex!\n";
Kirk Webb's avatar
Kirk Webb committed
832 833 834 835 836
	}

	return $failcount; # should be 0
}

837 838 839 840 841 842 843
# 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;

844 845
    $self->debug("$id: entering\n");

846 847 848 849 850 851 852
    # Bail now if the list of ports is empty.
    if (!@ports) {
	$self->debug("$id: called with empty port list... ".
		     "Returning success!\n");
	return 0;
    }

853 854 855 856
    my @ifindexes = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
    my $portmask = $self->convertIfindexesToBitmask(\@ifindexes);
    my %vlifindexes = $self->getVlanIfindex("ALL");
    while (my ($vlifidx, $vlnum) = each %vlifindexes) {
857 858
        $self->debug("$id: Attempting to remove @ports from ".
			 "vlan number $vlnum\n");
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
	# 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;
}

885 886 887 888
##############################################################################
## Snmpit API Module Methods Section
##

889 890 891 892 893 894 895 896 897
#
# 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
898
    my $id = "$self->{NAME}::listPorts()";
899

900
    my %Nodeports = ();
901 902 903 904 905 906 907 908 909 910
    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
911
    #			
912 913
    foreach $ifIndex (keys %{$self->{PORTINDEX}}) {

914 915 916 917
	#
	# Skip ports that don't seem to have anything interesting attached
	#
	my ($port) = $self->convertPortFormat($PORT_FORMAT_PORT, $ifIndex);
918
	my $nodeport = $port->getOtherEndPort();
919 920 921 922 923 924 925
	if (!defined($port) || !defined($nodeport) || 
	    $port->toString() eq $nodeport->toString()) {
	    $self->debug("Port $port not connected, skipping\n");
	    next;
	}
	$Nodeports{$ifIndex} = $nodeport;

926
	if ($status = snmpitGetWarn($self->{SESS},["ifAdminStatus",
927 928 929
						   $ifIndex])) {
	    $Able{$ifIndex} = ( $status =~ /up/ ? "yes" : "no" );
	}
930
    	
931
	if ($status = snmpitGetWarn($self->{SESS},["ifOperStatus",
932 933 934
						   $ifIndex])) {
	    $Link{$ifIndex} = $status;
	}
935
		
936
	if ($status = snmpitGetWarn($self->{SESS},["dot3StatsDuplexStatus",
937 938 939 940 941
						   $ifIndex])) {
	    $status =~ s/Duplex//;
	    $duplex{$ifIndex} = $status;
	}
	
942
	if ($status = snmpitGetWarn($self->{SESS},["ifHighSpeed",
943 944 945 946 947
						   $ifIndex])) {
	    $speed{$ifIndex} = $status . "Mbps";
	}
    }
    
948 949 950 951 952
    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
953 954 955 956
    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}];
957 958 959 960 961 962 963 964 965 966 967 968 969
    }
    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
970 971
	my $id = "$self->{NAME}::listVlans()";
	$self->debug("\n$id:\n",2);
972 973 974 975 976 977 978 979
	
	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
980
	# scratch each time instead of being stored in a hash by the constructor
981
	my ($results) = snmpitBulkwalkWarn($self->{SESS}, ["dot1qVlanStaticName"]);
982 983

	# $name should always be "dot1qVlanStaticName"
984 985
	foreach my $result (@{$results}) {
	    my ($name,$iid,$vlanname) = @{$result};
Kirk Webb's avatar
Kirk Webb committed
986
	    $self->debug("$id: got $name, $iid, name $vlanname\n",2);
987
	    if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
988
		warn "$id: WARNING: unexpected oid: $name\n";
989 990 991 992 993 994 995
		next;
	    }

	    # Must strip the prefix required on the Force10 to get the vlan id
	    # as known by Emulab.
	    $vlanname = stripVlanPrefix($vlanname);
	    $Names{$iid} = $vlanname;
996 997 998 999 1000 1001 1002 1003 1004 1005
	}
	
	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) {
1006 1007
	    if ($status = snmpitGetWarn($self->{SESS},
					["ifDescr",$ifIndex])) {
1008
		if ($status =~ /^Vlan\s(\d+)$/ || $status =~ /^Vl(\d+)$/) {
1009 1010
		    $Numbers{$ifIndex} = $1;
		} else {
Kirk Webb's avatar
Kirk Webb committed
1011
		    warn "$id: ERROR: Unable to parse out vlan tag for ifindex $ifIndex\n";
1012
		    return undef;
1013
		}
1014
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1015
		warn "$id: ERROR: Unable to get vlan tag for ifindex $ifIndex\n";
1016 1017
		return undef;
	    }
1018 1019 1020 1021 1022
	}
	
	# get corresponding port bitmaps from dot1qVlanStaticEgressPorts
	# and find out the corresponding port ifIndexes
	foreach $ifIndex (keys %Names) {
1023 1024 1025
	    my $membermask = $self->getMemberBitmask($ifIndex);
	    if (defined($membermask)) {
		my $indexes = $self->convertBitmaskToIfindexes($membermask);
1026 1027 1028
		my @ports = $self->convertPortFormat($PORT_FORMAT_PORT, 
						     @{$indexes});
		$Members{$ifIndex} = \@ports;
1029
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1030
		warn "$id: ERROR: Unable to get port membership for ifindex $ifIndex\n";
1031 1032
		return undef;
	    }
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
	}
	
	# 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($$) {
1053
    my ($self, $vlan_number) = @_;
1054

1055 1056 1057
    # resolve the vlan number to an ifindex.  If no result, then no vlan...
    if (defined($self->getVlanIfindex($vlan_number))) {
	return 1;
1058
    } else {
1059
    	return 0;
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    }
}

#
# 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
1075 1076
    my %vlanmap = ();
    my $id = "$self->{NAME}::findVlans()";
1077 1078 1079

    # 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
1080
    my %vlidx2num = $self->getVlanIfindex("ALL");
1081
    
1082
    # Grab the list of vlans.
Kirk Webb's avatar
Kirk Webb committed
1083
    my ($results) = snmpitBulkwalkWarn($self->{SESS}, ["dot1qVlanStaticName"]);
1084

1085 1086
    foreach my $result (@{$results}) {
	my ($name,$iid,$vlanname) = @{$result};
1087
	$self->debug("findVlans(): got $name, $iid, name $vlanname\n",2);
1088
	if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
1089
	    warn "$id: WARNING: unexpected oid: $name\n";
1090
	    next;
1091 1092
	}

1093 1094 1095 1096 1097 1098 1099
	# 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
1100
	    $vlanmap{$vlanname} = $vlidx2num{$iid};
1101 1102 1103
	}
    }

Kirk Webb's avatar
Kirk Webb committed
1104
    return %vlanmap;
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
}

#
# 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($$;$) { 
1117 1118 1119 1120 1121 1122 1123
    my $self = shift;
    my $vlan_id = shift;
    my $no_retry = shift;
    
    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
1124
    } else {
1125
	$max_tries = 10;
1126 1127
    }

1128 1129 1130
    # 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) {
1131

1132 1133 1134 1135
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
	}
1136

1137 1138
	# Wait before we try again
	if ($try < $max_tries) {
Kirk Webb's avatar
Kirk Webb committed
1139
	    $self->debug("findVlan: failed, trying again\n");
1140
	    sleep 1;
1141
	}
1142
    }
1143

1144 1145
    # Didn't find it
    return undef;
1146 1147
}

1148 1149 1150 1151 1152 1153
#
# Determine if a VLAN has any members 
# (Used by stack->switchesWithPortsInVlan())
#
sub vlanHasPorts($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
1154
    my $id = "$self->{NAME}::vlanHasPorts()";
1155 1156 1157

    my $vlifindex = $self->getVlanIfindex($vlan_number);
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1158
	warn "$id: ERROR: Could not lookup vlan index for vlan: $vlan_number\n";
1159 1160 1161 1162 1163
	return 0;
    }

    my $membermask = $self->getMemberBitmask($vlifindex);
    if (!defined($membermask)) {
Kirk Webb's avatar
Kirk Webb committed
1164
	warn "$id: ERROR: Could not get membership bitmask for blan: $vlan_number\n";
1165 1166
	return 0;
    }
1167
    my $setcount = unpack("%32b*", $membermask);
1168 1169 1170 1171

    return $setcount ? 1 : 0;
}

1172 1173
#
# Create a VLAN on this switch, with the given identifier (which comes from
1174
# the database) and given 802.1Q tag number ($vlan_number). 
1175
#
1176
# usage: createVlan($self, $vlan_id, $vlan_number)
1177 1178 1179
#        returns the new VLAN number on success
#        returns 0 on failure
#
1180 1181 1182 1183 1184 1185
sub createVlan($$$) {
    my $self = shift;
    
    # as known in db and as will be saved in administrative vlan
    # name on switch
    my $vlan_id = shift;
1186

1187 1188
    # 802.1Q vlan tag
    my $vlan_number = shift; 
Kirk Webb's avatar
Kirk Webb committed
1189 1190

    my $id = "$self->{NAME}::createVlan()";
1191
	
1192 1193
    # Check to see if the requested vlan number already exists.
    if ($self->vlanNumberExists($vlan_number)) {
Kirk Webb's avatar
Kirk Webb committed
1194
	warn "$id: ERROR: VLAN $vlan_number already exists\n";
1195 1196
	return 0;
    }
1197

1198 1199 1200 1201 1202 1203
    # 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
1204
	warn "$id: ERROR: VLAN Create id '$vlan_id' as VLAN $vlan_number failed.\n";
1205 1206
	return 0;
    }
1207 1208 1209

    # trying to use static ifindex offsets for vlans is unreliable.
    my $vlifindex = $self->getVlanIfindex($vlan_number);
1210
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1211
	warn "$id: ERROR: Could not lookup ifindex for vlan number: $vlan_number\n";
1212 1213
	return 0;
    }
1214 1215 1216 1217 1218 1219
    
    # 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", 
1220
					   $vlifindex,
1221 1222 1223 1224 1225
					   $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
1226
	warn "$id: ERROR: Setting VLAN name to '$vlan_id' failed, ".
1227 1228
	     "but VLAN $vlan_number was created! ".
	     "Manual cleanup required.\n";
1229 1230
	return 0;
    }
1231

1232
    return $vlan_number;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
}

#
# 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($$@) {
1244
    my ($self, $vlan_number, @ports) = @_;
Kirk Webb's avatar
Kirk Webb committed
1245
    my $id = "$self->{NAME}::setPortVlan";
1246

1247 1248
    $self->debug("id: entering\n");

1249 1250 1251 1252 1253 1254 1255
    # 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);
    }
1256

1257 1258 1259
    # 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.
1260
    my @portlist = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
Kirk Webb's avatar
Kirk Webb committed
1261
    my @portobjs = $self->convertPortFormat($PORT_FORMAT_PORT, @ports);
1262 1263
    $self->debug("id: input ports: " . join(",",@ports) . "\n");
    $self->debug("id: as ifIndexes: " . join(",",@portlist) . "\n");
1264

Kirk Webb's avatar
Kirk Webb committed
1265 1266 1267 1268 1269
    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);
    }

1270
    # Create a bitmask from this ifIndex list
1271
    my $portmask = $self->convertIfindexesToBitmask(\@portlist);
1272

Kirk Webb's avatar
Kirk Webb committed
1273 1274 1275 1276 1277
    # 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 = ();
1278
    my @upobjs = ();
Kirk Webb's avatar
Kirk Webb committed
1279
    foreach my $pobj (@portobjs) {
1280 1281
	if ($pobj->tagged() == 0 && 
	    !exists($self->{TRUNKS}->{$portlist[$i]})) {
1282
	    $self->debug("id: Adding port $pobj as untagged to $vlan_number\n",2);
Kirk Webb's avatar
Kirk Webb committed
1283
	    push @uportlist, $portlist[$i];
1284
	    push @upobjs, $pobj;
Kirk Webb's avatar
Kirk Webb committed
1285 1286 1287
	}
	$i++;
    }
1288
    my $uportmask = $self->convertIfindexesToBitmask(\@uportlist);
1289

1290 1291 1292 1293 1294
    # 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
1295

1296 1297 1298 1299 1300 1301 1302 1303 1304
    # 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);
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
}

# 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 = @_;
1317
	my $id = "$self->{NAME}::removeSomePortsFromVlan()";
1318

Kirk Webb's avatar
Kirk Webb committed
1319 1320 1321
	# 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
1322
	    warn "$id: WARNING: Attempt made to remove @ports from default VLAN 1\n";
Kirk Webb's avatar
Kirk Webb committed
1323 1324
	    return 0;
	}
1325 1326 1327 1328

	# 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
1329 1330
	$self->debug("$id: removing ports from vlan $vlan_number: @ports\n");
	$self->debug("$id: port ifIndexes: @portlist\n");
1331 1332 1333
	
	# Create a bitmask from this ifIndex list
	my $bitmaskToRemove = $self->convertIfindexesToBitmask(\@portlist);
Kirk Webb's avatar
Kirk Webb committed
1334 1335

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

1339
	# Get the vlan's ifindex.
1340
	my $vlanIfindex = $self->getVlanIfindex($vlan_number);
1341
	if (!defined($vlanIfindex)) {
Kirk Webb's avatar
Kirk Webb committed
1342
	    warn "$id: ERROR: Could not get ifindex for vlan number $vlan_number!\n";
1343 1344
	    return scalar(@ports);
	}
1345

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
	# 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);
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
}


#
# 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
1382
	my $id = "$self->{NAME}::removeVlan()";
1383 1384

	foreach my $vlan_number (@vlan_numbers) {
1385 1386
	        # We won't remove vlan 1.
	        next if $vlan_number == 1;
1387
		# Calculate ifIndex for this VLAN
1388
		my $ifIndex = $self->getVlanIfindex($vlan_number);
1389
		if (!defined($ifIndex)) {
Kirk Webb's avatar
Kirk Webb committed
1390
		    warn "$id: ERROR: Problem looking up vlan ifindex for vlan number $vlan_number.\n";
1391 1392 1393
		    $errors++;
		    next;
		}
1394 1395 1396 1397 1398 1399
		
		# 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
1400
		$RetVal = snmpitSetWarn($self->{SESS},
Kirk Webb's avatar
Kirk Webb committed
1401
				[$DeleteOID,$ifIndex,"destroy","INTEGER"]);
1402 1403
		# $RetVal should contain "0 but true" if successful	
		if ( defined($RetVal) ) { 
Kirk Webb's avatar
Kirk Webb committed
1404
			print "Removed VLAN $vlan_number on switch $self->{NAME}.\n";
1405
		} else {
Kirk Webb's avatar
Kirk Webb committed
1406
		    warn "$id: ERROR: Removal of VLAN $vlan_number failed.\n";
1407 1408
		    $errors++;
		    next;
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
		}
	}
	
	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($@) {
1424 1425 1426
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
Kirk Webb's avatar
Kirk Webb committed
1427
    my $id = "$self->{NAME}::removePortsFromVlan()";
1428 1429

    foreach my $vlan_number (@vlan_numbers) {
Kirk Webb's avatar
Kirk Webb committed
1430
    	$self->debug("$id: attempting to remove all ports from vlan_number $vlan_number\n");
1431
    	
1432 1433 1434
	# 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
1435
	    warn "$id: WARNING: Attempt made to remove all ports from default VLAN 1\n";
1436 1437
	    next;
	}
Kirk Webb's avatar
Kirk Webb committed
1438 1439

	# Get the ifindex of the vlan.
1440 1441
	my $vlanIfindex = $self->getVlanIfindex($vlan_number);
	if (!defined($vlanIfindex)) {
Kirk Webb's avatar
Kirk Webb committed
1442
	    warn "$id: WARNING: Could not get ifindex for vlan number $vlan_number!\n";
1443 1444
	    next;
	}
Kirk Webb's avatar
Kirk Webb committed
1445
	
1446 1447
	# Get the current membership bitmask and convert to a list of
	# port ifindexes to pass to removeSomePortsFromVlan()
1448
	my $currentBitmask = $self->getMemberBitmask($vlanIfindex);
1449 1450
	my $portlist = $self->convertBitmaskToIfindexes($currentBitmask);
	$errors += $self->removeSomePortsFromVlan($vlan_number, @{$portlist});
1451 1452
    }

1453
    return $errors;
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
}

#
# Set a variable associated with a port. The commands to execute are given
# in the cmdOIDs hash above. A command can involve multiple OIDs.
#
# 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 = @_;
Kirk Webb's avatar
Kirk Webb committed
1469
	my $id = "$self->{NAME}::portControl()";
1470

Kirk Webb's avatar
Kirk Webb committed
1471
	$self->debug("$id: $cmd -> (@ports)\n");
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495

	# 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... and probably FTOS will always require
		# ifIndexes.
		
		my $portFormat = $PORT_FORMAT_IFINDEX;
		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;

			$errors += $self->UpdateField($myoid,$myval,@portlist);
		}
		return $errors;
	} else {
		# Command not supported
1496 1497
		$self->debug("$id: Unsupported port control command ".
			     "'$cmd' ignored.\n");
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
		return -1;
	}
}

#
# Sets a *single* OID to a desired value for a given list of ports (in ifIndex format)
#
# usage: UpdateField($self, $OID, $desired_value, @ports)
#    returns 0 on success
#    returns -1 on failure
#
sub UpdateField($$$@) {
	my $self = shift;
	my ($OID,$val,@ports)= @_;

	$self->debug("UpdateField(): OID $OID value $val ports @ports\n");

	my $RetVal = 0;
	my $result = 0;

    foreach my $port (@ports) {
		$self->debug("UpdateField(): checking port $port for $OID $val ...\n");
Kirk Webb's avatar
Kirk Webb committed
1520
		$RetVal = snmpitGetWarn($self->{SESS},[$OID,$port]);
1521 1522 1523 1524 1525 1526 1527 1528
		if (!defined $RetVal) {
			$self->debug("UpdateField(): Port $port, change to $val: ".
				"No answer from device\n");
			$result = -1;
		} else {
			$self->debug("UpdateField(): Port $port was $RetVal\n");
			if ($RetVal ne $val) {
				$self->debug("UpdateField(): Setting port $port to $val...\n");
Kirk Webb's avatar
Kirk Webb committed
1529
				$RetVal = snmpitSetWarn($self->{SESS},[$OID,$port,$val,"INTEGER"]);
1530 1531 1532 1533

				my $count = 6;
				while (($RetVal ne $val) && (--$count > 0)) { 
					sleep 1;
Kirk Webb's avatar
Kirk Webb committed
1534
					$RetVal = snmpitGetWarn($self->{SESS},[$OID,$port]);
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
					$self->debug("UpdateField(): Value for port $port is ".
						"currently $RetVal\n");
				}
				$result =  ($count > 0) ? 0 : -1;
				$self->debug("UpdateField(): ".
					($result ? "failed.\n" : "succeeded.\n") );
			}
		}
	}
	return $result;
}

# 
# Get statistics for ports on the switch
#
# usage: getPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
#
1554 1555
sub getStats() {
    my $self = shift;
1556

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    #
    # Walk the tree for the VLAN members
    #
    my $vars = new SNMP::VarList(['ifInOctets'],['ifInUcastPkts'],
    				 ['ifInNUcastPkts'],['ifInDiscards'],
				 ['ifInErrors'],['ifInUnknownProtos'],
				 ['ifOutOctets'],['ifOutUcastPkts'],
				 ['ifOutNUcastPkts'],['ifOutDiscards'],
				 ['ifOutErrors'],['ifOutQLen']);
    my @stats = $self->{SESS}->bulkwalk(0,32,$vars);

    my $i = 0;
    my %stats = ();
    my %allports = ();
    foreach my $array (@stats) {
	while (@$array) {
	    my ($name,$ifindex,$value) = @{shift @$array};

	    # filter out entries we don't care about.
            if (! defined $self->{IFINDEX}{$ifindex}) { next; }

	    # Convert to Port object, check connectivity, and stash metrics.
Kirk Webb's avatar
Kirk Webb committed
1579 1580
            my ($swport) = $self->convertPortFormat($PORT_FORMAT_PORT, 
						    $ifindex);
1581 1582 1583 1584
            if (! defined $swport) { next; } # Skip if we don't know about it
            my $nportstr = $swport->getOtherEndPort()->toTripleString();
            $allports{$nportstr} = $swport;
	    ${$stats{$nportstr}}[$i] = $value;
1585
	}
1586 1587
	$i++;
    }
1588

1589 1590
    return map [$allports{$_},@{$stats{$_}}], sort {tbsort($a,$b)} keys %stats;
}
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622

#
# Read a set of values for all given ports.
#
# usage: getFields(self,ports,oids)
#        ports: Reference to a list of ports, in any allowable port format
#        oids: A list of OIDs to retrieve values for
#
# On sucess, returns a two-dimensional list indexed by port,oid
#
sub getFields($$$) {
	my $self = shift;
	my ($ports,$oids) = @_;

	my @ifindicies = $self->convertPortFormat($PORT_FORMAT_IFINDEX,@$ports);
	my @oids = @$oids;

	# Put together an SNMP::VarList for all the values we want to get
	my @vars = ();
	foreach my $ifindex (@ifindicies) {
		foreach my $oid (@oids) {
			push @vars, ["$oid","$ifindex"];
		}
	}

	# If we try to ask for too many things at once, we get back really bogus
	# errors. So, we limit ourselves to an arbitrary number that, by
	# experimentation, works.
	my $maxvars = 16;
	my @results = ();
	while (@vars) {
		my $varList = new SNMP::VarList(splice(@vars,0,$maxvars));
Kirk Webb's avatar
Kirk Webb committed
1623
		my $rv = snmpitGetWarn($self->{SESS},$varList);
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
		push @results, @$varList;
	}
	    
	# Build up the two-dimensional list for returning
	my @return = ();
	foreach my $i (0 .. $#ifindicies) {
		foreach my $j (0 .. $#oids) {
			my $val = shift @results;
			$return[$i][$j] = $$val[2];
		}
	}

	return @return;
}

1639 1640 1641
##############################################################################
## Trunk and port channel backends - not fully implemented yet.
##
1642

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
#
# Set a port's mode to "trunking"
#
# usage: enablePortTrunking2($self, $port, $vlan_number, $equaltrunking)
#        modport: module.port of the trunk to operate on
#        nativevlan: VLAN number of the native VLAN for this trunk
#        equalmode: don't do dual mode; tag PVID also.
#
# returns: 1 on success, 0 otherwise
#
sub enablePortTrunking2($$$$) {
Kirk Webb's avatar
Kirk Webb committed
1654 1655
    my ($self, $port, $native_vlan, $equalmode) = @_;
    my $id = "$self->{NAME}::enablePortTrunking2()";
1656