snmpit_force10.pm 70.7 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

#
# 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
62
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
63
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
64 65 66 67 68
    },
    "force10e1200" => {
        "moduleSlots"           => 14,  # Max # of modules in chassis
        "maxPortsPerModule"     => 48,  # Max # of ports in any module
        "bitmaskBitsPerModule"  => 96,  # Number of bits per module
69
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
70
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
71
    },
72 73
    "force10s55" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
74 75
        "maxPortsPerModule"     => 64,  # Max # of ports in any module
        "bitmaskBitsPerModule"  => 768, # Number of bits per module
76
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
77
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
78
    },
79 80 81
    "force10-z9000" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
        "maxPortsPerModule"     => 128, # Max # of ports in any module
82
        "bitmaskBitsPerModule"  => 1024, # Number of bits per module
83
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
84
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
85 86 87 88 89 90
    },
    "force10-z9500" => {
        "moduleSlots"           => 3,   # Max # of modules in chassis
        "maxPortsPerModule"     => 192, # Max # of ports in any module
        "bitmaskBitsPerModule"  => 192, # Number of bits per module
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
91
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
92
    },
93 94 95 96
    "force10-s6000" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
        "maxPortsPerModule"     => 128, # Max # of ports in any module
        "bitmaskBitsPerModule"  => 1024, # Number of bits per module
97
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
98
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
99 100 101 102 103 104
    },
    "force10-s3048" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
        "maxPortsPerModule"     => 52,  # Max # of ports in any module
        "bitmaskBitsPerModule"  => 1024, # Number of bits per module
	"zeroBased"             => 0,   # Whether ports/mods are 0 or 1-based
105 106 107 108 109 110 111 112
	"nybbleEncoded"         => 0,   # Nybble-per-phy-port PortSet encoding
    },
    "force10-z9100" => {
        "moduleSlots"           => 1,   # Max # of modules in chassis
        "maxPortsPerModule"     => 128, # Max # of ports in any module
        "bitmaskBitsPerModule"  => 512, # Number of bits per module
	"zeroBased"             => 1,   # Whether ports/mods are 0 or 1-based
	"nybbleEncoded"         => 1,   # Nybble-per-phy-port PortSet encoding
113
    },
114 115 116
};

#
117 118 119
# 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
120 121 122
#
my $vlanStaticNamePrefix = "emuID";

123 124 125 126
# 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";

127 128 129 130 131 132 133 134 135 136 137 138 139 140
#
# 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;
141
my $PORT_FORMAT_PORT     = 3;
142

143 144 145
# OpenFlow constants
my $MAX_OF_ID = 8;

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
#
# 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;

179 180 181
    # List of ports in trunk mode - used as a secondary check.
    $self->{TRUNKS} = {};

182 183 184
    # Mapping from OF instances to vlans.
    $self->{OFMAP} = undef;

185 186 187 188
    # Flag for whether or not the switch uses vlan tags in the Q-BRIDGE-MIB 
    # tables.  This is detected in readifIndex().
    $self->{USEVLANTAGS} = 0;

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    #
    # 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;

213 214 215 216
    # Dynamically determined size of vlan PortSet bit vectors 
    # (see bottom of readifIndex()).
    $self->{PORTSET_NUMBYTES} = 0; 

217 218 219 220 221
    #
    # 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
222
    $self->{POIFINDEX} = {};   # Port channel ifindex map.
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

    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",
242 243
		       "$mibpath/Q-BRIDGE-MIB.txt",
		       "$mibpath/EtherLike-MIB.txt");
244 245 246 247 248 249
    $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});

250 251 252
    $self->{SESS} = new SNMP::Session(DestHost => $self->{NAME},Version => '2c',
				      Timeout => 4000000, Retries=> 12,
				      Community => $self->{COMMUNITY});
253 254 255 256 257

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

262 263
    # Grab our expect object (Ugh... Why Force10, why?)
    # This does not immediately connect to the switch.
264 265
    if (exists($options->{"username"}) && exists($options->{"password"})) {
	my $swcreds = $options->{"username"} . ":" . $options->{"password"};
266 267 268 269 270 271 272 273 274 275 276
	$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";
    }

277 278 279 280 281 282 283 284 285 286 287 288 289 290
    #
    # 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);

291
    if (!$self->readifIndex()) {
Kirk Webb's avatar
Kirk Webb committed
292
	warn "ERROR: Unable to process ifindex table on $self->{NAME}\n";
293 294
	return undef;
    }
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    
    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;
    }
}

318 319 320
##############################################################################
## Internal / Utility Functions Section
##
321 322 323 324 325 326 327 328 329 330

#
# 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($) {
331
    my $self = shift;
332
    my $vlan1ifIndex = 0;
Kirk Webb's avatar
Kirk Webb committed
333 334
    my $id = "$self->{NAME}::readifIndex()";
    $self->debug("$id:\n",2);
335
        
336
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},["ifDescr"]);
337
    
338
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
339 340
	warn "$id: ERROR: No interface description rows returned ".
	     "while attempting to build ifindex table.\n";
341 342
	return 0;
    }
343

344
    foreach my $result (@{$rows}) {
345
	my ($name,$iid,$descr) = @{$result};
346
	$self->debug("got $name, $iid, descr $descr\n",2);
347
	if ($name ne "ifDescr") {
Kirk Webb's avatar
Kirk Webb committed
348
	    warn "$id: WARNING: Foreign snmp var returned: $name";
349 350 351 352
	    return 0;
	}
	
	# will match "GigabitEthernet 9/47" but not "Vlan 123"
353
	if ($descr =~ /(\w*)\s*(\d+)\/(\d+)\/?(\d+)?$/) {
354 355
	    my $type = $1;
	    my $module = $2;
356
	    my $port = defined($4) ? $4 : $3;
357 358 359 360 361 362 363 364 365 366 367 368 369
	    # Handle nybble-based encoding. I've only seen this on
	    # Z9100 switches so far.  The port numbering scheme on the
	    # z9100 is also one-based, but that doesn't work well when
	    # converting to this nybble scheme, so just force to
	    # zero-based. The DB must list these ports according to
	    # the converted value anyway (vs. what the switch reports
	    # directly).
	    if ($ChassisInfo->{$self->{TYPE}}->{nybbleEncoded} == 1) {
		my $base   = (int($3) - 1)*4;
		my $offset = defined($4) ? (int($4) - 1) : 0;
		$port = $base + $offset;
		$module--; # Force module to be zero-based.
	    }
370 371 372 373
	    # Note: Some Force10 switches (versions?) use zero-based
	    #       modules and ports, while others use 1-based. The
	    #       "ChassisInfo" defs above have a variable that
	    #       indicates which switch model is doing what.
374
	    my $modport = "${module}.${port}";
375 376 377 378 379 380 381 382 383
	    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);
	    }
384
	}
385 386 387 388 389 390 391 392 393 394 395 396
	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);
	}
397 398 399 400 401 402 403
	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);
	}
404
	elsif ($descr =~ /vlan 1/i || $descr =~ /vl1/i) {
405 406 407 408 409
	    # Used below to dynamically determine switch's PortSet size.
	    $vlan1ifIndex = $iid;
	}
    }

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    # Determine if vlan tags are used in the Q-BRIDGE-MIB tables, or
    # ifIndexes from IF-MIB.
    ($rows) = snmpitBulkwalkFatal($self->{SESS},["dot1qVlanStaticName"]);
    if (!scalar(@{$rows})) {
	warn "$id: WARNING: No entries in dot1qVlanStaticName table! Can't ".
	     "determine if tags or ifIndexes are in use in the Q-BRIDGE-MIB - ".
	     "assuming not...\n";
	$self->{USEVLANTAGS} = 0;
    } else {
	# First entry SHOULD be that of vlan 1.
	my $vlan1row = (@{$rows})[0];
	my ($oid,$iid,$ifname) = @{$vlan1row};
	$self->debug("got $oid, $iid, ifname $ifname\n",2);
	if ($oid ne "dot1qVlanStaticName") {
	    warn "$id: ERROR: Foreign OID ($oid) returned while attempting ".
		"to access dot1qVlanStaticName table!\n";
	    return 0;
	}
	if ($iid == 1) {
	    if ($ifname ne "Vlan 1") {
		warn "$id: WARNING: $self->{NAME} appears to use vlan tags ".
		     "in Q-BRIDGE tables, but the name for Vlan 1 is not ".
		     "'Vlan 1'. Assuming vlan tags are in use anyway...\n";
	    }
	    $self->debug("Switch $self->{NAME} uses vlan tags in Q-BRIDGE tables.\n");
	    $self->{USEVLANTAGS} = 1;
	} else {
	    if ($iid < 1000000000) {
		warn "$id: WARNING: First entry in dot1qVlanStaticName table ".
		     "on $self->{NAME} is below 1000000000, but not equal ".
		     "to 1 (value: $iid).  We will assume this switch uses ".
		     "vlan tags in the Q-BRIDGE tables anyway...\n";
	    }
	    $self->debug("Switch $self->{NAME} DOES NOT use vlan tags in Q-BRIDGE tables.\n");
	    $self->{USEVLANTAGS} = 0;
	}
    }

448
    # Figure out the size of the vlan PortSet bit vectors.
449
    $vlan1ifIndex = 1 if $self->{USEVLANTAGS};
450 451 452 453 454 455 456 457 458 459 460 461
    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 {
462
	warn "$id: ERROR: Unable to find ifIndex for Vlan 1 - can't determine ".
463 464
	     "PortSet size!\n";
	return 0;
465 466 467 468
    }

    # success
    return 1;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
}

#
# 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
486
    my $id = "$self->{NAME}::convertPortFormat()";
487 488 489 490 491 492 493 494 495 496 497 498 499

    #
    # 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
500
		warn "$id: ERROR: Given a bad list of ports\n";
501 502 503 504 505
		return undef;
    }

    my $input;
    SWITCH: for ($sample) {
506 507 508
	(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
509
	warn "$id: ERROR: Unrecognized input sample: $sample\n";
510
	return undef;
511 512 513 514 515 516
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
517 518
	$self->debug("Not converting, input format = output format\n",2);
	return @ports;
519 520 521
    }

    if ($input == $PORT_FORMAT_IFINDEX) {
522 523 524 525 526 527 528 529 530 531
	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;
	}
532
    } elsif ($input == $PORT_FORMAT_MODPORT) {
533 534 535 536 537 538 539 540 541 542 543 544 545
	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
546 547
	    return map $self->{IFINDEX}{$_->switch_card() .".". 
					$_->switch_port()}, @ports;
548 549
	} elsif ($output == $PORT_FORMAT_MODPORT) {
	    $self->debug("Converting Port to modport\n",2);
Kirk Webb's avatar
Kirk Webb committed
550
	    return map $_->switch_card() .".". $_->switch_port(), @ports;
551
	}
552 553 554 555 556
    }

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

561 562 563 564 565 566 567
#
# 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
568
    my $id = "$self->{NAME}::convertBitmaskToIfindexes()";
569 570 571 572 573 574

    # 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};
575
    my $zeroBased            = $ChassisInfo->{$type}->{zeroBased};
576 577

    my @ifIndexes;
578 579

    my $mod = 0;
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    while ($mod < $moduleSlots) {
        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));

597 598 599 600
            if ( vec($bitmask,$offset,1) ) {
		my $lmod  = $zeroBased ? $mod  : $mod  + 1;
		my $lport = $zeroBased ? $port : $port + 1;
                push @ifIndexes, $self->{IFINDEX}{"${lmod}.${lport}"};
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
            }
            $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
617
    my $id = "$self->{NAME}::convertIfindexesToBitmask()";
618 619 620 621 622 623

    # 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};
624
    my $zeroBased            = $ChassisInfo->{$type}->{zeroBased};
625

626 627
    # Create an all-zero (empty) PortSet bit vector.
    my $bitmask = pack("H*", '00' x $self->{PORTSET_NUMBYTES});
628 629 630 631 632 633 634

    # 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+)/;
635 636
        my $mod  = $zeroBased ? $1 : $1 - 1;
        my $port = $zeroBased ? $2 : $2 - 1;
637 638 639

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

640 641
        if ( $port >= $maxPortsPerModule )
        {
Kirk Webb's avatar
Kirk Webb committed
642
            warn "$id: WARNING: Cannot set port larger than maxport.\n";
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
            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
674 675
	my $id = "$self->{NAME}::bitmasksDiffer()";
	
676 677 678 679 680 681 682 683 684
	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
685
				$self->debug("$id: bit with index $i differs!\n");
686 687 688 689 690 691 692
				$differingBits++;
			}
		}

		return $differingBits;
	}
	else {
Kirk Webb's avatar
Kirk Webb committed
693 694 695
		warn "$id: WARNING: bitmasks to compare have ".
		     "differing length: \$bm1 has last index $#bm1unp ".
		     "and \$bm2 has last index $#bm2unp\n";
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
		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
715 716

    my $id = "$self->{NAME}::checkBits()";
717 718 719 720 721 722 723 724 725 726 727
    
    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
728 729
   		    $self->debug("checkBits(\"on\"): bit with index $i is set!\n");

730
		    if ($bm1unp[$i] != $bm2unp[$i]) {
Kirk Webb's avatar
Kirk Webb committed
731
			$self->debug("checkBits(\"on\"): bit with index $i isn't set in the other bitmask, while it should be!\n");
732 733 734 735 736 737 738 739
			$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
740
			$self->debug("checkBits(\"off\"): bit with index $i is set in the other bitmask, while it shouldn't be!\n");
741 742 743 744 745
			$differingBits++;
		    }
		}
	    }			
	} else {
Kirk Webb's avatar
Kirk Webb committed
746
	    warn "$id: ERROR: invalid requested status argument: $reqStatus\n";
747 748 749 750 751
	    return ($#bm1unp + 1);
	}
	
	return $differingBits;
    } else {
Kirk Webb's avatar
Kirk Webb committed
752
	warn "$id: ERROR: input bitmasks are of differing length!\n";
Kirk Webb's avatar
Kirk Webb committed
753
	$self->debug("$id: \$bm1 has last index $#bm1unp and \$bm2 has last index $#bm2unp\n");
754 755 756 757 758 759
	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.
760 761
sub stripVlanPrefix($) {
    my $vlname = shift;
762

763 764 765
    if ($vlname =~ /^$vlanStaticNamePrefix(\d+)$/) {
	return $1;
    } else {
766
	return $vlname;
767 768
    }
}
769

770 771
# Utility function to strip the static string prefix from a vlan name,
# giving the original Emulab vlan id.
772 773 774 775 776 777
sub addVlanPrefix($) {
    my $vlname = shift;
    
    return $vlanStaticNamePrefix.$vlname;
}

778 779

# Utility function for looking up ifindex for a vlan
780 781 782 783 784
# 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.
785 786
sub getVlanIfindex($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
787
    my $id = "$self->{NAME}::getVlanIfindex()";
788

789 790
    my $table_oid = $self->{USEVLANTAGS} ? "dot1qVlanStaticName" : "ifDescr";

791
    my %results = ();
792
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},[$table_oid]);
793 794
    
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
795
	warn "$id: ERROR: No interface description rows returned (snmp).";
796
	return undef;
797 798 799 800
    }

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

803 804 805 806 807 808 809 810 811
	if ($self->{USEVLANTAGS}) {
	    # Q-BRIDGE indexes are simply the vlan tags.
	    $curvlnum = $iid;
	} else {
	    # If we are iterating over the ifDescr table, these will match
	    # and we will adjust the vlan tag (number) accordingly.
	    next unless ($descr =~ /vlan\s+(\d+)/i || $descr =~ /vl(\d+)/i);
	    $curvlnum = $1;
	}
812

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

815
	if ($vlan_number eq "ALL") {
Kirk Webb's avatar
Kirk Webb committed
816
	    $results{$iid} = $curvlnum;
817 818
	}
	elsif ($curvlnum == $vlan_number) {
819 820 821 822
	    return $iid;
	}
    }

823 824 825 826
    if ($vlan_number eq "ALL") {
	return %results;
    }

827
    # Not found.
828 829 830 831 832 833 834
    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
835 836 837 838 839 840 841 842
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]);
843

Kirk Webb's avatar
Kirk Webb committed
844 845
    if (!$ebitmask || !$ubitmask) {
	warn "$id: ERROR: problem fetching current membership bitmask for vlan with ifindex $vlidx\n";
846 847 848
	return undef;
    }

Kirk Webb's avatar
Kirk Webb committed
849 850 851 852 853
    if ($both) {
	return ($ebitmask, $ubitmask);
    }

    return $ebitmask;
854 855
}

856 857
#
# Utility function to punch in the egress and untagged port memberships
Kirk Webb's avatar
Kirk Webb committed
858 859
# for the given vlan number (tag).  $onoff tells the function how to check
# the resulting membership list ("on" - add; "off" - remove).
860 861 862 863 864 865 866 867 868 869
#
# 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
870 871
sub setPortMembership($$$$$) {
        my ($self, $onoff, $eportmask, $uportmask, $vlifindex) = @_;
Kirk Webb's avatar
Kirk Webb committed
872
	my $id = "$self->{NAME}::setPortMembership()";
Kirk Webb's avatar
Kirk Webb committed
873

Kirk Webb's avatar
Kirk Webb committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
	# 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
896 897 898
	# Grab the number of bits set in the untagged port mask.
	my $setcount = unpack("%32b*", $uportmask);

Kirk Webb's avatar
Kirk Webb committed
899 900 901 902
	$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
903 904
	# The egress ports and untagged ports have to be updated
	# simultaneously.
Kirk Webb's avatar
Kirk Webb committed
905 906 907 908 909 910 911 912
	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
913
	# platform (even when successful).  Not sure why this happens...
Kirk Webb's avatar
Kirk Webb committed
914
	my $status = $self->{SESS}->set($snmpvars);
Kirk Webb's avatar
Kirk Webb committed
915

916 917
	# 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
918
	if (!defined($status)) {
Kirk Webb's avatar
Kirk Webb committed
919
	    $self->debug("$id: Error setting port membership: $self->{SESS}->{ErrorStr}\n");
Kirk Webb's avatar
Kirk Webb committed
920
	}
Kirk Webb's avatar
Kirk Webb committed
921 922 923 924

	# Get the current membership bitmask for this vlan
	my $newmask = $self->getMemberBitmask($vlifindex);
	if (!defined($newmask)) {
Kirk Webb's avatar
Kirk Webb committed
925
		warn "$id: ERROR: failed to get current ".
926
		     "membership bitmask for vlan with ifindex $vlifindex\n";
Kirk Webb's avatar
Kirk Webb committed
927 928 929
		return $setcount;
	}
	
Kirk Webb's avatar
Kirk Webb committed
930 931 932 933
	# 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
934 935 936
					 $newmask);

	if ($failcount) {
Kirk Webb's avatar
Kirk Webb committed
937
		warn "$id: Could not manipulate $failcount ".
938
		     "ports in vlan with ifindex $vlifindex!\n";
Kirk Webb's avatar
Kirk Webb committed
939 940 941 942 943
	}

	return $failcount; # should be 0
}

944 945 946 947 948 949 950
# 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;

951 952
    $self->debug("$id: entering\n");

953 954 955 956 957 958 959
    # Bail now if the list of ports is empty.
    if (!@ports) {
	$self->debug("$id: called with empty port list... ".
		     "Returning success!\n");
	return 0;
    }

960 961 962 963
    my @ifindexes = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
    my $portmask = $self->convertIfindexesToBitmask(\@ifindexes);
    my %vlifindexes = $self->getVlanIfindex("ALL");
    while (my ($vlifidx, $vlnum) = each %vlifindexes) {
964 965
        $self->debug("$id: Attempting to remove @ports from ".
			 "vlan number $vlnum\n");
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
	# 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;
}

992 993 994 995
##############################################################################
## Snmpit API Module Methods Section
##

996 997 998 999 1000 1001 1002 1003 1004
#
# 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
1005
    my $id = "$self->{NAME}::listPorts()";
1006

1007
    my %Nodeports = ();
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
    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
1018
    #			
1019 1020
    foreach $ifIndex (keys %{$self->{PORTINDEX}}) {

1021 1022 1023 1024
	#
	# Skip ports that don't seem to have anything interesting attached
	#
	my ($port) = $self->convertPortFormat($PORT_FORMAT_PORT, $ifIndex);
1025
	my $nodeport = $port->getOtherEndPort();
1026 1027 1028 1029 1030 1031 1032
	if (!defined($port) || !defined($nodeport) || 
	    $port->toString() eq $nodeport->toString()) {
	    $self->debug("Port $port not connected, skipping\n");
	    next;
	}
	$Nodeports{$ifIndex} = $nodeport;

1033
	if ($status = snmpitGetWarn($self->{SESS},["ifAdminStatus",
1034 1035 1036
						   $ifIndex])) {
	    $Able{$ifIndex} = ( $status =~ /up/ ? "yes" : "no" );
	}
1037
    	
1038
	if ($status = snmpitGetWarn($self->{SESS},["ifOperStatus",
1039 1040 1041
						   $ifIndex])) {
	    $Link{$ifIndex} = $status;
	}
1042
		
1043
	if ($status = snmpitGetWarn($self->{SESS},["dot3StatsDuplexStatus",
1044 1045 1046 1047 1048
						   $ifIndex])) {
	    $status =~ s/Duplex//;
	    $duplex{$ifIndex} = $status;
	}
	
1049
	if ($status = snmpitGetWarn($self->{SESS},["ifHighSpeed",
1050 1051 1052 1053 1054
						   $ifIndex])) {
	    $speed{$ifIndex} = $status . "Mbps";
	}
    }
    
1055 1056 1057 1058 1059
    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
1060 1061 1062 1063
    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}];
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    }
    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
1077 1078
	my $id = "$self->{NAME}::listVlans()";
	$self->debug("\n$id:\n",2);
1079 1080 1081 1082 1083 1084 1085 1086
	
	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
1087
	# scratch each time instead of being stored in a hash by the constructor
1088
	my ($results) = snmpitBulkwalkWarn($self->{SESS}, ["dot1qVlanStaticName"]);
1089 1090

	# $name should always be "dot1qVlanStaticName"
1091 1092
	foreach my $result (@{$results}) {
	    my ($name,$iid,$vlanname) = @{$result};
Kirk Webb's avatar
Kirk Webb committed
1093
	    $self->debug("$id: got $name, $iid, name $vlanname\n",2);
1094
	    if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
1095
		warn "$id: WARNING: unexpected oid: $name\n";
1096 1097 1098 1099 1100 1101 1102
		next;
	    }

	    # Must strip the prefix required on the Force10 to get the vlan id
	    # as known by Emulab.
	    $vlanname = stripVlanPrefix($vlanname);
	    $Names{$iid} = $vlanname;
1103 1104 1105 1106
	}
	
	my ($ifIndex, $status);
	
1107 1108 1109 1110 1111
	# Get corresponding VLAN numbers (i.e. the "real" vlan tags as known 
	# by the switch). Note that this may be a no-op mapping if we
	# previously determined that the switch uses vlan tags in the
	# Q-BRIDGE-MIB tables.
	my %vlanmap = $self->getVlanIfindex("ALL");
1112
	foreach $ifIndex (keys %Names) {
1113 1114
	    if (exists($vlanmap{$ifIndex})) {
		$Numbers{$ifIndex} = $vlanmap{$ifIndex};
1115
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1116
		warn "$id: ERROR: Unable to get vlan tag for ifindex $ifIndex\n";
1117 1118
		return undef;
	    }
1119 1120
	}
	
1121
	# Get corresponding port bitmaps from dot1qVlanStaticEgressPorts
1122 1123
	# and find out the corresponding port ifIndexes
	foreach $ifIndex (keys %Names) {
1124 1125 1126
	    my $membermask = $self->getMemberBitmask($ifIndex);
	    if (defined($membermask)) {
		my $indexes = $self->convertBitmaskToIfindexes($membermask);
1127 1128 1129
		my @ports = $self->convertPortFormat($PORT_FORMAT_PORT, 
						     @{$indexes});
		$Members{$ifIndex} = \@ports;
1130
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1131
		warn "$id: ERROR: Unable to get port membership for ifindex $ifIndex\n";
1132 1133
		return undef;
	    }
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	}
	
	# 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($$) {
1154
    my ($self, $vlan_number) = @_;
1155

1156 1157 1158
    # resolve the vlan number to an ifindex.  If no result, then no vlan...
    if (defined($self->getVlanIfindex($vlan_number))) {
	return 1;
1159
    } else {
1160
    	return 0;
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    }
}

#
# 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
1176 1177
    my %vlanmap = ();
    my $id = "$self->{NAME}::findVlans()";
1178 1179 1180

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

1186 1187
    foreach my $result (@{$results}) {
	my ($name,$iid,$vlanname) = @{$result};
1188
	$self->debug("findVlans(): got $name, $iid, name $vlanname\n",2);
1189
	if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
1190
	    warn "$id: WARNING: unexpected oid: $name\n";
1191
	    next;
1192 1193
	}

1194 1195 1196 1197 1198 1199 1200
	# 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
1201
	    $vlanmap{$vlanname} = $vlidx2num{$iid};
1202 1203 1204
	}
    }

Kirk Webb's avatar
Kirk Webb committed
1205
    return %vlanmap;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
}

#
# 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($$;$) { 
1218 1219 1220 1221 1222 1223 1224
    my $self = shift;
    my $vlan_id = shift;
    my $no_retry = shift;
    
    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
1225
    } else {
1226
	$max_tries = 10;
1227 1228
    }

1229 1230 1231
    # 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) {
1232

1233 1234 1235 1236
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
	}
1237

1238 1239
	# Wait before we try again
	if ($try < $max_tries) {
Kirk Webb's avatar
Kirk Webb committed
1240
	    $self->debug("findVlan: failed, trying again\n");
1241
	    sleep 1;
1242
	}
1243
    }
1244

1245 1246
    # Didn't find it
    return undef;
1247 1248
}

1249 1250 1251 1252 1253 1254
#
# Determine if a VLAN has any members 
# (Used by stack->switchesWithPortsInVlan())
#
sub vlanHasPorts($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
1255
    my $id = "$self->{NAME}::vlanHasPorts()";
1256 1257 1258

    my $vlifindex = $self->getVlanIfindex($vlan_number);
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1259
	warn "$id: ERROR: Could not lookup vlan index for vlan: $vlan_number\n";
1260 1261 1262 1263 1264
	return 0;
    }

    my $membermask = $self->getMemberBitmask($vlifindex);
    if (!defined($membermask)) {
1265
	warn "$id: ERROR: Could not get membership bitmask for vlan: $vlan_number\n";
1266 1267
	return 0;
    }
1268
    my $setcount = unpack("%32b*", $membermask);
1269 1270 1271 1272

    return $setcount ? 1 : 0;
}

1273 1274
#
# Create a VLAN on this switch, with the given identifier (which comes from
1275
# the database) and given 802.1Q tag number ($vlan_number). 
1276
#
1277
# usage: createVlan($self, $vlan_id, $vlan_number)
1278 1279 1280
#        returns the new VLAN number on success
#        returns 0 on failure
#
1281
sub createVlan($$$;$) {
1282 1283 1284 1285 1286
    my $self = shift;
    
    # as known in db and as will be saved in administrative vlan
    # name on switch
    my $vlan_id = shift;
1287

1288 1289
    # 802.1Q vlan tag
    my $vlan_number = shift; 
Kirk Webb's avatar
Kirk Webb committed
1290

1291 1292 1293
    # Grab any additional settings for vlan.
    my $otherargs = shift;

Kirk Webb's avatar
Kirk Webb committed
1294
    my $id = "$self->{NAME}::createVlan()";
1295
	
1296 1297
    # Check to see if the requested vlan number already exists.
    if ($self->vlanNumberExists($vlan_number)) {
Kirk Webb's avatar
Kirk Webb committed
1298
	warn "$id: ERROR: VLAN $vlan_number already exists\n";
1299 1300
	return 0;
    }
1301

1302 1303 1304 1305 1306 1307 1308 1309
    # Was OpenFlow requested?  If so then we have to create an OF instance
    # first and use CLI commands to create an OF-associated VLAN.  Thanks
    # FTOS...
    if ($otherargs && ref($otherargs) eq 'HASH' && 
	exists($otherargs->{"ofenabled"}) && $otherargs->{"ofenabled"} == 1) {
	return $self->createOFVlan($vlan_id, $vlan_number);
    }

1310 1311 1312 1313 1314 1315
    # 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
1316
	warn "$id: ERROR: VLAN Create id '$vlan_id' as VLAN $vlan_number failed.\n";
1317 1318
	return 0;
    }
1319 1320 1321

    # trying to use static ifindex offsets for vlans is unreliable.
    my $vlifindex = $self->getVlanIfindex($vlan_number);
1322
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1323
	warn "$id: ERROR: Could not lookup ifindex for vlan number: $vlan_number\n";
1324 1325
	return 0;
    }
1326 1327 1328 1329 1330 1331
    
    # 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", 
1332
					   $vlifindex,
1333 1334 1335 1336 1337
					   $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
1338
	warn "$id: ERROR: Setting VLAN name to '$vlan_id' failed, ".
1339 1340
	     "but VLAN $vlan_number was created! ".
	     "Manual cleanup required.\n";
1341 1342
	return 0;
    }
1343

1344
    return $vlan_number;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
}

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

Kirk Webb's avatar
Kirk Webb committed
1359
    $self->debug("$id: entering\n");
1360

1361 1362 1363 1364 1365 1366 1367
    # 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);
    }
1368

1369 1370 1371
    # 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.
1372
    my @portlist = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
Kirk Webb's avatar
Kirk Webb committed
1373
    my @portobjs = $self->convertPortFormat($PORT_FORMAT_PORT, @ports);
Kirk Webb's avatar
Kirk Webb committed
1374 1375
    $self->debug("$id: input ports: " . join(",",@ports) . "\n");
    $self->debug("$id: as ifIndexes: " . join(",",@portlist) . "\n");
1376

Kirk Webb's avatar
Kirk Webb committed
1377 1378 1379 1380 1381
    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);
    }

1382
    # Create a bitmask from this ifIndex list
1383
    my $portmask = $self->convertIfindexesToBitmask(\@portlist);
1384

Kirk Webb's avatar
Kirk Webb committed
1385 1386 1387 1388 1389
    # 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 = ();
1390
    my @upobjs = ();
Kirk Webb's avatar
Kirk Webb committed
1391
    foreach my $pobj (@portobjs) {
1392 1393
	if ($pobj->tagged() == 0 && 
	    !exists($self->{TRUNKS}->{$portlist[$i]})) {
1394
	    $self->debug("id: Adding port $pobj as untagged to $vlan_number\n",2);
Kirk Webb's avatar
Kirk Webb committed
1395
	    push @uportlist, $portlist[$i];
1396
	    push @upobjs, $pobj;
Kirk Webb's avatar
Kirk Webb committed
1397 1398 1399
	}
	$i++;
    }
1400
    my $uportmask = $self->convertIfindexesToBitmask(\@uportlist);
1401

1402 1403 1404 1405 1406
    # 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
1407

1408 1409 1410 1411 1412 1413 1414 1415 1416
    # 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);
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
}

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

Kirk Webb's avatar
Kirk Webb committed
1431 1432 1433
	# 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
1434
	    warn "$id: WARNING: Attempt made to remove @ports from default VLAN 1\n";
Kirk Webb's avatar
Kirk Webb committed
1435 1436
	    return 0;
	}
1437 1438 1439 1440

	# 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
1441 1442
	$self->debug("$id: removing ports from vlan $vlan_number: @ports\n");
	$self->debug("$id: port ifIndexes: @portlist\n");
1443 1444 1445
	
	# Create a bitmask from this ifIndex list
	my $bitmaskToRemove = $self->convertIfindexesToBitmask(\@portlist);
Kirk Webb's avatar
Kirk Webb committed
1446 1447

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

1451
	# Get the vlan's ifindex.
1452
	my $vlanIfindex = $self->getVlanIfindex($vlan_number);
1453
	if (!defined($vlanIfindex)) {
Kirk Webb's avatar
Kirk Webb committed
1454
	    warn "$id: ERROR: Could not get ifindex for vlan number $vlan_number!\n";
1455 1456
	    return scalar(@ports);
	}
1457

1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
	# 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);
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
}


#
# 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
1494
	my $id = "$self->{NAME}::removeVlan()";
1495 1496

	foreach my $vlan_number (@vlan_numbers) {
1497 1498
	        # We won't remove vlan 1.
	        next if $vlan_number == 1;
1499
		# Calculate ifIndex for this VLAN
1500
		my $ifIndex = $self->getVlanIfindex($vlan_number);
1501
		if (!defined($ifIndex)) {
Kirk Webb's avatar
Kirk Webb committed
1502
		    warn "$id: ERROR: Problem looking up vlan ifindex for vlan number $vlan_number.\n";
1503 1504 1505
		    $errors++;
		    next;
		}
1506 1507 1508 1509 1510 1511
		
		# 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
1512
		$RetVal = snmpitSetWarn($self->{SESS},
Kirk Webb's avatar
Kirk Webb committed
1513
				[$DeleteOID,$ifIndex,"destroy","INTEGER"]);
1514 1515
		# $RetVal should contain "0 but true" if successful	
		if ( defined($RetVal) ) { 
Kirk Webb's avatar
Kirk Webb committed
1516
			print "Removed VLAN $vlan_number on switch $self->{NAME}.\n";
1517
		} else {
Kirk Webb's avatar
Kirk Webb committed
1518
		    warn "$id: ERROR: Removal of VLAN $vlan_number failed.\n";
1519 1520
		    $errors++;
		    next;
1521
		}
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538

		# If a prior operation, e.g. disableOpenflow(), has
		# loaded the OFMAP, then search it to see if there is
		# an associated OF instance and remove it if so.  We
		# don't want to load the OFMAP if it hasn't been loaded
		# because it is an expensive CLI-based operation.
		my $ofid = 0;
		if ($self->{OFMAP} && ($ofid = $self->vlan2OFID($vlan_number)) > 0) {
		    my $cmd = "no openflow of-instance $ofid";
		    my ($fail, $output) = $self->{EXP_OBJ}->doCLICmd($cmd, 1);
		    if ($fail) {
			warn "$id: ERROR: Failed to remove OFID $ofid for vlan $vlan_number: $output\n";
			$errors++;
		    } else {
			delete $self->{OFMAP}->{$ofid};
		    }
		}
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	}
	
	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($@) {
1553 1554 1555
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
Kirk Webb's avatar
Kirk Webb committed
1556
    my $id = "$self->{NAME}::removePortsFromVlan()";
1557 1558

    foreach my $vlan_number (@vlan_numbers) {
Kirk Webb's avatar
Kirk Webb committed
1559
    	$self->debug("$id: attempting to remove all ports from vlan_number $vlan_number\n");
1560
    	
1561 1562 1563
	# 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
1564
	    warn "$id: WARNING: Attempt made to remove all ports from default VLAN 1\n";
1565 1566
	    next;
	}
Kirk Webb's avatar
Kirk Webb committed
1567 1568

	# Get the ifindex of the vlan.
1569 1570
	my $vlanIfindex = $self->getVlanIfindex($vlan_number);
	if (!defined($vlanIfindex)) {
Kirk Webb's avatar
Kirk Webb committed
1571
	    warn "$id: WARNING: Could not get ifindex for vlan number $vlan_number!\n";
1572 1573
	    next;
	}
Kirk Webb's avatar
Kirk Webb committed
1574
	
1575 1576
	# Get the current membership bitmask and convert to a list of
	# port ifindexes to pass to removeSomePortsFromVlan()
1577
	my $currentBitmask = $self->getMemberBitmask($vlanIfindex);
1578 1579
	my $portlist = $self->convertBitmaskToIfindexes($currentBitmask);
	$errors