snmpit_cisco.pm 29 KB
Newer Older
1
#!/usr/bin/perl -w
Mac Newbold's avatar
Mac Newbold committed
2
3
4
#
# snmpit module for Cisco Catalyst 6509 switches
#
5
6
7
# TODO: Standardize returning 0 on success/failure
# TODO: Fix uninitialized variable warnings in getStats()
#
Mac Newbold's avatar
Mac Newbold committed
8
9

package snmpit_cisco;
10
use strict;
Mac Newbold's avatar
Mac Newbold committed
11
12
13

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

Mac Newbold's avatar
Mac Newbold committed
14
use English;
Mac Newbold's avatar
Mac Newbold committed
15
16
17
use SNMP;
use snmpit_lib;

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#
# These are the commands that can be passed to the portControl function
# below
#
my %cmdOIDs =
(
    "enable" => ["ifAdminStatus","up"],
    "disable"=> ["ifAdminStatus","down"],
    "100mbit"=> ["portAdminSpeed","s100000000"],
    "10mbit" => ["portAdminSpeed","s10000000"],
    "full"   => ["portDuplex","full"],
    "half"   => ["portDuplex","half"],
    "auto"   => ["portAdminSpeed","autoDetect",
		 "portDuplex","auto"]
);
Mac Newbold's avatar
Mac Newbold committed
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
#
# 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
48

49
50
51
52
53
54
55
#
# Creates a new object.
#
# usage: new($classname,$devicename,$debuglevel)
#        returns a new object, blessed into the snmpit_cisco class.
#
sub new($$;$) {
Mac Newbold's avatar
Mac Newbold committed
56

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

61
62
    my $name = shift;
    my $debugLevel = shift;
63

64
65
66
67
    #
    # Create the actual object
    #
    my $self = {};
Mac Newbold's avatar
Mac Newbold committed
68

69
70
71
72
73
74
75
76
77
    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
	$self->{DEBUG} = $debugLevel;
    } else {
	$self->{DEBUG} = 0;
    }
    $self->{BLOCK} = 1;
78
    $self->{BULK} = 1;
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    $self->{NAME} = $name;

    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);
    &SNMP::addMibFiles("$mibpath/CISCO-STACK-MIB.txt",
	"$mibpath/CISCO-VTP-MIB.txt",
93
94
	"$mibpath/CISCO-PAGP-MIB.txt",
	"$mibpath/RMON-MIB.txt");
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    
    $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} =
	    new SNMP::Session(DestHost => $self->{NAME},Version => "2c");
    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
110

111
112
113
114
115
    #
    # The bless needs to occur before readifIndex(), since it's a class 
    # method
    #
    bless($self,$class);
Mac Newbold's avatar
Mac Newbold committed
116

117
    $self->readifIndex();
Mac Newbold's avatar
Mac Newbold committed
118

119
    return $self;
Mac Newbold's avatar
Mac Newbold committed
120
121
}

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#
# 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");

    #
    # 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
169
    } else {
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
	#
	# 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];
206
    if (!defined($sample)) {
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
	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; };
	$input = $PORT_FORMAT_NODEPORT; last;
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
	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) {
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
	    return map portnum($self->{NAME}.":".$self->{IFINDEX}{$_}), @ports;
234
	}
235
236
237
238
239
    } elsif ($input == $PORT_FORMAT_MODPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
	    return map portnum($self->{NAME} . $_), @ports;
240
	}
241
242
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
    } elsif ($input == $PORT_FORMAT_NODEPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
	    return map $self->{IFINDEX}{(split /:/,portnum($_))[1]}, @ports;
	} elsif ($output == $PORT_FORMAT_MODPORT) {
	    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

    #
272
    # Try max_tries times before we give up, in case some other process just
273
274
275
    # has it locked.
    #
    my $tries = 1;
276
277
    my $max_tries = 20;
    while ($tries <= $max_tries) {
278
279
280
281
282
283
284
285
286
287
288
289
    
	#
	# 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) {
290
291
292
293
294
295
296
	    #
	    # Only print this message every five tries
	    #
	    if (!($tries % 5)) {
		print STDERR "VLAN edit buffer request failed - " .
			     "try $tries of $max_tries.\n";
	    }
297
298
299
300
301
302
303
304
	} else {
	    last;
	}
	$tries++;

	sleep(1);
    }

305
    if ($tries > $max_tries) {
306
307
308
309
310
	#
	# Admit defeat and exit
	#
	print STDERR "ERROR: Failed to obtain VLAN edit buffer lock\n";
	return 0;
311
    } else {
312
313
314
315
316
317
318
319
	#
	# 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;
320
    }
321

Mac Newbold's avatar
Mac Newbold committed
322
323
}

324
325
326
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
354
355
356
#
# 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
    my $RetVal = $self->{SESS}->set([[$EditOp,1,"apply","INTEGER"]]);
    $self->debug("Apply set: '$RetVal'\n");

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

    my $ApplyRetVal = $RetVal;

    if ($RetVal ne "succeeded") {
	$self->debug("Apply failed: Gave $RetVal\n");
	# Only release the buffer if they've asked to force it.
	if (!$force) {
	    $RetVal = $self->{SESS}->set([[$EditOp,1,"release","INTEGER"]]);
	    $self->debug("Release: '$RetVal'\n");
	    if (! $RetVal ) {
357
358
		warn("VLAN Reconfiguration Failed. No changes saved.\n");
		return 0;
359
360
361
362
363
364
365
	    }
	}
    } else { 
	$self->debug("Apply Succeeded.\n");
	# If I succeed, release buffer
	$RetVal = $self->{SESS}->set([[$EditOp,1,"release","INTEGER"]]);
	if (! $RetVal ) {
366
367
	    warn("VLAN Reconfiguration Failed. No changes saved.\n");
	    return 0;
368
369
370
371
372
	}
	$self->debug("Release: '$RetVal'\n");
    }
    
    return $ApplyRetVal;
Mac Newbold's avatar
Mac Newbold committed
373
374
}

375
376
#
# Given a VLAN identifier from the database, find the cisco-specific VLAN
377
378
# number that is assigned to that VLAN. Retries several times (to account
# for propagation delays) unless the $no_retry option is given.
379
#
380
# usage: findVlan($self, $vlan_id,$no_retry)
381
382
383
#        returns the VLAN number for the given vlan_id if it exists
#        returns undef if the VLAN id is not found
#
384
sub findVlan($$;$) { 
385
386
    my $self = shift;
    my $vlan_id = shift;
387
388
389
390
391
392
393
394
    my $no_retry = shift;

    my $max_tries;
    if ($no_retry) {
	$max_tries = 1;
    } else {
	$max_tries = 10;
    }
395
396
397
398

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

    #
399
400
    # We try this a few time, with 1 second sleeps, since it can take
    # a while for VLAN information to propagate
401
    #
402
403
    foreach my $try (1 .. $max_tries) {

404
	#
405
	# Walk the tree to find the VLAN names
406
	#
407
408
409
410
411
412
413
414
	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\.//;
415

416
417
418
419
	    $self->debug("Got $name $vlan_number $vlan_name\n",2);
	    if ($vlan_name eq $vlan_id) {
		return $vlan_number;
	    }
420
421
	}

422
423
424
	#
	# Wait before we try again
	#
425
426
427
428
	if ($try != $max_tries) {
	    $self->debug("VLAN find failed, trying again\n");
	    sleep 1;
	}
429
    }
430
431
432
433
    #
    # Didn't find it
    #
    return undef;
Mac Newbold's avatar
Mac Newbold committed
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
#
# Create a VLAN on this switch, with the given identifier (which comes from
# the database.) Picks its own switch-specific VLAN number to use.
#
# usage: createVlan($self, $vlan_id)
#        returns 1 on success
#        returns 0 on failure
#
sub createVlan($$) {
    my $self = shift;
    my $vlan_id = shift;

    my $okay = 0;

    #
    # NOTE: I'm not sure why I have to give these as numeric OIDs rather
    # than using the names.
    # TODO: Figure this out
    #
    my $VlanType = '.1.3.6.1.4.1.9.9.46.1.4.2.1.3.1'; # vlan # is index
    my $VlanName = '.1.3.6.1.4.1.9.9.46.1.4.2.1.4.1'; # vlan # is index
    my $VlanSAID = '.1.3.6.1.4.1.9.9.46.1.4.2.1.6.1'; # vlan # is index
    my $VlanRowStatus = '.1.3.6.1.4.1.9.9.46.1.4.2.1.11.1'; # vlan # is index

    #
461
462
463
464
    # 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....
465
    #
466
467
468
    my $max_tries = 3;
    my $tries_remaining = $max_tries;
    while ($tries_remaining) {
469
	#
470
	# Try to wait out transient failures
471
	#
472
473
474
475
476
477
	if ($tries_remaining != $max_tries) {
	    print STDERR "VLAN creation failed, trying again " .
		"($tries_remaining tries left)\n";
	    sleep 5;
	}
	$tries_remaining--;
478

479
480
481
	if (!$self->vlanLock()) {
	    next;
	}
482

483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
	#
	# Find a free VLAN number to use. Since 1 is the default VLAN on
	# Ciscos, we start with number 2.
	# XXX: The maximum VLAN number is hardcoded at 1000
	#
	my $vlan_number = 2; # We need to start at 2
	my $RetVal = $self->{SESS}->get([$VlanRowStatus,$vlan_number]);
	$self->debug("Row $vlan_number got '$RetVal'\n",2);
	while (($RetVal ne 'NOSUCHINSTANCE') && ($vlan_number <= 1000)) {
	    $vlan_number += 1;
	    $RetVal = $self->{SESS}->get([[$VlanRowStatus,$vlan_number]]);
	    $self->debug("Row $vlan_number got '$RetVal'\n",2);
	}
	if ($vlan_number > 1000) {
	    #
	    # We must have failed to find one
	    #
	    print STDERR "ERROR: Failed to find a free VLAN number\n";
	    next;
	}
503

504
	$self->debug("Using Row $vlan_number\n");
505

506
507
508
509
510
	#
	# SAID is a funky security identifier that _must_ be set for VLAN
	# creation to suceeed.
	#
	my $SAID = pack("H*",sprintf("%08x",$vlan_number + 100000));
511

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
	print "  Creating VLAN $vlan_id as VLAN #$vlan_number ... ";

	#
	# Perform the actual creation. Yes, this next line MUST happen all in
	# one set command....
	#
	$RetVal = $self->{SESS}->set([[$VlanRowStatus,$vlan_number,
			"createAndGo","INTEGER"],
		[$VlanType,$vlan_number,"ethernet","INTEGER"],
		[$VlanName,$vlan_number,$vlan_id,"OCTETSTR"],
		[$VlanSAID,$vlan_number,$SAID,"OCTETSTR"]]);
	print "",($RetVal? "Succeeded":"Failed"), ".\n";

	#
	# Check for success
	#
	if (!$RetVal) {
	    print STDERR "VLAN Create '$vlan_id' as VLAN $vlan_number " .
		    "failed.\n";
	    next;
	} else {
	    $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;	     
	    }
	    return 1;
	}
548
    }
549
550
551
552

    print STDERR "*** Failed to create VLAN $vlan_id after $max_tries tries " .
		 "- giving up\n";
    return 0;
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
}

#
# Put the given ports in the given VLAN. The VLAN is given as a VLAN
# identifier from the database.
#
# usage: setPortVlan($self,$vlan_id, @ports)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub setPortVlan($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @ports = @_;

568
    my $PortVlanMemb = "vlanPortVlan"; #index is ifIndex
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

    my $errors = 0;

    #
    # Find the real VLAN number from the passed VLAN ID
    #
    my $vlan_number = $self->findVlan($vlan_id);
    if (!defined($vlan_number)) {
	print STDERR "ERROR: VLAN with identifier $vlan_id does not exist\n";
	return 1;
    }
    $self->debug("Found VLAN with ID $vlan_id: $vlan_number\n");

    #
    # Convert ports from the format the were passed in to IfIndex format
    #
585
    my @portlist = $self->convertPortFormat($PORT_FORMAT_MODPORT,@ports);
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612

    #
    # 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
	#
	my $RetVal = $self->{SESS}->set([$PortVlanMemb,$port,$vlan_number,
					 'INTEGER']);
	if (!$RetVal) {
	    print STDERR "$port VLAN change failed with $RetVal.\n";
	    $errors++;
	    next;
Mac Newbold's avatar
Mac Newbold committed
613
	} else {
614
	    push @okports, $port;
Mac Newbold's avatar
Mac Newbold committed
615
	}
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    }

    #
    # 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) {
	$self->debug("Disabling " . join(',',@ports) . "...");
	if ( my $rv = $self->portControl("disable",@ports) ) {
	    print STDERR "Port disable had $rv failures.\n";
	    $errors += $rv;
	}
    } else {
	$self->debug("Enabling "  . join(',',@ports) . "...");
	if ( my $rv = $self->portControl("enable",@ports) ) {
	    print STDERR "Port enable had $rv failures.\n";
	    $errors += $rv;
	}
    }
Mac Newbold's avatar
Mac Newbold committed
635

636
    return $errors;
637
638
}

639
640
641
642
#
# Remove all ports from the given VLAN. The VLAN is given as a VLAN
# identifier from the database.
#
643
# usage: removePortsFromVlan(self,int vlans)
644
645
646
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
647
sub removePortsFromVlan($@) {
648
    my $self = shift;
649
    my @vlan_ids = @_;
650
651

    #
652
    # Find the real VLAN numbers from the passed VLAN IDs
653
    #
654
655
656
657
658
659
660
661
662
    my %vlan_numbers = ();
    foreach my $vlan_id (@vlan_ids) {
	my $vlan_number = $self->findVlan($vlan_id);
	if (!defined($vlan_number)) {
	    print STDERR "ERROR: VLAN with identifier $vlan_id does not exist\n";
	    return 1;
	}
	$self->debug("Found VLAN with ID $vlan_id: $vlan_number\n");
	$vlan_numbers{$vlan_number} = 1;
663
664
665
666
667
    }

    #
    # Get a list of the ports in the VLAN
    #
668
669
    my $VlanPortVlan = ["vlanPortVlan"]; # index by module.port, gives vlan
    my @ports;
670
671
672
673

    #
    # Walk the tree to find VLAN membership
    #
674
    my ($rows) = $self->{SESS}->bulkwalk(0,32,$VlanPortVlan);
675
    foreach my $rowref (@$rows) {
676
677
678
	my ($name,$modport,$port_vlan_number) = @$rowref;
	$self->debug("Got $name $modport $port_vlan_number\n");
	if ($vlan_numbers{$port_vlan_number}) {
679
	    push @ports, $modport;
Mac Newbold's avatar
Mac Newbold committed
680
681
682
	}
    }

683
684
685
    $self->debug("About to remove ports " . join(",",@ports) . "\n");
    if (@ports) {
	return $self->setPortVlan("default",@ports);
Mac Newbold's avatar
Mac Newbold committed
686
    } else {
687
	return 0;
Mac Newbold's avatar
Mac Newbold committed
688
    }
689
690
691
692
693
}

#
# Remove the given VLAN from this switch. This presupposes that all of its
# ports have already been removed with removePortsFromVlan(). The VLAN is
Robert Ricci's avatar
Robert Ricci committed
694
# given as a VLAN identifier from the database.
695
696
697
698
699
700
#
# usage: removeVlan(self,int vlan)
#	 returns 1 on success
#	 returns 0 on failure
#
#
701
sub removeVlan($@) {
702
    my $self = shift;
703
    my @vlan_ids = @_;
704
705
706
707
708
709
710
711

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

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
    my $errors = 0;

    foreach my $vlan_id (@vlan_ids) {
	#
	# Find the real VLAN number from the passed VLAN ID
	#
	my $vlan_number = $self->findVlan($vlan_id);
	if (!defined($vlan_number)) {
	    print STDERR "ERROR: VLAN with identifier $vlan_id does ".
		    "not exist\n";
	    return 0;
	}
	$self->debug("Found VLAN with ID $vlan_id: $vlan_number\n");

	#
	# Perform the actual removal
	#
	my $VlanRowStatus = '.1.3.6.1.4.1.9.9.46.1.4.2.1.11.1'; # vlan is index

	print "  Removing VLAN #$vlan_number ... ";
	my $RetVal = $self->{SESS}->set([$VlanRowStatus,$vlan_number,
					 "destroy","INTEGER"]);
	if ($RetVal) {
	    print "Succeeded.\n";
	} else {
	    print "Failed.\n";
	    $errors++;
	}
    }
741
742
743
744
745
746

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

747
    if ($errors) {
748
	return 0;
Mac Newbold's avatar
Mac Newbold committed
749
    } else {
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
	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) {
	my $trans = $self->{IFINDEX}{$port};
	if (defined $trans) {
	    if (defined (portnum("$self->{NAME}:$trans"))) {
		$trans = "$trans,".portnum("$self->{NAME}:$trans");
	    } else {
		$trans = "$trans,".portnum("$self->{NAME}:$port");
Mac Newbold's avatar
Mac Newbold committed
772
773
	    }
	} else {
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
	    $trans = "???";
	}
	$self->debug("Checking port $port ($trans) for $val...");
	$Status = $self->{SESS}->get([[$OID,$port]]);
	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) {
			$Status=$self->{SESS}->get([[$OID,$port]]);
			$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
807
808
	}
    }
809
810
    # returns 0 on success, # of failed ports on failure
    $err;
Mac Newbold's avatar
Mac Newbold committed
811
812
}

813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
#
# 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 #
    my $VlanPortVlan = ["vlanPortVlan"]; # index by module.port, gives vlan #

    #
    # Walk the tree to find the VLAN names
    #
    my ($rows) = $self->{SESS}->bulkwalk(0,32,$VlanName);
    my %Names = ();
    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",3);
	if (!$Names{$vlan_number}) {
	    $Names{$vlan_number} = $vlan_name;
	}
Mac Newbold's avatar
Mac Newbold committed
844
    }
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874

    #
    # Walk the tree for the VLAN members
    #
    ($rows) = $self->{SESS}->bulkwalk(0,32,$VlanPortVlan);
    my %Members = ();
    foreach my $rowref (@$rows) {
	my ($name,$modport,$vlan_number) = @$rowref;
	$self->debug("Got $name $modport $vlan_number\n",3);
	my $node;
	($node = portnum("$self->{NAME}:$modport")) || ($node = "port$modport");
	push @{$Members{$vlan_number}}, $node;
    }

    #
    # 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}];
    	}
    }
    $self->debug(join("\n",@list)."\n",2);

    return @list;
Mac Newbold's avatar
Mac Newbold committed
875
876
}

877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
#
# 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
933
934
}

935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# 
# 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++;
    }

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

Mac Newbold's avatar
Mac Newbold committed
976
977
}

978
979
980
#
# Enable, or disable,  port on a trunk
#
981
# usage: setVlansOnTrunk(self, modport, value, vlan_numbers)
982
983
#        modport: module.port of the trunk to operate on
#        value: 0 to disallow the VLAN on the trunk, 1 to allow it
984
#	 vlan_numbers: An array of cisco-native VLAN numbers operate on
985
986
#        Returns 1 on success, 0 otherwise
#
987
sub setVlansOnTrunk($$$$) {
988
    my $self = shift;
989
    my ($modport, $value, @vlan_numbers) = @_;
990
991
992
993
994
995
996

    #
    # Some error checking
    #
    if (($value != 1) && ($value != 0)) {
	die "Invalid value $value passed to setVlanOnTrunk\n";
    }
997
    if (grep(/^1$/,@vlan_numbers)) {
998
999
1000
	die "VLAN 1 passed to setVlanOnTrunk\n"
    }