snmpit_force10.pm 73 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
    },
Kirk Webb's avatar
Kirk Webb committed
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
Kirk Webb's avatar
Kirk Webb committed
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
    #
    # 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
    #
Kirk Webb's avatar
Kirk Webb committed
282
283
284
285
286
287
288
289
    my $sysdetails = snmpitGetFatal($self->{SESS},["sysDescr",0],30);
    if ($sysdetails !~ /Application Software Version:\s+(\d+)\.(\d+)(\S+)/i) {
	warn "Could not determine FTOS version for $self->{NAME}!\n";
	return undef;
    }
    $self->{OSVER} = "$1.$2$3";
    $self->{OSMAJOR} = int($1);
    $self->{OSMINOR} = int($2);
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

    # Forward- and backward-compat-breaking updates by Dell to comply 
    # with RFC2579. FTOS 9.10+
    $self->{DO_RFC2579} = 
	($self->{OSMAJOR} >= 10 || 
	 ($self->{OSMAJOR} == 9 && $self->{OSMINOR} >= 10))
	? 1 : 0;
    # Forward- and backward-compat-breaking updates by Dell to fix
    # port removal logic to be standards-compliant (has been wrong for
    # years). FTOS 9.11+
    $self->{DO_COMPLIANT_PORTSETS} = 
	($self->{OSMAJOR} >= 10 ||
	 ($self->{OSMAJOR} == 9 && $self->{OSMINOR} >= 11))
	? 1 : 0;

Kirk Webb's avatar
Kirk Webb committed
305
    print "Switch $self->{NAME} is running $self->{OSVER}\n" if $self->{DEBUG};
306
307
308
309
310
311
312

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

313
    if (!$self->readifIndex()) {
Kirk Webb's avatar
Kirk Webb committed
314
	warn "ERROR: Unable to process ifindex table on $self->{NAME}\n";
315
316
	return undef;
    }
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    
    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;
    }
}

340
341
342
##############################################################################
## Internal / Utility Functions Section
##
343
344
345
346
347
348
349
350
351
352

#
# 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($) {
353
    my $self = shift;
354
    my $vlan1ifIndex = 0;
Kirk Webb's avatar
Kirk Webb committed
355
356
    my $id = "$self->{NAME}::readifIndex()";
    $self->debug("$id:\n",2);
357
        
358
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},["ifDescr"]);
359
    
360
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
361
362
	warn "$id: ERROR: No interface description rows returned ".
	     "while attempting to build ifindex table.\n";
363
364
	return 0;
    }
365

366
    foreach my $result (@{$rows}) {
367
	my ($name,$iid,$descr) = @{$result};
368
	$self->debug("got $name, $iid, descr $descr\n",2);
369
	if ($name ne "ifDescr") {
Kirk Webb's avatar
Kirk Webb committed
370
	    warn "$id: WARNING: Foreign snmp var returned: $name";
371
372
373
374
	    return 0;
	}
	
	# will match "GigabitEthernet 9/47" but not "Vlan 123"
375
	if ($descr =~ /(\w*)\s*(\d+)\/(\d+)\/?(\d+)?$/) {
376
377
	    my $type = $1;
	    my $module = $2;
378
	    my $port = defined($4) ? $4 : $3;
379
380
381
382
383
384
385
386
387
388
389
390
391
	    # 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.
	    }
392
393
394
395
	    # 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.
396
	    my $modport = "${module}.${port}";
397
398
399
400
401
402
403
404
405
	    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);
	    }
406
	}
407
408
409
410
411
412
413
414
415
416
417
418
	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);
	}
419
420
421
422
423
424
425
	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);
	}
426
	elsif ($descr =~ /vlan 1/i || $descr =~ /vl1/i) {
427
428
429
430
431
	    # Used below to dynamically determine switch's PortSet size.
	    $vlan1ifIndex = $iid;
	}
    }

432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
    # 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;
	}
    }

470
    # Figure out the size of the vlan PortSet bit vectors.
471
    $vlan1ifIndex = 1 if $self->{USEVLANTAGS};
472
473
474
475
476
477
478
479
480
481
482
483
    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 {
484
	warn "$id: ERROR: Unable to find ifIndex for Vlan 1 - can't determine ".
485
486
	     "PortSet size!\n";
	return 0;
487
488
489
490
    }

    # success
    return 1;
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
}

#
# 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
508
    my $id = "$self->{NAME}::convertPortFormat()";
509
510
511
512
513
514
515
516
517
518
519
520
521

    #
    # 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
522
		warn "$id: ERROR: Given a bad list of ports\n";
523
524
525
526
527
		return undef;
    }

    my $input;
    SWITCH: for ($sample) {
528
529
530
	(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
531
	warn "$id: ERROR: Unrecognized input sample: $sample\n";
532
	return undef;
533
534
535
536
537
538
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
539
540
	$self->debug("Not converting, input format = output format\n",2);
	return @ports;
541
542
543
    }

    if ($input == $PORT_FORMAT_IFINDEX) {
544
545
546
547
548
549
550
551
552
553
	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;
	}
554
    } elsif ($input == $PORT_FORMAT_MODPORT) {
555
556
557
558
559
560
561
562
563
564
565
566
567
	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
568
569
	    return map $self->{IFINDEX}{$_->switch_card() .".". 
					$_->switch_port()}, @ports;
570
571
	} elsif ($output == $PORT_FORMAT_MODPORT) {
	    $self->debug("Converting Port to modport\n",2);
Kirk Webb's avatar
Kirk Webb committed
572
	    return map $_->switch_card() .".". $_->switch_port(), @ports;
573
	}
574
575
576
577
578
    }

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

583
584
585
586
587
588
589
#
# 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
590
    my $id = "$self->{NAME}::convertBitmaskToIfindexes()";
591
592
593
594
595
596

    # 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};
597
    my $zeroBased            = $ChassisInfo->{$type}->{zeroBased};
598
599

    my @ifIndexes;
600
601

    my $mod = 0;
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    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));

619
620
621
622
            if ( vec($bitmask,$offset,1) ) {
		my $lmod  = $zeroBased ? $mod  : $mod  + 1;
		my $lport = $zeroBased ? $port : $port + 1;
                push @ifIndexes, $self->{IFINDEX}{"${lmod}.${lport}"};
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
            }
            $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
639
    my $id = "$self->{NAME}::convertIfindexesToBitmask()";
640
641
642
643
644
645

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

648
649
    # Create an all-zero (empty) PortSet bit vector.
    my $bitmask = pack("H*", '00' x $self->{PORTSET_NUMBYTES});
650
651
652
653
654
655
656

    # 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+)/;
657
658
        my $mod  = $zeroBased ? $1 : $1 - 1;
        my $port = $zeroBased ? $2 : $2 - 1;
659
660
661

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

662
663
        if ( $port >= $maxPortsPerModule )
        {
Kirk Webb's avatar
Kirk Webb committed
664
            warn "$id: WARNING: Cannot set port larger than maxport.\n";
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
            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
696
697
	my $id = "$self->{NAME}::bitmasksDiffer()";
	
698
699
700
701
702
703
704
705
706
	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
707
				$self->debug("$id: bit with index $i differs!\n");
708
709
710
711
712
713
714
				$differingBits++;
			}
		}

		return $differingBits;
	}
	else {
Kirk Webb's avatar
Kirk Webb committed
715
716
717
		warn "$id: WARNING: bitmasks to compare have ".
		     "differing length: \$bm1 has last index $#bm1unp ".
		     "and \$bm2 has last index $#bm2unp\n";
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
		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
737
738

    my $id = "$self->{NAME}::checkBits()";
739
740
741
742
743
744
745
746
747
748
749
    
    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
750
751
   		    $self->debug("checkBits(\"on\"): bit with index $i is set!\n");

752
		    if ($bm1unp[$i] != $bm2unp[$i]) {
Kirk Webb's avatar
Kirk Webb committed
753
			$self->debug("checkBits(\"on\"): bit with index $i isn't set in the other bitmask, while it should be!\n");
754
755
756
757
758
759
760
761
			$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
762
			$self->debug("checkBits(\"off\"): bit with index $i is set in the other bitmask, while it shouldn't be!\n");
763
764
765
766
767
			$differingBits++;
		    }
		}
	    }			
	} else {
Kirk Webb's avatar
Kirk Webb committed
768
	    warn "$id: ERROR: invalid requested status argument: $reqStatus\n";
769
770
771
772
773
	    return ($#bm1unp + 1);
	}
	
	return $differingBits;
    } else {
Kirk Webb's avatar
Kirk Webb committed
774
	warn "$id: ERROR: input bitmasks are of differing length!\n";
Kirk Webb's avatar
Kirk Webb committed
775
	$self->debug("$id: \$bm1 has last index $#bm1unp and \$bm2 has last index $#bm2unp\n");
776
777
778
779
780
781
	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.
782
783
sub stripVlanPrefix($) {
    my $vlname = shift;
784

785
786
787
    if ($vlname =~ /^$vlanStaticNamePrefix(\d+)$/) {
	return $1;
    } else {
788
	return $vlname;
789
790
    }
}
791

792
793
# Utility function to strip the static string prefix from a vlan name,
# giving the original Emulab vlan id.
794
795
796
797
798
799
sub addVlanPrefix($) {
    my $vlname = shift;
    
    return $vlanStaticNamePrefix.$vlname;
}

800
801

# Utility function for looking up ifindex for a vlan
802
803
804
805
806
# 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.
807
808
sub getVlanIfindex($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
809
    my $id = "$self->{NAME}::getVlanIfindex()";
810

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

813
    my %results = ();
814
    my ($rows) = snmpitBulkwalkFatal($self->{SESS},[$table_oid]);
815
816
    
    if (!$rows || !@{$rows}) {
Kirk Webb's avatar
Kirk Webb committed
817
	warn "$id: ERROR: No interface description rows returned (snmp).";
818
	return undef;
819
820
821
822
    }

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

825
826
827
828
829
830
831
832
833
	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;
	}
834

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

837
	if ($vlan_number eq "ALL") {
Kirk Webb's avatar
Kirk Webb committed
838
	    $results{$iid} = $curvlnum;
839
840
	}
	elsif ($curvlnum == $vlan_number) {
841
842
843
844
	    return $iid;
	}
    }

845
846
847
848
    if ($vlan_number eq "ALL") {
	return %results;
    }

849
    # Not found.
850
851
852
853
854
855
856
    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
857
858
859
860
861
862
863
864
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]);
865

Kirk Webb's avatar
Kirk Webb committed
866
867
    if (!$ebitmask || !$ubitmask) {
	warn "$id: ERROR: problem fetching current membership bitmask for vlan with ifindex $vlidx\n";
868
869
870
	return undef;
    }

Kirk Webb's avatar
Kirk Webb committed
871
872
873
874
875
    if ($both) {
	return ($ebitmask, $ubitmask);
    }

    return $ebitmask;
876
877
}

878
879
#
# Utility function to punch in the egress and untagged port memberships
Kirk Webb's avatar
Kirk Webb committed
880
881
# for the given vlan number (tag).  $onoff tells the function how to check
# the resulting membership list ("on" - add; "off" - remove).
882
883
884
885
886
887
888
889
890
891
#
# 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
892
893
sub setPortMembership($$$$$) {
        my ($self, $onoff, $eportmask, $uportmask, $vlifindex) = @_;
Kirk Webb's avatar
Kirk Webb committed
894
	my $id = "$self->{NAME}::setPortMembership()";
Kirk Webb's avatar
Kirk Webb committed
895
	my $status = 0;
Kirk Webb's avatar
Kirk Webb committed
896

Kirk Webb's avatar
Kirk Webb committed
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
	# 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
919
920
921
	# Grab the number of bits set in the untagged port mask.
	my $setcount = unpack("%32b*", $uportmask);

Kirk Webb's avatar
Kirk Webb committed
922
923
924
925
	$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
926
927
	# The egress ports and untagged ports have to be updated
	# simultaneously.
Kirk Webb's avatar
Kirk Webb committed
928
929
930
931
932
933
	my $snmpvars = new SNMP::VarList(
	    ["dot1qVlanStaticEgressPorts", $vlifindex, 
	     $eportmask, "OCTETSTR"], 
	    ["dot1qVlanStaticUntaggedPorts", $vlifindex, 
	     $uportmask, "OCTETSTR"]);

Kirk Webb's avatar
Kirk Webb committed
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
	# Take vlan out of service, if necessary.
	if ($self->{DO_RFC2579}) {
	    $status = snmpitGetWarn($self->{SESS}, 
				    ["dot1qVlanStaticRowStatus", $vlifindex]);
	    $self->debug("$id: vlan $vlifindex status is: $status\n");
	    if ($status =~ /active/i) {
		$status = snmpitSetWarn($self->{SESS}, 
					["dot1qVlanStaticRowStatus",
					 $vlifindex, "notInService",
					 "INTEGER"]);
		if (!$status) {
		    warn "$id: ERROR: failed to take vlan $vlifindex out of service\n";
		    return $setcount;
		}
	    }
	}

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

956
957
	# 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
958
	if (!defined($status)) {
Kirk Webb's avatar
Kirk Webb committed
959
	    $self->debug("$id: Error setting port membership: $self->{SESS}->{ErrorStr}\n");
Kirk Webb's avatar
Kirk Webb committed
960
	}
Kirk Webb's avatar
Kirk Webb committed
961
962
963
964

	# Get the current membership bitmask for this vlan
	my $newmask = $self->getMemberBitmask($vlifindex);
	if (!defined($newmask)) {
Kirk Webb's avatar
Kirk Webb committed
965
		warn "$id: ERROR: failed to get current ".
966
		     "membership bitmask for vlan with ifindex $vlifindex\n";
Kirk Webb's avatar
Kirk Webb committed
967
968
969
		return $setcount;
	}
	
Kirk Webb's avatar
Kirk Webb committed
970
971
972
973
	# 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
974
975
976
					 $newmask);

	if ($failcount) {
Kirk Webb's avatar
Kirk Webb committed
977
		warn "$id: Could not manipulate $failcount ".
978
		     "ports in vlan with ifindex $vlifindex!\n";
Kirk Webb's avatar
Kirk Webb committed
979
980
	}

Kirk Webb's avatar
Kirk Webb committed
981
982
983
984
985
986
987
988
989
990
991
992
993
	# Put vlan back in service, if necessary. Don't attempt if
	# all ports have been removed.
	if ($self->{DO_RFC2579} && unpack("%32b*", $newmask)) {
	    $status = snmpitSetWarn($self->{SESS}, 
				    ["dot1qVlanStaticRowStatus",
				     $vlifindex, "active",
				     "INTEGER"]);
	    if (!$status) {
		warn "$id: ERROR: failed to put vlan $vlifindex back in service\n";
		return $setcount;
	    }
	}

Kirk Webb's avatar
Kirk Webb committed
994
995
996
	return $failcount; # should be 0
}

997
998
999
1000
1001
1002
1003
# 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;

1004
1005
    $self->debug("$id: entering\n");

1006
1007
1008
1009
1010
1011
1012
    # Bail now if the list of ports is empty.
    if (!@ports) {
	$self->debug("$id: called with empty port list... ".
		     "Returning success!\n");
	return 0;
    }

1013
1014
1015
1016
    my @ifindexes = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
    my $portmask = $self->convertIfindexesToBitmask(\@ifindexes);
    my %vlifindexes = $self->getVlanIfindex("ALL");
    while (my ($vlifidx, $vlnum) = each %vlifindexes) {
1017
1018
        $self->debug("$id: Attempting to remove @ports from ".
			 "vlan number $vlnum\n");
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
	# 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;
}

1045
1046
1047
1048
##############################################################################
## Snmpit API Module Methods Section
##

1049
1050
1051
1052
1053
1054
1055
1056
1057
#
# 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
1058
    my $id = "$self->{NAME}::listPorts()";
1059

1060
    my %Nodeports = ();
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
    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
1071
    #			
1072
1073
    foreach $ifIndex (keys %{$self->{PORTINDEX}}) {

1074
1075
1076
1077
	#
	# Skip ports that don't seem to have anything interesting attached
	#
	my ($port) = $self->convertPortFormat($PORT_FORMAT_PORT, $ifIndex);
1078
	my $nodeport = $port->getOtherEndPort();
1079
1080
1081
1082
1083
1084
1085
	if (!defined($port) || !defined($nodeport) || 
	    $port->toString() eq $nodeport->toString()) {
	    $self->debug("Port $port not connected, skipping\n");
	    next;
	}
	$Nodeports{$ifIndex} = $nodeport;

1086
	if ($status = snmpitGetWarn($self->{SESS},["ifAdminStatus",
1087
1088
1089
						   $ifIndex])) {
	    $Able{$ifIndex} = ( $status =~ /up/ ? "yes" : "no" );
	}
1090
    	
1091
	if ($status = snmpitGetWarn($self->{SESS},["ifOperStatus",
1092
1093
1094
						   $ifIndex])) {
	    $Link{$ifIndex} = $status;
	}
1095
		
1096
	if ($status = snmpitGetWarn($self->{SESS},["dot3StatsDuplexStatus",
1097
1098
1099
1100
1101
						   $ifIndex])) {
	    $status =~ s/Duplex//;
	    $duplex{$ifIndex} = $status;
	}
	
1102
	if ($status = snmpitGetWarn($self->{SESS},["ifHighSpeed",
1103
1104
1105
1106
1107
						   $ifIndex])) {
	    $speed{$ifIndex} = $status . "Mbps";
	}
    }
    
1108
1109
1110
1111
1112
    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
1113
1114
1115
1116
    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}];
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
    }
    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
1130
1131
	my $id = "$self->{NAME}::listVlans()";
	$self->debug("\n$id:\n",2);
1132
1133
1134
1135
1136
1137
1138
1139
	
	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
1140
	# scratch each time instead of being stored in a hash by the constructor
1141
	my ($results) = snmpitBulkwalkWarn($self->{SESS}, ["dot1qVlanStaticName"]);
1142
1143

	# $name should always be "dot1qVlanStaticName"
1144
1145
	foreach my $result (@{$results}) {
	    my ($name,$iid,$vlanname) = @{$result};
Kirk Webb's avatar
Kirk Webb committed
1146
	    $self->debug("$id: got $name, $iid, name $vlanname\n",2);
1147
	    if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
1148
		warn "$id: WARNING: unexpected oid: $name\n";
1149
1150
1151
1152
1153
1154
1155
		next;
	    }

	    # Must strip the prefix required on the Force10 to get the vlan id
	    # as known by Emulab.
	    $vlanname = stripVlanPrefix($vlanname);
	    $Names{$iid} = $vlanname;
1156
1157
1158
1159
	}
	
	my ($ifIndex, $status);
	
1160
1161
1162
1163
1164
	# 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");
1165
	foreach $ifIndex (keys %Names) {
1166
1167
	    if (exists($vlanmap{$ifIndex})) {
		$Numbers{$ifIndex} = $vlanmap{$ifIndex};
1168
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1169
		warn "$id: ERROR: Unable to get vlan tag for ifindex $ifIndex\n";
1170
1171
		return undef;
	    }
1172
1173
	}
	
1174
	# Get corresponding port bitmaps from dot1qVlanStaticEgressPorts
1175
1176
	# and find out the corresponding port ifIndexes
	foreach $ifIndex (keys %Names) {
1177
1178
1179
	    my $membermask = $self->getMemberBitmask($ifIndex);
	    if (defined($membermask)) {
		my $indexes = $self->convertBitmaskToIfindexes($membermask);
1180
1181
1182
		my @ports = $self->convertPortFormat($PORT_FORMAT_PORT, 
						     @{$indexes});
		$Members{$ifIndex} = \@ports;
1183
	    } else {
Kirk Webb's avatar
Kirk Webb committed
1184
		warn "$id: ERROR: Unable to get port membership for ifindex $ifIndex\n";
1185
1186
		return undef;
	    }
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
	}
	
	# 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($$) {
1207
    my ($self, $vlan_number) = @_;
1208

1209
1210
1211
    # resolve the vlan number to an ifindex.  If no result, then no vlan...
    if (defined($self->getVlanIfindex($vlan_number))) {
	return 1;
1212
    } else {
1213
    	return 0;
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
    }
}

#
# 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
1229
1230
    my %vlanmap = ();
    my $id = "$self->{NAME}::findVlans()";
1231
1232
1233

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

1239
1240
    foreach my $result (@{$results}) {
	my ($name,$iid,$vlanname) = @{$result};
1241
	$self->debug("findVlans(): got $name, $iid, name $vlanname\n",2);
1242
	if ($name ne "dot1qVlanStaticName") {
Kirk Webb's avatar
Kirk Webb committed
1243
	    warn "$id: WARNING: unexpected oid: $name\n";
1244
	    next;
1245
1246
	}

1247
1248
1249
1250
1251
1252
1253
	# 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
1254
	    $vlanmap{$vlanname} = $vlidx2num{$iid};
1255
1256
1257
	}
    }

Kirk Webb's avatar
Kirk Webb committed
1258
    return %vlanmap;
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
}

#
# 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($$;$) { 
1271
1272
1273
1274
1275
1276
1277
    my $self = shift;
    my $vlan_id = shift;
    my $no_retry = shift;
    
    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
1278
    } else {
1279
	$max_tries = 10;
1280
1281
    }

1282
1283
1284
    # 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) {
1285

1286
1287
1288
1289
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
	}
1290

1291
1292
	# Wait before we try again
	if ($try < $max_tries) {
Kirk Webb's avatar
Kirk Webb committed
1293
	    $self->debug("findVlan: failed, trying again\n");
1294
	    sleep 1;
1295
	}
1296
    }
1297

1298
1299
    # Didn't find it
    return undef;
1300
1301
}

1302
1303
1304
1305
1306
1307
#
# Determine if a VLAN has any members 
# (Used by stack->switchesWithPortsInVlan())
#
sub vlanHasPorts($$) {
    my ($self, $vlan_number) = @_;
Kirk Webb's avatar
Kirk Webb committed
1308
    my $id = "$self->{NAME}::vlanHasPorts()";
1309
1310
1311

    my $vlifindex = $self->getVlanIfindex($vlan_number);
    if (!defined($vlifindex)) {
Kirk Webb's avatar
Kirk Webb committed
1312
	warn "$id: ERROR: Could not lookup vlan index for vlan: $vlan_number\n";
1313
1314
1315
1316
1317
	return 0;
    }

    my $membermask = $self->getMemberBitmask($vlifindex);
    if (!defined($membermask)) {
1318
	warn "$id: ERROR: Could not get membership bitmask for vlan: $vlan_number\n";
1319
1320
	return 0;
    }
1321
    my $setcount = unpack("%32b*", $membermask);
1322
1323
1324
1325

    return $setcount ? 1 : 0;
}

1326
1327
#
# Create a VLAN on this switch, with the given identifier (which comes from
1328
# the database) and given 802.1Q tag number ($vlan_number). 
1329
#
1330
# usage: createVlan($self, $vlan_id, $vlan_number)
1331
1332
1333
#        returns the new VLAN number on success
#        returns 0 on failure
#
1334
sub createVlan($$$;$) {
1335
1336
1337
1338
1339
    my $self = shift;
    
    # as known in db and as will be saved in administrative vlan
    # name on switch
    my $vlan_id = shift;
1340

1341
1342
    # 802.1Q vlan tag
    my $vlan_number = shift; 
Kirk Webb's avatar
Kirk Webb committed
1343

1344
1345
1346
    # Grab any additional settings for vlan.
    my $otherargs = shift;

Kirk Webb's avatar
Kirk Webb committed
1347
    my $id = "$self->{NAME}::createVlan()";
1348
	
1349
1350
    # Check to see if the requested vlan number already exists.
    if ($self->vlanNumberExists($vlan_number)) {
Kirk Webb's avatar
Kirk Webb committed
1351
	warn "$id: ERROR: VLAN $vlan_number already exists\n";
1352
1353
	return 0;
    }
1354

1355
1356
1357
1358
1359
1360
1361
1362
    # 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);
    }

1363
    # Create VLAN
Kirk Webb's avatar
Kirk Webb committed
1364
    my $valstr = $self->{DO_RFC2579} ? "createAndWait" : "createAndGo";
1365
    my $RetVal = snmpitSetWarn($self->{SESS},["dot1qVlanStaticRowStatus", 
Kirk Webb's avatar
Kirk Webb committed
1366
					      $vlan_number, $valstr,
1367
1368
1369
					      "INTEGER"]);
    # $RetVal will be undefined if the set failed, or "1" if it succeeded.
    if (! defined($RetVal) )  { 
Kirk Webb's avatar