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

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

Mac Newbold's avatar
Mac Newbold committed
9 10 11 12 13 14 15 16 17 18
#
# snmpit module for Intel EtherExpress 510T switches
#

# Special Note:
# Because this code is not urgently needed, and it is unknown if it ever
# will be needed again, it has not been debugged since moving it into 
# this module. So don't count on it. It will need to be debugged before
# actually using it for anything useful.

19 20
package snmpit_intel;
use strict;
Mac Newbold's avatar
Mac Newbold committed
21

22
$| = 1;				# Turn off line buffering on output
Mac Newbold's avatar
Mac Newbold committed
23

24
use English;
Mac Newbold's avatar
Mac Newbold committed
25 26 27
use SNMP;
use snmpit_lib;

28 29 30 31 32 33
#
# These are the commands that can be passed to the portControl function
# below
#
my %cmdOIDs = 
(
34 35
    "enable" => ["ifAdminStatus","up"],
    "disable"=> ["ifAdminStatus","down"],
36 37 38 39 40 41 42 43 44
    "100mbit"=> [".1.3.6.1.4.1.343.6.10.2.4.1.12.1.1","disable",
		 ".1.3.6.1.4.1.343.6.10.2.4.1.10.1.1","speed100Mbit"],
    "10mbit" => [".1.3.6.1.4.1.343.6.10.2.4.1.12.1.1","disable",
		 ".1.3.6.1.4.1.343.6.10.2.4.1.10.1.1","speed10Mbit"],
    "full"   => [".1.3.6.1.4.1.343.6.10.2.4.1.12.1.1","disable",
		 ".1.3.6.1.4.1.343.6.10.2.4.1.11.1.1","full"],
    "half"   => [".1.3.6.1.4.1.343.6.10.2.4.1.12.1.1","disable",
		 ".1.3.6.1.4.1.343.6.10.2.4.1.11.1.1","half"],
    "auto"   => [".1.3.6.1.4.1.343.6.10.2.4.1.12.1.1","enable"]
45
);
Mac Newbold's avatar
Mac Newbold committed
46

47 48 49 50 51 52 53

#
# Creates a new object.
#
# usage: new($classname,$devicename,$debuglevel)
#        returns a new object, blessed into the snmpit_intel class.
#
Mac Newbold's avatar
Mac Newbold committed
54 55
sub new {

56 57 58
    # The next two lines are some voodoo taken from perltoot(1)
    my $proto = shift;
    my $class = ref($proto) || $proto;
Mac Newbold's avatar
Mac Newbold committed
59

60 61
    my $name = shift;
    my $debugLevel = shift;
62
    my $community = shift;
Mac Newbold's avatar
Mac Newbold committed
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
    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
	$self->{DEBUG} = $debugLevel;
    } else {
	$self->{DEBUG} = 0;
    }
77 78
    $self->{BLOCK} = 1;
    $self->{CONFIRM} = 1;
79
    $self->{NAME} = $name;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    
    #
    # 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'};
    }
Mac Newbold's avatar
Mac Newbold committed
98

99
    if ($self->{DEBUG}) {
100
	print "snmpit_intel module initializing... debug level $self->{DEBUG}\n"
101 102 103
	;   
    }

104 105 106 107 108 109 110 111
    #
    # This variable is used to determined how deep in locking the VLAN edit
    # buffer we are. This is so that we can have 'nested' calls to vlanLock,
    # and only the first one will grab the lock from the switch, and only
    # the last call to vlanUnlock will unlock on the switch.
    #
    $self->{LOCKLEVEL} = 0;

112 113 114 115 116 117
    #
    # 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);
118 119 120 121
    &SNMP::addMibFiles("$mibpath/SNMPv2-SMI.txt", "$mibpath/SNMPv2-TC.txt", 
	               "$mibpath/SNMPv2-MIB.txt", "$mibpath/IANAifType-MIB.txt",
		       "$mibpath/IF-MIB.txt",
		       "$mibpath/INT_GEN.MIB", 
122 123 124 125 126 127 128 129
		       "$mibpath/INT_S500.MIB",
		       "$mibpath/INT_VLAN.MIB");
    $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});

130 131
    $self->{SESS} = new SNMP::Session(DestHost => $self->{NAME},
	Community => $self->{COMMUNITY});
132 133 134 135 136 137 138 139 140 141 142

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

    bless($self,$class);
    return $self;
Mac Newbold's avatar
Mac Newbold committed
143 144
}

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
#
# 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");

    my @p = map { portnum($_) } @ports;

    #
165 166 167
    # Find the command in the %cmdOIDs hash (defined at the top of this file).
    # Some commands involve multiple SNMP commands, so we need to make sure
    # we get all of them
168
    #
169 170 171 172 173 174 175 176 177 178
    if (defined $cmdOIDs{$cmd}) {
	my @oid = @{$cmdOIDs{$cmd}};
	my $errors = 0;

	while (@oid) {
	    my $myoid = shift @oid;
	    my $myval = shift @oid;
	    $errors += $self->UpdateField($myoid,$myval,@ports);
	}
	return $errors;
179 180 181 182 183 184 185
    } else {
	#
	# Command not supported
	#
	print STDERR "Unsupported port control command '$cmd' ignored.\n";
	return -1;
    }
Mac Newbold's avatar
Mac Newbold committed
186 187
}

188 189
#
# Obtain a lock on the VLAN edit buffer. This must be done before VLANs
190
# are created or removed, or ports are assigned to VLANs. Will retry 60
191 192 193 194 195 196
# times before failing
#
# usage: vlanLock($self)
#        returns 1 on success
#        returns 0 on failure
#
197 198 199 200 201 202 203 204 205
sub vlanLock($) {
    my $self = shift;

    my $TokenOwner = '.1.3.6.1.4.1.343.6.11.4.5';
    my $TokenReq = '.1.3.6.1.4.1.343.6.11.4.6';
    my $TokenReqResult = '.1.3.6.1.4.1.343.6.11.4.7';
    my $TokenRelease = '.1.3.6.1.4.1.343.6.11.4.8';
    my $TokenReleaseResult = '.1.3.6.1.4.1.343.6.11.4.9';

206 207 208 209 210 211 212 213 214 215 216
    #
    # For nested locks - if we're called, but already locked, we just
    # report sucess and increase the lock level
    #
    if ($self->{LOCKLEVEL}) {
	$self->debug("vlanLock - already at lock level $self->{LOCKLEVEL}\n");
	$self->{LOCKLEVEL}++;
	return 1;
    }
    $self->{LOCKLEVEL} = 1;

217 218 219 220 221 222 223 224 225 226
    #
    # Some magic needed by the Intel switch
    #
    my $Num = pack("C*",0,0,0,0,1,1);

    #
    # Try max_tries times before we give up, in case some other process just
    # has it locked.
    #
    my $tries = 1;
227
    my $max_tries = 60;
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    while ($tries <= $max_tries) {

	#
	# Attempt to grab the edit buffer
	#
	$self->{SESS}->set([[$TokenReq,0,$Num,"OCTETSTR"]]);
	my $RetVal = $self->{SESS}->get([[$TokenReqResult,0]]);
	while ($RetVal eq "notReady") {
	    $RetVal = $self->{SESS}->get([[$TokenReqResult,0]]);
	    $self->debug("*VLAN Token Claim Result is $RetVal\n");
	    select (undef, undef, undef, .25); #wait 1/4 second
	}

	$self->debug("VLAN Token Claim Result is $RetVal\n");

	if ($RetVal ne 'success') {
	    #
	    # Only print this message every five tries
	    #
	    if (!($tries % 5)) {
		print STDERR "VLAN edit buffer request failed - " .
		"try $tries of $max_tries.\n";
	    }
	} else {
	    last;
	}
	$tries++;

	sleep(1);
Mac Newbold's avatar
Mac Newbold committed
257
    }
258 259 260 261 262 263 264 265 266

    if ($tries > $max_tries) {
	#
	# Admit defeat and exit
	#
	print STDERR "ERROR: Failed to obtain VLAN edit buffer lock\n";
	return 0;
    } else {
	return 1;
Mac Newbold's avatar
Mac Newbold committed
267
    }
268

Mac Newbold's avatar
Mac Newbold committed
269 270
}

271 272
#
# Release a lock on the VLAN edit buffer. As part of releasing, applies the
273 274 275
# VLAN edit buffer. If $self->{CONFIRM} is set, uses the saveWithConfirmOption,
# which requires the porcess to confirm the changes, or they are cancelled
# (so that you don't accidentally cut yourself off from the switch.)
276 277 278 279 280 281 282 283 284 285
#
# usage: vlanUnlock($self)
#        
sub vlanUnlock($;$) {
    my $self = shift;

    my $TokenRelease = '.1.3.6.1.4.1.343.6.11.4.8';
    my $TokenReleaseResult = '.1.3.6.1.4.1.343.6.11.4.9';
    my $TokenConfirmState = '.1.3.6.1.4.1.343.6.11.1.18';

286 287 288 289 290 291 292 293 294 295 296
    #
    # Allow for nested locks - only release the lock if our locklevel
    # is down to 1 (ie. we're the last level that cares about the lock)
    #
    if ($self->{LOCKLEVEL} > 1) {
	$self->debug("vlanUnock - at lock level $self->{LOCKLEVEL}\n");
	$self->{LOCKLEVEL}--;
	return 1;
    }
    $self->{LOCKLEVEL} = 0;

297 298
    my $save = ($self->{CONFIRM} ? "saveWithConfirmOption" : "save");

299 300 301
    #
    # Relse the token
    #
302 303 304 305 306
    $self->debug("Releasing Token with $save command\n");
    $self->{SESS}->set([[$TokenRelease,0,$save,"INTEGER"]]);
    my $RetVal = $self->{SESS}->get([[$TokenReleaseResult,0]]);
    $self->debug("VLAN Configuration Save Result is $RetVal\n");

307 308 309
    #
    # Wait for the switch to report that the token has been released
    #
Mac Newbold's avatar
Mac Newbold committed
310
    while ($RetVal eq "notReady") {
311 312 313
	$RetVal = $self->{SESS}->get([[$TokenReleaseResult,0]]);
	$self->debug("VLAN Configuration Save Result is $RetVal\n");
	select (undef, undef, undef, .25); #wait 1/4 second
Mac Newbold's avatar
Mac Newbold committed
314
    }
315 316

    if ($self->{CONFIRM}) {
317 318 319 320 321

	#
	# Wait for the switch to report that it's ready to recieve
	# confirmation of the release
	#
322 323 324 325 326 327 328 329
	$RetVal = $self->{SESS}->get([[$TokenConfirmState,0]]);
	$self->debug("VLAN Configuration Confirm Result is $RetVal\n");
	while ($RetVal eq "notReady") {
	    sleep(2);
	    $RetVal = $self->{SESS}->get([[$TokenConfirmState,0]]);
	    $self->debug("VLAN Configuration Confirm Result is $RetVal\n");
	}

330 331 332
	#
	# Confirm the release
	#
333
	if ($RetVal eq "ready") {
334 335
	    $RetVal = $self->{SESS}->set([[$TokenConfirmState,0,"confirm",
		"INTEGER"]]);
336 337 338
	    $self->debug("VLAN Configuration Confirm Result is $RetVal\n");
	} # XXX: Should there be an 'else'?

339 340 341
	#
	# Wait for the switch to confirm the confirmation
	#
342 343 344 345 346
	while (!($RetVal =~ /Conf/i)) {
	    $RetVal = $self->{SESS}->get([[$TokenConfirmState,0]]);
	    $self->debug("VLAN Configuration Confirm Result is $RetVal\n");
	}

347 348 349
	#
	# Make sure the confirmation was confirmed
	#
350
	if ($RetVal ne "confirmedNewConf") {
351 352
	    warn("VLAN Reconfiguration Failed ($RetVal). No changes saved.\n");
	    return 0;
353 354
	}

355 356 357 358
    } else { # if $self->{CONFIRM}
	#
	# Just check the return value
	#
359
	if ($RetVal ne 'success') {
360 361
	    warn("VLAN Reconfiguration Failed: $RetVal. No changes saved.\n");
	    return 0;
362
	}
Mac Newbold's avatar
Mac Newbold committed
363 364 365
    }
}

366
#
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
# Given VLAN indentifiers from the database, finds the Intel-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 Intel VLAN numbers
#        any VLANs not found have NULL VLAN numbers
#
sub findVlans($@) { 
    my $self = shift;
    my @vlan_ids = @_;

    my $field = ["policyVlanName",0];

    my %mapping = ();
    @mapping{@vlan_ids} = undef;

    #
    # Find all VLAN names. Do one to get the first field...
    #
    $self->{SESS}->getnext($field);
    my ($name,$vlan_number,$vlan_name);
    do {
	($name,$vlan_number,$vlan_name) = @{$field};
	$self->debug("findVlan: Got $name $vlan_number $vlan_name\n");

	#
	# We only want the names - we ignore everything else
	#
	if ($name =~ /policyVlanName/) {
	    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;
	    }
	}

	$self->{SESS}->getnext($field);
    } while ( $name =~ /^policyVlanName/) ;

    return %mapping;
}

#
# Given a VLAN identifier from the database, find the Intel-specific VLAN
412 413
# number that is assigned to that VLAN. Retries several times (to account
# for propagation delays) unless the $no_retry option is given.
414
#
415 416 417
# 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
418
#
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
sub findVlan($$;$) { 
    my $self = shift;
    my $vlan_id = shift;
    my $no_retry = shift;

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

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

437 438 439 440
	my %mapping = $self->findVlans($vlan_id);
	if (defined($mapping{$vlan_id})) {
	    return $mapping{$vlan_id};
	}
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

	#
	# Wait before we try again
	#
	if ($try != $max_tries) {
	    $self->debug("VLAN find failed, trying again\n");
	    sleep 1;
	}
    }
    #
    # Didn't find it
    #
    return undef;
}

#   
# Create a VLAN on this switch, with the given identifier (which comes from
458 459
# the database.) Picks its own switch-specific VLAN number to use. If ports
# are given, puts them in the newly-created VLAN.
460
#
461
# usage: createVlan($self, $vlan_id,@ports)
462 463 464
#        returns 1 on success
#        returns 0 on failure
#
465
sub createVlan($$;@) {
466 467
    my $self = shift;
    my $vlan_id = shift;
468
    my @ports = @_;
469 470 471 472 473 474 475 476 477 478 479 480 481

    my $okay = 0;

    if (!$self->vlanLock()) {
	return 0;
    }

    my $NextVLANId = '.1.3.6.1.4.1.343.6.11.1.6';
    my $CreateOID = ".1.3.6.1.4.1.343.6.11.1.9.1.3";
    my $RetVal = "Undef.";

    #
    # Intel provides us with a handy way to pick a VLAN number
482 483
    # NOTE: This will respect the MAX_VLAN variable, but not the MIN_VLAN
    # one
484 485
    #
    my $vlan_number = $self->{SESS}->get([[$NextVLANId,0]]);
486 487 488 489
    if ($vlan_number > $self->{MAX_VLAN}) {
	print STDERR "ERROR: Returned VLAN was too high ($vlan_number)\n";
	return 0;
    }
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

    #
    # Pick a name if one was not given
    #
    if (!$vlan_id) {
	$vlan_id = $vlan_number;
    }

    print "  Creating VLAN $vlan_id as VLAN #$vlan_number ... ";
    $RetVal = $self->{SESS}->set([[$CreateOID,$vlan_number,$vlan_id,
	"OCTETSTR"]]);
    if ($RetVal) {
	$okay = 1;
	print "Succeeded\n";
    } else {
	print "Failed\n";
	$okay = 0;
    }

509 510 511 512 513
    #
    # If we wre given any ports, put them into the VLAN now, so that
    # we can do this without unlocking/relocking.
    #
    if ($okay && @ports) {
514
	$self->debug("CreateVlan: port list is ".join(",",@ports)."\n");
515 516 517 518 519
	if ($self->setPortVlan($vlan_id,@ports)) {
	    $okay = 0;
	}
    }

520 521
    $self->vlanUnlock();

522
    return $okay;
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 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 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

}

#
# 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 = @_;

    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");

    #
    # Run the port list through portmap to find the ports on the switch that
    # we are concerned with
    #
    $self->debug("Raw port list: " . join(",",@ports) . "\n");
    my @portlist = map { portnum($_) } @ports;

    if (!$self->vlanLock()) {
	return 1;
    }

    foreach my $port (@portlist) {
	#
	# The value returned from portmap looks like: intel1:1.1 . It's
	# only the last part, the port number, that we acutally care about
	# (since intels don't have multiple cards, every port is considered
	# to be on port 1)
	#
	$port =~ /:1\.(\d+)$/;
	$port = $1;

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

	# 
	# Remove the port from all VLANs it's currently in (or we can end
	# up with it in multiple VLANs)
	#
	$self->removePortFromVlans($port);

	#
	# Do the acutal SNMP command
	#
	my $policyPortRuleCreateObj = "policyPortRuleCreateObj";
	my $RetVal = $self->{SESS}->set([$policyPortRuleCreateObj,
	    "$vlan_number.$port",$vlan_number,'OCTETSTR']);

	if (!$RetVal) {
	    print STDERR "$port VLAN change failed with $RetVal.\n";
	    $errors++;
	    next;
	}

	#
	# Ports going into the System vlan are being taken out of circulation,
	# so we disable them. Otherwise, we need to make sure they get enabled.
	#
	if ($vlan_id eq "System") {
	    $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;
	    }
	}
    }

    $self->vlanUnlock();

    return $errors;

}

#
# Remove a port from all VLANs of which it it currently a member
#
# usage: removePortFromVlans(self,int port)
#	 returns 0 on sucess.
#	 returns the number of failed VLANs on failure.
#
sub removePortFromVlans($$) {
    my $self = shift;
    my $port_number = shift;

    my $errors = 0;

    $self->debug("removePortFromVlans($port_number) called\n");
    my $field = ["policyPortRuleDeleteObj",0];

    if (!$self->vlanLock()) {
	return 1;
    }

    #
    # Do one to get the first field...
    #
    $self->{SESS}->getnext($field);
    my ($name,$index,$value);
    do {
	($name,$index,$value) = @{$field};
	$self->debug("removePortFromVlans: Got $name $index $value\n");

	if ($name eq "policyPortRuleDeleteObj") {
	    #
	    # This table is indexed by vlan.port
	    #
	    $index =~ /(\d+)\.(\d+)/;
	    my ($vlan,$port) = ($1,$2);

	    #
	    # If this was the port we're looking for, nuke it!
	    #
	    if ($port == $port_number) {
		my $RetVal = $self->{SESS}->set(["policyPortRuleDeleteObj",
		    $index,1,"INTEGER"]);
		if (!$RetVal) {
		    $errors++;
		}
	    }
	}
	$self->{SESS}->getnext($field);

    } while ( $name =~ /^policyPortRuleDeleteObj/) ;

    $self->vlanUnlock();

    return $errors;

}

#
# Remove all ports from the given VLAN. The VLAN is given as a VLAN
# identifier from the database.
#
# usage: removePortsFromVlan(self,int vlan)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub removePortsFromVlan($$) {
    my $self = shift;
    my $vlan_id = shift;

    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");

    if (!$self->vlanLock()) {
	return 1;
    }

    my $field = ["policyPortRuleDeleteObj",0];

    #
    # Do one to get the first field...
    #
    $self->{SESS}->getnext($field);
    my ($name,$index,$value);
    do {
	($name,$index,$value) = @{$field};
	if ($name eq "policyPortRuleDeleteObj") {
	    $self->debug("removePortsFromVlan: Got $name $index $value\n");

	    #
	    # This table is indexed by vlan.port
	    #
	    $index =~ /(\d+)\.(\d+)/;
	    my ($vlan,$port) = ($1,$2);

	    if ($vlan == $vlan_number) {
		#
		# Remove the port from this VLAN
		#
		$self->debug("Removing $port from vlan $vlan\n");
		my $RetVal = $self->{SESS}->set(["policyPortRuleDeleteObj",
		    $index,1,"INTEGER"]);
737
		if (!$RetVal) {
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
		    $errors++;
		}

		#
		# Put the port in the System VLAN. We have to translate the
		# port into node:port form since that's what setPortVlan
		# expects.
		#
		my $portnum = portnum("$self->{NAME}:1.$port");
		$self->debug("Calling setPortVlan(System,$portnum)");
		my $errors += $self->setPortVlan("System",$portnum);
	    }
	}
	$self->{SESS}->getnext($field);

    } while ( $name =~ /^policyPortRuleDeleteObj/) ;

    $self->vlanUnlock();

    return $errors;

}
760 761

#
762 763
# Remove the given VLAN from this switch. Removes all ports from the VLAN,
# so it's not necessary to call removePortsFromVlan() first. The VLAN is
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
# given as a VLAN identifier from the database.
#
# usage: removeVlan(self,int vlan)
#        returns 1 on success
#        returns 0 on failure
#
#
sub removeVlan($$) {
    my $self = shift;
    my $vlan_id = shift;

    #
    # 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;
Mac Newbold's avatar
Mac Newbold committed
782
    }
783 784 785 786 787 788 789
    $self->debug("Found VLAN with ID $vlan_id: $vlan_number\n");

    #
    # Need to lock the VLAN edit buffer
    #
    if (!$self->vlanLock()) {
	return 0;
Mac Newbold's avatar
Mac Newbold committed
790 791
    }

792 793 794 795 796 797 798 799 800 801 802
    #
    # First, remove all ports from this VLAN
    #
    if ($self->removePortsFromVlan($vlan_id)) {
	#
	# Uh oh, something went wrong. Unlock and bail
	#
	$self->vlanUnlock();
	return 0;
    }

803 804 805 806 807 808 809
    #
    # Perform the actual removal
    #
    my $DeleteOID = ".1.3.6.1.4.1.343.6.11.1.9.1.4";
    my $RetVal = "Undef.";

    print "  Removing VLAN #$vlan_number ... ";
810 811
    $RetVal = $self->{SESS}->set([[$DeleteOID,$vlan_number,"delete",
	"INTEGER"]]);
812 813 814 815 816 817 818 819
    my $ok;
    if ($RetVal) {
	print "Succeeded.\n";
	$ok = 1;
    } else {
	print "Failed.\n";
	$ok = 0;
    }
820 821 822 823 824 825 826 827

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

    if (! defined $RetVal) {
	print STDERR "VLAN #$vlan_number does not exist on this switch.\n";
Mac Newbold's avatar
Mac Newbold committed
828
    }
829

830
    return $ok;
Mac Newbold's avatar
Mac Newbold committed
831 832 833
}

#
834
# XXX: Major cleanup
Mac Newbold's avatar
Mac Newbold committed
835
#
836 837 838 839 840 841 842 843
sub UpdateField($$$@) {
    my $self = shift;
    my ($OID,$val,@ports)= @_;

    my $Status = 0;
    my $err = 0;

    $self->debug("UpdateField: '@_'\n");
Mac Newbold's avatar
Mac Newbold committed
844 845

    foreach my $port (@ports) {
846 847 848 849 850 851 852 853 854 855 856 857
	#
	# Check the input format - the ports might already be in
	# switch:module.port form, or we may have to convert them to it with
	# portnum
	#
	if ($port =~ /:1\.(\d+)/) {
	    $port = $1;
	} else {
	    $port = portnum($port);
	    $port =~ /:1\.(\d+)/;
	    $port = $1;
	}
858
	$self->debug("Checking port $port for $val...");
859
	$Status = $self->{SESS}->get([$OID,$port]);
860 861 862 863 864 865 866 867 868 869 870 871 872
	if (!defined $Status) {
	    print STDERR "Port $port, 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...");
		# The empty sub {} is there to force it into async mode
		$self->{SESS}->set([[$OID,$port,$val,"INTEGER"]],sub {});
		if ($self->{BLOCK}) {
		    while ($Status ne $val) { 
			$Status = $self->{SESS}->get([[$OID,$port]]);
873
			$self->debug("Value for $port was $Status\n");
874 875
			# XXX: Timeout
		    }
876
		    #print "Okay.\n";
877
		} else {
878
		    #print "\n";
879 880
		}
	    }
Mac Newbold's avatar
Mac Newbold committed
881
	}
882

Mac Newbold's avatar
Mac Newbold committed
883
    }
884 885


886
    return 0;
Mac Newbold's avatar
Mac Newbold committed
887 888
}

889 890 891 892 893 894
#
# List all VLANs on the device
#
# usage: listVlans($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
895
sub listVlans($) {
896 897
    my $self = shift;

898 899 900 901
    my %Names = ();
    my %Members = ();

    #
902
    # First, we grab the names of all VLANs
903
    #
904
    my $field = ["policyVlanName",0];
905 906 907 908 909 910 911
    my ($varname,$index,$vlan_number);
    $self->{SESS}->getnext($field);
    do {
	($varname,$index,$vlan_number) = @{$field};
	$self->debug("listVlans: Got $varname $index $vlan_number\n");
	if ($varname =~ /policyVlanName/) {
	    $Names{$index} = $vlan_number
912 913 914 915 916 917 918 919 920 921 922 923 924
	}
	$self->{SESS}->getnext($field);
    } while ( $varname eq "policyVlanName");

    #
    # Next, we find membership, by port
    #
    $field = ["policyPortRuleVlanId",0];
    $self->{SESS}->getnext($field);
    do {
	($varname,$index,$vlan_number) = @{$field};
	$self->debug("listVlans: Got $varname $index $vlan_number\n");
	if ($varname =~ /policyPortRuleVlanId/) {
925 926 927 928 929 930 931 932 933 934 935 936 937 938
	    #
	    # This table is indexed by vlan.port
	    #
	    $index =~ /(\d+)\.(\d+)/;
	    my $port = $2;

	    #
	    # Find out the real node name. We just call it portX if
	    # it doesn't seem to have one.
	    #
	    my $node;
	    ($node = portnum($self->{NAME} . ":1." . $port)) ||
			($node = "port$port");

939 940
	    push @{$Members{$vlan_number}}, $node;
	}
941

942
	$self->{SESS}->getnext($field);
943

944
    } while ( $varname eq "policyPortRuleVlanId" );
945 946 947 948 949 950 951

    #
    # Build a list from the name and membership lists
    #
    my @list = ();

    foreach my $vlan_id ( sort {$a <=> $b} keys %Names ) {
952 953 954 955 956 957 958
	#
	# Special case - we don't want to list the System VLAN, as that's
	# where ports that are not in use go. (This is the same as ignoring
	# VLAN #1 on Cisco's
	#
	next if ($Names{$vlan_id} eq "System");

959
	#
960 961
	# Check for members to avoid pushing an undefined value into
	# the array (which causes warnings elsewhere)
962
	#
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 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 1045 1046 1047
	if ($Members{$vlan_id}) {
	    push @list, [$Names{$vlan_id},$vlan_id,$Members{$vlan_id}];
	} else {
	    push @list, [$Names{$vlan_id},$vlan_id,[]];
	}
    }

    $self->debug("LIST:\n".join("\n",@list)."\n",2);
    return @list;
}

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

    my %Able = ();
    my %Link = ();
    my %auto = ();
    my %speed = ();
    my %duplex = ();

    # XXX: do these get in the way?
    my $MinPorts = 1;
    my $MaxPorts = 24;

    my $ifTable = ["ifAdminStatus",0];

    #
    # Get the ifAdminStatus (enabled/disabled) and ifOperStatus
    # (up/down)
    #
    my ($varname, $port, $status);
    $self->{SESS}->getnext($ifTable);
    do {
	($varname,$port,$status) = @{$ifTable};
	$self->debug("$varname $port $status\n");
	if (($port >= $MinPorts) && ($port <= $MaxPorts)) {
	    if ($varname =~ /AdminStatus/) { 
		$Able{$port} = ($status =~/up/ ? "yes" : "no");
	    }
	    if ($varname =~ /OperStatus/) { 
		$Link{$port} = $status;
	    } 
	}
	$self->{SESS}->getnext($ifTable);
    } while ( $varname =~ /^i(f)(.*)Status$/) ;

    #
    # Get the port configuration, including speed, duplex, and whether or not
    # it is autoconfiguring
    #
    my $portConf = ["portConfSpeed",0];
    $self->{SESS}->getnext($portConf);
    do {
	$self->debug("$varname $port $status\n");
	($varname,$port,$status) = @{$portConf};
	$port =~ s/\./:/g;
	$port = (split(":",$port))[2];
	if (($port >= $MinPorts) && ($port <= $MaxPorts)) {
	    if ($varname =~ /Speed/) {
		$status =~ s/speed//;
		$status =~ s/autodetect/\(auto\)/i;
		$speed{$port} = $status;
	    } elsif ($varname =~ /Duplex/) { 
		$status =~ s/autodetect/\(auto\)/i;
		$duplex{$port} = $status;
	    } elsif ($varname =~ /AutoNeg/) {
		$auto{$port} = $status;
	    } 
	}
	$self->{SESS}->getnext($portConf);
    } while ( $varname =~ /^portConf(Speed|Duplex|AutoNeg)$/);

    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
    foreach my $id ( keys %Able ) {
	my $port = portnum($self->{NAME} . ":1." . $id);
1048

1049 1050 1051 1052 1053 1054
	#
	# Skip ports that don't seem to have anything interesting attached
	#
	if (!$port) {
	    $self->debug("$id does not seem to be connected, skipping\n");
	    next;
1055
	}
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	if (! defined ($speed{$id}) ) { $speed{$id} = " "; }
	if (! defined ($duplex{$id}) ) { $duplex{$id} = " "; }
	push @rv, [$port,$Able{$id},$Link{$id},$speed{$id},$duplex{$id}];
    }
    return @rv;

}

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

    my $MinPorts = 1;
    my $MaxPorts = 24;

    my $ifTable = ["ifInOctets",0];
    my %inOctets=();
    my %inUcast=();
    my %inNUcast=();
    my %inDiscard=();
    my %inErr=();
    my %inUnkProt=();
    my %outOctets=();
    my %outUcast=();
    my %outNUcast=();
    my %outDiscard=();
    my %outErr=();
    my %outQLen=();

    #
    # Walk the whole stats tree, and fill these ha
    #
    $self->{SESS}->getnext($ifTable);
    my ($varname, $port, $value);
    do {
	($varname,$port,$value) = @{$ifTable};
	$self->debug("getStats: Got $varname, $port, $value\n");
	if (($port >= $MinPorts) && ($port <= $MaxPorts)) {
	    if ($varname =~ /InOctets/) {
		$inOctets{$port} = $value;
	    } elsif ($varname =~ /InUcast/) {
		$inUcast{$port} = $value;
	    } elsif ($varname =~ /InNUcast/) {
		$inNUcast{$port} = $value;
	    } elsif ($varname =~ /InDiscard/) {
		$inDiscard{$port} = $value;
	    } elsif ($varname =~ /InErrors/) {
		$inErr{$port} = $value;
	    } elsif ($varname =~ /InUnknownP/) {
		$inUnkProt{$port} = $value;
	    } elsif ($varname =~ /OutOctets/) {
		$outOctets{$port} = $value;
	    } elsif ($varname =~ /OutUcast/) {
		$outUcast{$port} = $value;
	    } elsif ($varname =~ /OutNUcast/) {
		$outNUcast{$port} = $value;
	    } elsif ($varname =~ /OutDiscard/) {
		$outDiscard{$port} = $value;
	    } elsif ($varname =~ /OutErrors/) {
		$outErr{$port} = $value;
	    } elsif ($varname =~ /OutQLen/) {
		$outQLen{$port} = $value;
	    }
	}
	$self->{SESS}->getnext($ifTable);
    } while ( $varname =~ /^i[f](In|Out)/) ;

    #
    # Put all of the data gathered in the loop into a list suitable for
    # returning
    #
    my @rv = ();
    foreach my $id ( keys %inOctets ) {
	my $port = portnum($self->{NAME} . ":1." . $id);

	#
	# Skip ports that don't seem to have anything interesting attached
	#
	if (!$port) {
	    $self->debug("$id does not seem to be connected, skipping\n");
	    next;
	}
	push @rv, [$port,$inOctets{$id},$inUcast{$id},$inNUcast{$id},
		$inDiscard{$id},$inErr{$id},$inUnkProt{$id},$outOctets{$id},
		$outUcast{$id},$outNUcast{$id},$outDiscard{$id},$outErr{$id},
		$outQLen{$id}];

    }
    return @rv;
1151

Mac Newbold's avatar
Mac Newbold committed
1152 1153
}

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
#
# usage: getFields(self,ports,oids)
#        ports: Reference to a list of ports, in any allowable port format
#        oids: A list of OIDs to reteive values for
#
# On sucess, returns a two-dimensional list indexed by port,oid
#
sub getFields($$$) {
    my $self = shift;
    my ($ports,$oids) = @_;


    my @ifindicies = map { portnum($_) =~ /:1\.(\d+)$/; $1 } @$ports;
    my @oids = @$oids;

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

    #
    # If we try to ask for too many things at once, we get back really bogus
    # errors. So, we limit ourselves to an arbitrary number that, by
    # experimentation, works.
    #
    my $maxvars = 16;
    my @results = ();
    while (@vars) {
	my $varList = new SNMP::VarList(splice(@vars,0,$maxvars));
	my $rv = $self->{SESS}->get($varList);
	push @results, @$varList;
    }
	    
    #
    # Build up the two-dimensional list for returning
    #
    my @return = ();
    foreach my $i (0 .. $#ifindicies) {
	foreach my $j (0 .. $#oids) {
	    my $val = shift @results;
	    $return[$i][$j] = $$val[2];
	}
    }

    return @return;
}

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
#   
# 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;
Mac Newbold's avatar
Mac Newbold committed
1220
    }
1221 1222
    if ($self->{DEBUG} >= $debuglevel) {
	print STDERR $string;
Mac Newbold's avatar
Mac Newbold committed
1223 1224 1225 1226 1227 1228
    }
}

# End with true
1;