snmpit_cisco.pm 40.7 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2
3
4

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2004 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6
7
8
# All rights reserved.
#

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #
    # We have to change our behavior depending on what OS the switch runs
    #
    $options->{'type'} =~ /^(\w+)(-ios)?$/;
Robert Ricci's avatar
Robert Ricci committed
114
    $self->{SWITCHTYPE} = $1;
115

116
117
118
119
120
    if ($2) {
	$self->{OSTYPE} = "IOS";
    } else {
	$self->{OSTYPE} = "CatOS";
    }
121
122
123
124
125
126
127
128
129
130
131

    if ($self->{DEBUG}) {
	print "snmpit_cisco 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);
132
133
134
135
136
    # We list all MIBs we use, so that we don't depend on a correct .index file
    my @mibs = ("$mibpath/SNMPv2-SMI.txt", "$mibpath/SNMPv2-TC.txt",
	    "$mibpath/SNMPv2-MIB.txt", "$mibpath/IANAifType-MIB.txt",
	    "$mibpath/IF-MIB.txt", "$mibpath/RMON-MIB.txt",
	    "$mibpath/CISCO-SMI.txt", "$mibpath/CISCO-TC.txt",
Robert Ricci's avatar
Robert Ricci committed
137
138
	    "$mibpath/CISCO-VTP-MIB.txt", "$mibpath/CISCO-PAGP-MIB.txt",
	    "$mibpath/CISCO-PRIVATE-VLAN-MIB.txt");
139
140
141
142
143
144
145
146
147
148
149
	    
    if ($self->{OSTYPE} eq "CatOS") {
	push @mibs, "$mibpath/CISCO-STACK-MIB.txt";
    } elsif ($self->{OSTYPE} eq "IOS") {
	push @mibs, "$mibpath/CISCO-VLAN-MEMBERSHIP-MIB.txt";
    } else {
	warn "ERROR: Unsupported switch OS $self->{OSTYPE}\n";
	return undef;
    }

    &SNMP::addMibFiles(@mibs);
150
151
152
153
154
155
156
    
    $SNMP::save_descriptions = 1; # must be set prior to mib initialization
    SNMP::initMib();		  # parses default list of Mib modules 
    $SNMP::use_enums = 1;	  # use enum values instead of only ints

    warn ("Opening SNMP session to $self->{NAME}...") if ($self->{DEBUG});
    $self->{SESS} =
157
158
	    new SNMP::Session(DestHost => $self->{NAME},Version => "2c",
		    Community => $self->{COMMUNITY});
159
160
161
162
163
164
165
    if (!$self->{SESS}) {
	#
	# Bomb out if the session could not be established
	#
	warn "ERROR: Unable to connect via SNMP to $self->{NAME}\n";
	return undef;
    }
Mac Newbold's avatar
Mac Newbold committed
166

167
168
169
170
171
    #
    # The bless needs to occur before readifIndex(), since it's a class 
    # method
    #
    bless($self,$class);
Mac Newbold's avatar
Mac Newbold committed
172

173
    $self->readifIndex();
Mac Newbold's avatar
Mac Newbold committed
174

175
    return $self;
Mac Newbold's avatar
Mac Newbold committed
176
177
}

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#
# Set a variable associated with a port. The commands to execute are given
# in the cmdOIs hash above
#
# usage: portControl($self, $command, @ports)
#	 returns 0 on success.
#	 returns number of failed ports on failure.
#	 returns -1 if the operation is unsupported
#
sub portControl ($$@) {
    my $self = shift;

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

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

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    $self->debug("portControl: Checking supported for $cmd on " .
	    "$self->{OSTYPE}\n");

    #
    # Check right up front for unsupported operations
    #
    if ($self->{OSTYPE} eq "IOS" && ($cmd !~ /(en|dis)able/)) {
	#
	# XXX - Do we silently exit, in which case the caller doesn't know
	# we failed, or do we exit with an error, in which case the caller has
	# to know what we support before calling us? We'll go with the latter
	# for now.
	#
	$self->debug("portControl: unsupported\n");
	return -1;
    }

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    #
    # Find the command in the %cmdOIDs hash (defined at the top of this file)
    #
    if (defined $cmdOIDs{$cmd}) {
	my @oid = @{$cmdOIDs{$cmd}};
	my $errors = 0;

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

	#
	# Some commands involve multiple SNMP commands, so we need to make
	# sure we get all of them
	#
	while (@oid) {
	    my $myoid = shift @oid;
	    my $myval = shift @oid;
	    $errors += $self->UpdateField($myoid,$myval,@portlist);
	}
	return $errors;

Mac Newbold's avatar
Mac Newbold committed
242
    } else {
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
	#
	# Command not supported
	#
	print STDERR "Unsupported port control command '$cmd' ignored.\n";
	return -1;
    }
}

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


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

    #
    # We determine the type by sampling the first port given
    #
    my $sample = $ports[0];
279
    if (!defined($sample)) {
280
281
282
283
284
285
286
287
	warn "convertPortFormat: Given a bad list of ports\n";
	return undef;
    }

    my $input;
    SWITCH: for ($sample) {
	(/^\d+$/) && do { $input = $PORT_FORMAT_IFINDEX; last; };
	(/^\d+\.\d+$/) && do { $input = $PORT_FORMAT_MODPORT; last; };
Robert Ricci's avatar
Robert Ricci committed
288
289
	(/^$self->{NAME}\.\d+\/\d+$/) && do { $input = $PORT_FORMAT_MODPORT;
		@ports = map {/^$self->{NAME}\.(\d+)\/(\d+)$/; "$1.$2";} @ports; last; };
290
291
292
293
294
295
296
	$input = $PORT_FORMAT_NODEPORT; last;
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
297
	$self->debug("Not converting, input format = output format\n",2);
298
299
300
301
302
303
304
305
306
	return @ports;
    }

    # Shark hack
    @ports = map {if (/(sh\d+)-\d(:\d)/) { "$1$2" } else { $_ }} @ports;
    # End shark hack

    if ($input == $PORT_FORMAT_IFINDEX) {
	if ($output == $PORT_FORMAT_MODPORT) {
307
	    $self->debug("Converting ifindex to modport\n",2);
308
309
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
310
	    $self->debug("Converting ifindex to nodeport\n",2);
311
	    return map portnum($self->{NAME}.":".$self->{IFINDEX}{$_}), @ports;
312
	}
313
314
    } elsif ($input == $PORT_FORMAT_MODPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
315
	    $self->debug("Converting modport to ifindex\n",2);
316
317
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
318
319
	    $self->debug("Converting modport to nodeport\n",2);
	    return map portnum($self->{NAME} . ":$_"), @ports;
320
	}
321
322
    } elsif ($input == $PORT_FORMAT_NODEPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
323
	    $self->debug("Converting nodeport to ifindex\n",2);
324
325
	    return map $self->{IFINDEX}{(split /:/,portnum($_))[1]}, @ports;
	} elsif ($output == $PORT_FORMAT_MODPORT) {
326
	    $self->debug("Converting nodeport to modport\n",2);
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
	    return map { (split /:/,portnum($_))[1] } @ports;
	}
    }

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

}

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

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

    #
354
    # Try max_tries times before we give up, in case some other process just
355
356
357
    # has it locked.
    #
    my $tries = 1;
358
    my $max_tries = 40;
359
    while ($tries <= $max_tries) {
360
361
362
363
364
365
366
367
368
369
370
371
    
	#
	# Attempt to grab the edit buffer
	#
	my $grabBuffer = $self->{SESS}->set([$EditOp,1,"copy","INTEGER"]);

	#
	# Check to see if we were sucessful
	#
	$self->debug("Buffer Request Set gave " .
		(defined($grabBuffer)?$grabBuffer:"undef.") . "\n");
	if (! $grabBuffer) {
372
373
374
375
376
377
378
	    #
	    # Only print this message every five tries
	    #
	    if (!($tries % 5)) {
		print STDERR "VLAN edit buffer request failed - " .
			     "try $tries of $max_tries.\n";
	    }
379
380
381
382
383
	} else {
	    last;
	}
	$tries++;

384
	sleep(3);
385
386
    }

387
    if ($tries > $max_tries) {
388
389
390
391
392
	#
	# Admit defeat and exit
	#
	print STDERR "ERROR: Failed to obtain VLAN edit buffer lock\n";
	return 0;
393
    } else {
394
395
396
397
398
399
400
401
	#
	# Set the owner of the buffer to be the machine we're running on
	#
	my $me = `/usr/bin/uname -n`;
	chomp $me;
	$self->{SESS}->set([$BufferOwner,1,$me,"OCTETSTR"]);

	return 1;
402
    }
403

Mac Newbold's avatar
Mac Newbold committed
404
405
}

406
407
408
409
410
411
412
413
414
415
416
417
418
419
#
# Release a lock on the VLAN edit buffer. As part of releasing, applies the
# VLAN edit buffer.
#
# usage: vlanUnlock($self)
#
# TODO: Finish commenting, major cleanup, removal of obsolete features
#        
sub vlanUnlock($;$) {
    my $self = shift;
    my $force = shift;

    my $EditOp = 'vtpVlanEditOperation'; # use index 1
    my $ApplyStatus = 'vtpVlanApplyStatus'; # use index 1
420
421
422
423
424
425
426
427
    my $ApplyRetVal = $self->{SESS}->set([[$EditOp,1,"apply","INTEGER"]]);
    $self->debug("Apply set: '$ApplyRetVal'\n");

    $ApplyRetVal = snmpitGetWarn($self->{SESS},[$ApplyStatus,1]);
    $self->debug("Apply gave $ApplyRetVal\n");
    while ($ApplyRetVal eq "inProgress") { 
	$ApplyRetVal = snmpitGetWarn($self->{SESS},[$ApplyStatus,1]);
	$self->debug("Apply gave $ApplyRetVal\n");
428
429
    }

430
431
432
    if ($ApplyRetVal ne "succeeded") {
	$self->debug("Apply failed: Gave $ApplyRetVal\n");
	warn("ERROR: Failure applying VLAN changes: $ApplyRetVal\n");
433
434
	# Only release the buffer if they've asked to force it.
	if (!$force) {
435
	    my $RetVal = $self->{SESS}->set([[$EditOp,1,"release","INTEGER"]]);
436
437
	    $self->debug("Release: '$RetVal'\n");
	    if (! $RetVal ) {
438
439
		warn("VLAN Reconfiguration Failed. No changes saved.\n");
		return 0;
440
441
442
443
444
	    }
	}
    } else { 
	$self->debug("Apply Succeeded.\n");
	# If I succeed, release buffer
445
	my $RetVal = $self->{SESS}->set([[$EditOp,1,"release","INTEGER"]]);
446
	if (! $RetVal ) {
447
448
	    warn("VLAN Reconfiguration Failed. No changes saved.\n");
	    return 0;
449
450
451
452
453
	}
	$self->debug("Release: '$RetVal'\n");
    }
    
    return $ApplyRetVal;
Mac Newbold's avatar
Mac Newbold committed
454
455
}

456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# 
# Check to see if the given (cisco-specific) VLAN number exists on the switch
#
# usage: vlanNumberExists($self, $vlan_number)
#        returns 1 if the VLAN exists, 0 otherwise
#
sub vlanNumberExists($$) {
    my $self = shift;
    my $vlan_number = shift;

    my $VlanName = "vtpVlanName";

    #
    # Just look up the name for this VLAN, and see if we get an answer back
    # or not
    #
    my $rv = $self->{SESS}->get([$VlanName,"1.$vlan_number"]);
Robert Ricci's avatar
Robert Ricci committed
473
    if (!$rv or $rv eq "NOSUCHINSTANCE") {
474
475
476
477
478
479
	return 0;
    } else {
    	return 1;
    }
}

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#
# Given VLAN indentifiers from the database, finds the cisco-specific VLAN
# number for them. If not VLAN id is given, returns mappings for the entire
# switch.
# 
# usage: findVlans($self, @vlan_ids)
#        returns a hash mapping VLAN ids to Cisco VLAN numbers
#        any VLANs not found have NULL VLAN numbers
#
sub findVlans($@) { 
    my $self = shift;
    my @vlan_ids = @_;

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

    #
    # Walk the tree to find the VLAN names
    # TODO - we could optimize a bit, since, if we find all VLAN, we can stop
    # looking, potentially saving us a lot of time. But, it would require a
    # more complex walk.
    #
    my %mapping = ();
    @mapping{@vlan_ids} = undef;
    my ($rows) = $self->{SESS}->bulkwalk(0,32,[$VlanName]);
    foreach my $rowref (@$rows) {
	my ($name,$vlan_number,$vlan_name) = @$rowref;
	#
	# We get the VLAN number in the form 1.number - we need to strip
	# off the '1.' to make it useful
	#
	$vlan_number =~ s/^1\.//;

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

    return %mapping;
}

522
523
#
# Given a VLAN identifier from the database, find the cisco-specific VLAN
524
525
# number that is assigned to that VLAN. Retries several times (to account
# for propagation delays) unless the $no_retry option is given.
526
#
527
# usage: findVlan($self, $vlan_id,$no_retry)
528
529
530
#        returns the VLAN number for the given vlan_id if it exists
#        returns undef if the VLAN id is not found
#
531
sub findVlan($$;$) { 
532
533
    my $self = shift;
    my $vlan_id = shift;
534
535
536
537
538
539
540
541
    my $no_retry = shift;

    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
    } else {
	$max_tries = 10;
    }
542
543

    #
544
545
    # We try this a few time, with 1 second sleeps, since it can take
    # a while for VLAN information to propagate
546
    #
547
548
    foreach my $try (1 .. $max_tries) {

549
550
551
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
552
553
	}

554
555
556
	#
	# Wait before we try again
	#
557
558
559
560
	if ($try != $max_tries) {
	    $self->debug("VLAN find failed, trying again\n");
	    sleep 1;
	}
561
    }
562
563
564
565
    #
    # Didn't find it
    #
    return undef;
Mac Newbold's avatar
Mac Newbold committed
566
567
}

568
569
#
# Create a VLAN on this switch, with the given identifier (which comes from
570
571
# the database.) If $vlan_number is given, attempts to use it when creating
# the vlan - otherwise, picks its own Cisco-specific VLAN number.
572
#
573
574
# usage: createVlan($self, $vlan_id, $vlan_number, [,$private_type
# 		[,$private_primary, $private_port]])
575
#        returns the new VLAN number on success
576
#        returns 0 on failure
Robert Ricci's avatar
Robert Ricci committed
577
578
579
#        if $private_type is given, creates a private VLAN - if private_type
#        is 'community' or 'isolated', then the assocated primary VLAN and
#        promiscous port must also be given
580
#
Robert Ricci's avatar
Robert Ricci committed
581
sub createVlan($$;$$$) {
582
583
    my $self = shift;
    my $vlan_id = shift;
584
    my $vlan_number = shift;
585

Robert Ricci's avatar
Robert Ricci committed
586
587
588
589
590
591
592
593
594
595
    my ($private_type,$private_primary,$private_port);
    if (@_) {
	$private_type = shift;
	if ($private_type ne "primary") {
	    $private_primary = shift;
	    $private_port = shift;
	}
    } else {
	$private_type = "normal";
    }
596

Robert Ricci's avatar
Robert Ricci committed
597
598
599
600
601
602
603

    my $okay = 1;

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

605
    #
Robert Ricci's avatar
Robert Ricci committed
606
    # If they gave a VLAN number, make sure it doesn't exist
607
608
609
610
611
612
613
614
    #
    if ($vlan_number) {
	if ($self->vlanNumberExists($vlan_number)) {
	    print STDERR "ERROR: VLAN $vlan_number already exists\n";
	    return 0;
	}
    }
    
615
    #
616
617
618
619
    # We may have to do this multiple times - a few times, we've had the
    # Cisco give no errors, but fail to actually create the VLAN. So, we'll
    # make sure it gets created, and retry if it did not. Of course, we don't
    # want to try forever, though....
620
    #
621
622
623
    my $max_tries = 3;
    my $tries_remaining = $max_tries;
    while ($tries_remaining) {
624
	#
625
	# Try to wait out transient failures
626
	#
627
628
629
630
631
632
	if ($tries_remaining != $max_tries) {
	    print STDERR "VLAN creation failed, trying again " .
		"($tries_remaining tries left)\n";
	    sleep 5;
	}
	$tries_remaining--;
633

634
635
636
	if (!$self->vlanLock()) {
	    next;
	}
637

638
	if (!$vlan_number) {
639
	    #
640
	    # Find a free VLAN number to use.
641
	    #
642
	    $vlan_number = $self->{MIN_VLAN};
643
	    my $RetVal = snmpitGetWarn($self->{SESS},
644
		[$VlanRowStatus,"1.$vlan_number"]);
645
646
647
648
649
650
651
	    if (!defined($RetVal)) {
		#
		# If we can't get the first one, we might as well bail
		#
		warn "WARNING: Failed to VLAN name for VLAN $vlan_number\n";
		next;
	    }
652
	    $self->debug("Row $vlan_number got '$RetVal'\n",2);
653
	    while (($RetVal ne 'NOSUCHINSTANCE') &&
654
		    ($vlan_number <= $self->{MAX_VLAN})) {
655
		$vlan_number += 1;
656
		$RetVal = snmpitGetWarn($self->{SESS},
657
		    [$VlanRowStatus,"1.$vlan_number"]);
658
659
660
661
662
663
664
665
666
667
		if (!defined($RetVal)) {
		    #
		    # We probably could unlock the edit buffer and die, but
		    # the script using this library could have other unfinished
		    # business
		    #
		    warn "WARNING: Failed to VLAN name for VLAN $vlan_number\n";
		} else {
		    $self->debug("Row $vlan_number got '$RetVal'\n",2);
		}
668
	    }
669
	    if ($vlan_number > $self->{MAX_VLAN}) {
670
671
672
673
674
675
		#
		# We must have failed to find one
		#
		print STDERR "ERROR: Failed to find a free VLAN number\n";
		next;
	    }
676
	}
677

678
	$self->debug("Using Row $vlan_number\n");
679

680
681
682
683
684
	#
	# SAID is a funky security identifier that _must_ be set for VLAN
	# creation to suceeed.
	#
	my $SAID = pack("H*",sprintf("%08x",$vlan_number + 100000));
685

686
687
	print "  Creating VLAN $vlan_id as VLAN #$vlan_number on " .
		"$self->{NAME} ... ";
688
689
690
691
692

	#
	# Perform the actual creation. Yes, this next line MUST happen all in
	# one set command....
	#
693
	my $RetVal = $self->{SESS}->set([[$VlanRowStatus,"1.$vlan_number",
694
			"createAndGo","INTEGER"],
Robert Ricci's avatar
Robert Ricci committed
695
696
697
		[$VlanType,"1.$vlan_number","ethernet","INTEGER"],
		[$VlanName,"1.$vlan_number",$vlan_id,"OCTETSTR"],
		[$VlanSAID,"1.$vlan_number",$SAID,"OCTETSTR"]]);
698
699
700
701
702
703
704
705
	print "",($RetVal? "Succeeded":"Failed"), ".\n";

	#
	# Check for success
	#
	if (!$RetVal) {
	    print STDERR "VLAN Create '$vlan_id' as VLAN $vlan_number " .
		    "failed.\n";
Robert Ricci's avatar
Robert Ricci committed
706
	    $self->vlanUnlock();
707
708
	    next;
	} else {
Robert Ricci's avatar
Robert Ricci committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
	    #
	    # Handle private VLANs - Part I: Stuff that has to be done while we
	    # have the edit buffer locked
	    #
	    if ($self->{SUPPORTS_PRIVATE} && $private_type ne "normal") {
		#
		# First, set the private VLAN type
		#
		my $PVlanType = "cpvlanVlanEditPrivateVlanType";
		print "    Setting private VLAN type to $private_type ... ";
		$RetVal = $self->{SESS}->set([$PVlanType,"1.$vlan_number",$private_type,
		    'INTEGER']);
		print "",($RetVal? "Succeeded":"Failed"), ".\n";
		if (!$RetVal) {
		    $okay = 0;
		}
		if ($okay) {
		    #
		    # Now, if this isn't a primary VLAN, associate it with its
		    # primary VLAN
		    #
		    if ($private_type ne "primary") {
			my $PVlanAssoc = "cpvlanVlanEditAssocPrimaryVlan";
			my $primary_number = $self->findVlan($private_primary);
			if (!$primary_number) {
			    print "    **** Error - Primary VLAN " .
			    	"$private_primary could not be found\n";
			    $okay = 0;
			} else {
			    print "    Associating with $private_primary (#$primary_number) ... ";
			    $RetVal = $self->{SESS}->set([[$PVlanAssoc,"1.$vlan_number",
				$primary_number,"INTEGER"]]);
			    print "", ($RetVal? "Succeeded":"Failed"), ".\n";
			    if (!$RetVal) {
				$okay = 0;
			    }
			}
		    }
		}
	    }

750
751
752
753
754
755
756
757
758
759
760
761
762
	    $RetVal = $self->vlanUnlock();
	    $self->debug("Got $RetVal from vlanUnlock\n");

	    #
	    # Unfortunately, there are some rare circumstances in which it
	    # seems that we can't trust the switch to tell us the truth.
	    # So, let's use findVlan to see if it really got created.
	    #
	    if (!$self->findVlan($vlan_id)) {
		print STDERR "*** Switch reported success, but VLAN did not " .
			     "get created - trying again\n";
		next;	     
	    }
Robert Ricci's avatar
Robert Ricci committed
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
	    if ($self->{SUPPORTS_PRIVATE} && $private_type ne "normal" &&
		$private_type ne "primary") {

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

		my $SecondaryPort = 'cpvlanPromPortSecondaryRemap';

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

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

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

		    #
		    # Get the existing bitfield used to maintain the mapping
		    # for the port
		    #
		    my $bitfield = $self->{SESS}->get([$SecondaryPort,$ifIndex]);
		    my $unpacked = unpack("B*",$bitfield);

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

		    $bits[$vlan_number] = 1;

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

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

		    # And save it back...
		    $RetVal = $self->{SESS}->set([$SecondaryPort,$ifIndex,$bitfield,
			"OCTETSTR"]);
		    print "", ($RetVal? "Succeeded":"Failed"), ".\n";

		}
	    }
818
819
820
821
822
	    if ($okay) {
		return $vlan_number;
	    } else {
		return 0;
	    }
823
	}
824
    }
825
826
827
828

    print STDERR "*** Failed to create VLAN $vlan_id after $max_tries tries " .
		 "- giving up\n";
    return 0;
829
830
831
}

#
832
833
# Put the given ports in the given VLAN. The VLAN is given as a cisco-specific
# VLAN number
834
#
835
# usage: setPortVlan($self, $vlan_number, @ports)
836
837
838
839
840
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub setPortVlan($$@) {
    my $self = shift;
841
    my $vlan_number = shift;
842
843
844
845
    my @ports = @_;

    my $errors = 0;

846
847
    if (!$self->vlanNumberExists($vlan_number)) {
	print STDERR "ERROR: VLAN $vlan_number does not exist\n";
848
849
850
851
	return 1;
    }

    #
Robert Ricci's avatar
Robert Ricci committed
852
853
    # If this switch supports private VLANs, check to see if the VLAN we're
    # putting it into is a secondary private VLAN
854
    #
Robert Ricci's avatar
Robert Ricci committed
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
    my $privateVlan = 0;
    if ($self->{SUPPORTS_PRIVATE}) {
	$self->debug("Checking to see if vlan is private ... ");
	my $PrivateType = "cpvlanVlanPrivateVlanType";
	my $type = snmpitGetFatal($self->{SESS},[$PrivateType,"1.$vlan_number"]);
	$self->debug("type is $type ... ");
	if ($type eq "community" ||  $type eq "isolated") {
	    $self->debug("It is\n");
	    $privateVlan = 1;
	} else {
	    $self->debug("It isn't\n");
	}
    }

    my $PortVlanMemb;
870
871
    my $format;
    if ($self->{OSTYPE} eq "CatOS") {
Robert Ricci's avatar
Robert Ricci committed
872
873
874
875
876
877
878
	if (!$privateVlan) {
	    $PortVlanMemb = "vlanPortVlan"; #index is ifIndex
	    $format = $PORT_FORMAT_MODPORT;
	} else {
	    $PortVlanMemb = "cpvlanPrivatePortSecondaryVlan";
	    $format = $PORT_FORMAT_IFINDEX;
	}
879
    } elsif ($self->{OSTYPE} eq "IOS") {
Robert Ricci's avatar
Robert Ricci committed
880
	$PortVlanMemb = "vmVlan"; #index is ifIndex
881
882
883
	$format = $PORT_FORMAT_IFINDEX;
    }

Robert Ricci's avatar
Robert Ricci committed
884
885
886
    #
    # Convert ports from the format the were passed in to the correct format
    #
887
    my @portlist = $self->convertPortFormat($format,@ports);
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908

    #
    # We'll keep track of which ports suceeded, so that we don't try to
    # enable/disable, etc. ports that failed.
    #
    my @okports = ();
    foreach my $port (@portlist) {

	# 
	# Make sure the port didn't get mangled in conversion
	#
	if (!defined $port) {
	    print STDERR "Port not found, skipping\n";
	    $errors++;
	    next;
	}
	$self->debug("Putting port $port in VLAN $vlan_number\n");

	#
	# Do the acutal SNMP command
	#
909
910
911
	my $snmpvar = [$PortVlanMemb,$port,$vlan_number,'INTEGER'];
	my $retval = snmpitSetWarn($self->{SESS},$snmpvar);
	if (!$retval) {
912
913
	    $errors++;
	    next;
Mac Newbold's avatar
Mac Newbold committed
914
	} else {
915
	    push @okports, $port;
Mac Newbold's avatar
Mac Newbold committed
916
	}
917
918
919
920
921
922
923
    }

    #
    # Ports going into VLAN 1 are being taken out of circulation, so we
    # disable them. Otherwise, we need to make sure they get enabled.
    #
    if ($vlan_number == 1) {
924
925
	$self->debug("Disabling " . join(',',@okports) . "...");
	if ( my $rv = $self->portControl("disable",@okports) ) {
926
927
928
929
	    print STDERR "Port disable had $rv failures.\n";
	    $errors += $rv;
	}
    } else {
930
931
	$self->debug("Enabling "  . join(',',@okports) . "...");
	if ( my $rv = $self->portControl("enable",@okports) ) {
932
933
934
935
	    print STDERR "Port enable had $rv failures.\n";
	    $errors += $rv;
	}
    }
Mac Newbold's avatar
Mac Newbold committed
936

937
    return $errors;
938
939
}

940
#
941
942
# Remove all ports from the given VLANs, which are given as Cisco-specific
# VLAN numbers
943
#
944
# usage: removePortsFromVlan(self,int vlans)
945
946
947
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
948
sub removePortsFromVlan($@) {
949
    my $self = shift;
950
    my @vlan_numbers = @_;
951
952

    #
953
    # Make sure the VLANs actually exist
954
    #
955
956
957
    foreach my $vlan_number (@vlan_numbers) {
	if (!$self->vlanNumberExists($vlan_number)) {
	    print STDERR "ERROR: VLAN $vlan_number does not exist\n";
958
959
	    return 1;
	}
960
961
    }

962
963
964
965
    #
    # Make a hash of the vlan number for easy lookup later
    #
    my %vlan_numbers = ();
966
    @vlan_numbers{@vlan_numbers} = @vlan_numbers;
967

968
969
970
    #
    # Get a list of the ports in the VLAN
    #
971
972
973
974
975
976
    my $VlanPortVlan;
    if ($self->{OSTYPE} eq "CatOS") {
	$VlanPortVlan = "vlanPortVlan"; #index is ifIndex
    } elsif ($self->{OSTYPE} eq "IOS") {
	$VlanPortVlan = "vmVlan"; #index is ifIndex
    }
977
    my @ports;
978
979
980
981

    #
    # Walk the tree to find VLAN membership
    #
982
    my ($rows) = $self->{SESS}->bulkwalk(0,32,$VlanPortVlan);
983
    foreach my $rowref (@$rows) {
984
985
986
	my ($name,$modport,$port_vlan_number) = @$rowref;
	$self->debug("Got $name $modport $port_vlan_number\n");
	if ($vlan_numbers{$port_vlan_number}) {
987
	    push @ports, $modport;
Mac Newbold's avatar
Mac Newbold committed
988
989
990
	}
    }

991
992
    $self->debug("About to remove ports " . join(",",@ports) . "\n");
    if (@ports) {
993
	return $self->setPortVlan(1,@ports);
Mac Newbold's avatar
Mac Newbold committed
994
    } else {
995
	return 0;
Mac Newbold's avatar
Mac Newbold committed
996
    }
997
998
999
1000
1001
}

#
# Remove the given VLAN from this switch. This presupposes that all of its
# ports have already been removed with removePortsFromVlan(). The VLAN is
1002
# given as a Cisco-specific VLAN number
1003
1004
1005
1006
1007
1008
#
# usage: removeVlan(self,int vlan)
#	 returns 1 on success
#	 returns 0 on failure
#
#
1009
sub removeVlan($@) {
1010
    my $self = shift;
1011
    my @vlan_numbers = @_;
1012
1013
1014
1015
1016
1017
1018
1019

    #
    # Need to lock the VLAN edit buffer
    #
    if (!$self->vlanLock()) {
    	return 0;
    }

1020
1021
    my $errors = 0;

1022
    foreach my $vlan_number (@vlan_numbers) {
1023
	#
1024
	# Make sure the VLAN actually exists
1025
	#
1026
1027
	if (!$self->vlanNumberExists($vlan_number)) {
	    print STDERR "ERROR: VLAN $vlan_number does not exist\n";
1028
1029
1030
1031
1032
1033
	    return 0;
	}

	#
	# Perform the actual removal
	#
Robert Ricci's avatar
Robert Ricci committed
1034
	my $VlanRowStatus = 'vtpVlanEditRowStatus'; # vlan is index
1035

1036
	print "  Removing VLAN #$vlan_number on $self->{NAME} ... ";
Robert Ricci's avatar
Robert Ricci committed
1037
	my $RetVal = $self->{SESS}->set([$VlanRowStatus,"1.$vlan_number",
1038
1039
1040
1041
1042
1043
1044
1045
					 "destroy","INTEGER"]);
	if ($RetVal) {
	    print "Succeeded.\n";
	} else {
	    print "Failed.\n";
	    $errors++;
	}
    }
1046
1047
1048
1049
1050
1051

    #
    # Unlock whether successful or not
    #
    $self->vlanUnlock();

1052
    if ($errors) {
1053
	return 0;
Mac Newbold's avatar
Mac Newbold committed
1054
    } else {
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
	return 1;
    }

}

#
# TODO: Cleanup
#
sub UpdateField($$$@) {
    my $self = shift;
    # returns 0 on success, # of failed ports on failure
    $self->debug("UpdateField: '@_'\n");
    my ($OID,$val,@ports)= @_;
    my $Status = 0;
    my $err = 0;
    foreach my $port (@ports) {
Robert Ricci's avatar
Robert Ricci committed
1071
1072
1073
	my ($trans) = convertPortFormat($PORT_FORMAT_NODEPORT,$port);
	if (!defined $trans) {
	    $trans = ""; # Guard against some uninitialized value warnings
1074
1075
	}
	$self->debug("Checking port $port ($trans) for $val...");
1076
	$Status = snmpitGetWarn($self->{SESS},[$OID,$port]);
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
	if (!defined $Status) {
	    warn "Port $port ($trans), change to $val: No answer from device\n";
	    return -1;		# return error
	} else {
	    $self->debug("Okay.\n");
	    $self->debug("Port $port was $Status\n");
	    if ($Status ne $val) {
		$self->debug("Setting $port to $val...");
		# Don't use async
		my $result = $self->{SESS}->set([$OID,$port,$val,"INTEGER"]);
		$self->debug("Set returned '$result'\n") if (defined $result);
		if ($self->{BLOCK}) {
		    my $n = 0;
		    while ($Status ne $val) {
1091
			$Status = snmpitGetWarn($self->{SESS},[$OID,$port]);
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
			$self->debug("Value for $port was $Status\n");
			select (undef, undef, undef, .25); # wait .25 seconds
			$n++;
			if ($n > 20) {
			    $err++;
			    $self->debug("Timing out...");
			    last;
			}
		    }
		    $self->debug("Okay.\n");
		} else {
		    $self->debug("\n");
		}
	    }
Mac Newbold's avatar
Mac Newbold committed
1106
1107
	}
    }
1108
1109
    # returns 0 on success, # of failed ports on failure
    $err;
Mac Newbold's avatar
Mac Newbold committed
1110
1111
}

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
#
# 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;

    $self->debug("Getting VLAN info...\n");
    # We don't need VlanIndex really...
    my $VlanName = ["vtpVlanName"]; # index by 1.vlan #
1124
1125
1126
1127
1128
1129
1130

    my $VlanPortVlan;
    if ($self->{OSTYPE} eq "CatOS") {
	$VlanPortVlan = "vlanPortVlan"; #index is ifIndex
    } elsif ($self->{OSTYPE} eq "IOS") {
	$VlanPortVlan = "vmVlan"; #index is ifIndex
    }
1131
1132
1133
1134
1135
1136

    #
    # Walk the tree to find the VLAN names
    #
    my ($rows) = $self->{SESS}->bulkwalk(0,32,$VlanName);
    my %Names = ();
1137
    my %Members = ();
1138
1139
1140
1141
1142
1143
1144
1145
    foreach my $rowref (@$rows) {
	my ($name,$vlan_number,$vlan_name) = @$rowref;
	#
	# We get the VLAN number in the form 1.number - we need to strip
	# off the '1.' to make it useful
	#
	$vlan_number =~ s/^1\.//;

1146
	$self->debug("Got $name $vlan_number $vlan_name\n");
1147
1148
	if (!$Names{$vlan_number}) {
	    $Names{$vlan_number} = $vlan_name;
1149
	    @{$Members{$vlan_number}} = ();
1150
	}
Mac Newbold's avatar
Mac Newbold committed
1151
    }
1152
1153
1154
1155
1156
1157
1158
1159

    #
    # Walk the tree for the VLAN members
    #
    ($rows) = $self->{SESS}->bulkwalk(0,32,$VlanPortVlan);
    foreach my $rowref (@$rows) {
	my ($name,$modport,$vlan_number) = @$rowref;
	$self->debug("Got $name $modport $vlan_number\n",3);
1160
1161
	my ($node) = $self->convertPortFormat($PORT_FORMAT_NODEPORT,$modport);
	if (!$node) {
Robert Ricci's avatar
Robert Ricci committed
1162
1163
	    $modport =~ s/\./\//;
	    $node = $self->{NAME} . ".$modport";
1164
	}
1165
	push @{$Members{$vlan_number}}, $node;
1166
1167
1168
1169
	if (!$Names{$vlan_number}) {
	    $self->debug("listVlans: WARNING: port $self->{NAME}.$modport in non-existant " .
		"VLAN $vlan_number\n");
	}
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
    }

    #
    # Build a list from the name and membership lists
    #
    my @list = ();
    foreach my $vlan_id (sort {$a <=> $b} keys %Names) {
    	if ($vlan_id != 1) {
	    #
    	    # Special case for Cisco - VLAN 1 is special and should not
    	    # be reported
	    #
    	    push @list, [$Names{$vlan_id},$vlan_id,$Members{$vlan_id}];
    	}
    }
1185
    $self->debug(join("\n",(map {join ",", @$_} @list))."\n");
1186
1187

    return @list;
Mac Newbold's avatar
Mac Newbold committed
1188
1189
}

1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
#
# List all ports on the device
#
# usage: listPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
# TODO: convert to bulkwalk
#
sub listPorts($) {
    my $self = shift;

    my %Able = ();
    my %Link = ();
    my %speed = ();
    my %duplex = ();
    my $ifTable = ["ifAdminStatus",0];
    my @data=();

    # TODO: Clean up this section and convert to bulkwalk
    #do one to get the first field...
    $self->debug("Getting port information...\n");
    do {{
	$self->{SESS}->getnext($ifTable);
	@data = @{$ifTable};
	if ($data[0] eq "ifLastChange") {
	    $ifTable = ["portAdminSpeed",0];
	    $self->{SESS}->getnext($ifTable);
	    @data = @{$ifTable};
	}
	if (! defined $self->{IFINDEX}{$data[1]}) { next; }
	my $port = portnum("$self->{NAME}:$data[1]")
	    || portnum("$self->{NAME}:".$self->{IFINDEX}{$data[1]});
	if (! defined $port) { next; }
	$self->debug("$port\t$data[0]\t$data[2]\n",2);
	if    ($data[0]=~/AdminStatus/) {$Able{$port}=($data[2]=~/up/?"yes":"no");}
	elsif ($data[0]=~/ifOperStatus/)         {  $Link{$port}=$data[2];}
	elsif ($data[0]=~/AdminSpeed/)           { $speed{$port}=$data[2];}
	elsif ($data[0]=~/Duplex/)               {$duplex{$port}=$data[2];}
	# Insert stuff here to get ifSpeed if necessary... AdminSpeed is the
	# _desired_ speed, and ifSpeed is the _real_ speed it is using
	}} while ( $data[0] =~
	    /(i(f).*Status)|(port(AdminSpeed|Duplex))/) ;

    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
    foreach my $id ( keys %Able ) {
	my $vlan;
	if (! defined ($speed{$id}) ) { $speed{$id} = " "; }
	if (! defined ($duplex{$id}) ) { $duplex{$id} = " "; }
	$speed{$id} =~ s/s([10]+)000000/${1}Mbps/;
	push @rv, [$id,$Able{$id},$Link{$id},$speed{$id},$duplex{$id}];
    }
    return @rv;
Mac Newbold's avatar
Mac Newbold committed
1246
1247
}

1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
# 
# Get statistics for ports on the switch
#
# usage: getPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
# TODO: Clean up undefined variable warnings
#
sub getStats ($) {
    my $self = shift;

    #
    # Walk the tree for the VLAN members
    #
    my $vars = new SNMP::VarList(['ifInOctets'],['ifInUcastPkts'],
    				 ['ifInNUcastPkts'],['ifInDiscards'],
				 ['ifInErrors'],['ifInUnknownProtos'],
				 ['ifOutOctets'],['ifOutUcastPkts'],
				 ['ifOutNUcastPkts'],['ifOutDiscards'],
				 ['ifOutErrors'],['ifOutQLen']);
    my @stats = $self->{SESS}->bulkwalk(0,32,$vars);

    #
    # We need to flip the two-dimentional array we got from bulkwalk on
    # its side, and convert ifindexes into node:port
    #
    my $i = 0;
    my %stats;
    foreach my $array (@stats) {
	while (@$array) {
	    my ($name,$ifindex,$value) = @{shift @$array};
	    my ($port) = $self->convertPortFormat($PORT_FORMAT_NODEPORT,$ifindex);
	    if ($port) {
		${$stats{$port}}[$i] = $value;
	    }
	}
	$i++;
    }

1287
    return map [$_,@{$stats{$_}}], sort {tbsort($a,$b)} keys %stats;
1288

Mac Newbold's avatar
Mac Newbold committed
1289
1290
}

1291
1292
1293
#
# Enable, or disable,  port on a trunk
#
1294
# usage: setVlansOnTrunk(self, modport, value, vlan_numbers)
1295
1296
#        modport: module.port of the trunk to operate on
#        value: 0 to disallow the VLAN on the trunk, 1 to allow it
1297
#	 vlan_numbers: An array of cisco-native VLAN numbers operate on
1298
1299
#        Returns 1 on success, 0 otherwise
#
1300
sub setVlansOnTrunk($$$$) {
1301
    my $self = shift;
1302
    my ($modport, $value, @vlan_numbers) = @_;
1303
1304
1305
1306
1307
1308
1309

    #
    # Some error checking
    #
    if (($value != 1) && ($value != 0)) {
	die "Invalid value $value passed to setVlanOnTrunk\n";
    }
1310
    if (grep(/^1$/,@vlan_numbers)) {
1311
1312
1313
1314
1315
	die "VLAN 1 passed to setVlanOnTrunk\n"
    }

    my $ifIndex = $self->{IFINDEX}{$modport};

1316
1317
1318
1319
1320
1321
1322
    #
    # If this is part of an EtherChannel, we have to find the ifIndex for the
    # channel.
    # TODO: Perhaps this should be general - ie. $self{IFINDEX} should have
    # the channel ifIndex the the port is in a channel. Not sure that
    # this is _always_ beneficial, though
    #
1323
    my $channel = snmpitGetFatal($self->{SESS},["pagpGroupIfIndex",$ifIndex]);
1324
1325
1326
1327
    if (($channel =~ /^\d+$/) && ($channel != 0)) {
	$ifIndex = $channel;
    }

1328
1329
1330
    #
    # Get the exisisting bitfield for allowed VLANs on the trunk
    #
1331
1332
    my $bitfield = snmpitGetFatal($self->{SESS},
	    ["vlanTrunkPortVlansEnabled",$ifIndex]);
1333
1334
1335
1336
1337
    my $unpacked = unpack("B*",$bitfield);
    
    # Put this into an array of 1s and 0s for easy manipulation
    my @bits = split //,$unpacked;

1338
1339
1340
1341
    # Just set the bit of the ones we want to change
    foreach my $vlan_number (@vlan_numbers) {
	$bits[$vlan_number] = $value;
    }
1342
1343
1344

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

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

    # And save it back...
1349
1350
1351
    my $rv = $self->{SESS}->set(["vlanTrunkPortVlansEnabled",$ifIndex,$bitfield,
    	    "OCTETSTR"]);
    if ($rv) {
1352
1353
1354
1355
1356
1357
1358
	return 1;
    } else {
	return 0;
    }

}

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
#
# Reads the IfIndex table from the switch, for SNMP functions that use 
# IfIndex rather than the module.port style. Fills out the objects IFINDEX
# members,
#
# usage: readifIndex(self)
#        returns nothing
#
sub readifIndex($) {
    my $self = shift;

    #
1371
1372
1373
1374
    # How we fill this table is highly dependant on which OS the switch
    # is running - CatOS provides a convenient table to convert from
    # node/port to ifindex, but under IOS, we have to infer it from the
    # port description
1375
    #
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387

    if ($self->{OSTYPE} eq "CatOS") {
	my ($rows) = $self->{SESS}->bulkwalk(0,32,["portIfIndex"]);

	foreach my $rowref (@$rows) {
	    my ($name,$modport,$ifindex) = @$rowref;

	    $self->{IFINDEX}{$modport} = $ifindex;
	    $self->{IFINDEX}{$ifindex} = $modport;
	}
    } elsif ($self->{OSTYPE} eq "IOS") {
	my ($rows) = $self->{SESS}->bulkwalk(0,32,["ifDescr"]);
1388