snmpit_nortel.pm 44.3 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh Stoller's avatar
Leigh Stoller committed
2
#
3
#
4
# EMULAB-LGPL
5
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
6
# Copyright (c) 2004-2009 Regents, University of California.
7
# All rights reserved.
8

9 10 11 12 13 14 15 16 17 18 19 20 21
#
# snmpit module for Nortel level 2 switches
#

package snmpit_nortel;
use strict;

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

use English;
use SNMP;
use snmpit_lib;

22 23 24
use libtestbed;


25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#
# These are the commands that can be passed to the portControl function
# below
#
my %cmdOIDs =
(
    "enable" => ["ifAdminStatus","up"],
    "disable"=> ["ifAdminStatus","down"],
    "1000mbit"=> ["rcPortAdminSpeed","mbps1000"],
    "100mbit"=> ["rcPortAdminSpeed","mbps100"],
    "10mbit" => ["rcPortAdminSpeed","mbps10"],
    "auto"   => ["rcPortAutoNegotiate","true"],
    "full"   => ["rcPortAdminDuplex","full"],
    "half"   => ["rcPortAdminDuplex","half"],
);

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

#
# Creates a new object.
#
# usage: new($classname,$devicename,$debuglevel,$community)
#        returns a new object, blessed into the snmpit_intel class.
#
sub new($$$;$) {

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

    my $name = shift;
    my $debugLevel = shift;
    my $community = shift;

    #
    # Create the actual object
    #
    my $self = {};

    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
	$self->{DEBUG} = $debugLevel;
    } else {
	$self->{DEBUG} = 0;
    }
    $self->{BLOCK} = 1;
86
    $self->{CONFIRM} = 1;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    $self->{NAME} = $name;

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

    #
    # set up hashes for pending vlans
    #
    $self->{IFINDEX} = {};
    $self->{PORTINDEX} = {};

    # other global variables
    $self->{DOALLPORTS} = 1;
    $self->{DOALLPORTS} = 0;
116
    $self->{SKIPIGMP} = 1;
117 118

    if ($self->{DEBUG}) {
119 120
	print "snmpit_nortel initializing $self->{NAME}, " .
	    "debug level $self->{DEBUG}\n" ;   
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    }


    #
    # Set up SNMP module variables, and connect to the device
    #
    $SNMP::debugging = ($self->{DEBUG} - 2) if $self->{DEBUG} > 2;
    my $mibpath = '/usr/local/share/snmp/mibs';
    &SNMP::addMibDirs($mibpath);
    &SNMP::addMibFiles("$mibpath/SNMPv2-SMI.txt", "$mibpath/SNMPv2-TC.txt", 
	               "$mibpath/SNMPv2-MIB.txt", "$mibpath/IANAifType-MIB.txt",
		       "$mibpath/IF-MIB.txt",
		       "$mibpath/RAPID-CITY.txt");
    $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});

140 141
    $self->{SESS} = new SNMP::Session(DestHost => $self->{NAME},Version => "2c",
	Timeout => 4000000, Retries=> 12, Community => $self->{COMMUNITY});
142 143 144 145 146 147 148 149

    if (!$self->{SESS}) {
	#
	# Bomb out if the session could not be established
	#
	warn "WARNING: Unable to connect via SNMP to $self->{NAME}\n";
	return undef;
    }
150 151 152 153 154 155
    #
    # The bless needs to occur before readifIndex(), since it's a class 
    # method
    #
    bless($self,$class);

156 157 158 159
    #
    # Sometimes the SNMP session gets created when there is no connectivity
    # to the device so let's try something simple
    #
160
    my $test_case = $self->get1("sysDescr", 0);
161 162 163 164 165
    if (!defined($test_case)) {
	warn "WARNING: Unable to retrieve via SNMP from $self->{NAME}\n";
	return undef;

    }
166
    $self->{DESCR} = $test_case;
167 168 169 170 171 172

    $self->readifIndex();

    return $self;
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
# Attempt to repeat an action until it succeeds

sub hammer($$$;$) {
    my ($self, $closure, $id, $retries) = @_;

    if (!defined($retries)) { $retries = 12; }
    for my $i (1 .. $retries) {
	my $result = $closure->();
	if (defined($result) || ($retries == 1)) { return $result; }
	warn $id . " ... will try again\n";
	sleep 1;
    }
    warn  $id . " .. giving up\n";
    return undef;
}

# shorthand

sub get1($$$) {
    my ($self, $obj, $instance) = @_;
193
    my $id = $self->{NAME} . ":get1 $obj.$instance";
194 195 196 197 198 199 200 201 202 203 204 205
    my $closure = sub () {
	my $RetVal = snmpitGet($self->{SESS}, [$obj, $instance], 1);
	if (!defined($RetVal)) { sleep 4;}
	return $RetVal;
    };
    my $RetVal = $self->hammer($closure, $id, 40);
    if (!defined($RetVal)) {
	warn "$id failed - $snmpit_lib::snmpitErrorString\n";
    }
    return $RetVal;
}

206 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
# Translate a list of ifIndexes to a PortSet

sub listToPortSet($@)
{
    my $self = shift;
    my @ports = @_;

    my ($max, $portbitstring, $portSet, $port);
    my @portbits;

    $self->debug("listToPortsSet: input @ports\n",2);
    if (scalar @ports) {
	@ports = sort { $b <=> $a} @ports;
	$max = ($ports[0] | 7);
    } else { $max = 7 ; }
    $port = 0;
    while ($port <= $max) { $portbits[$port] = 48 ; $port++; }
    while (scalar @ports) { $port = pop @ports; $portbits[$port] = 49; }
    $self->debug("portbits after insertions: @portbits\n",2);
    $portbitstring = pack "C*", @portbits;
    $self->debug("listToPortSet output string $portbitstring \n");
    $portSet = pack "B*", $portbitstring ;
    return $portSet;
}
# Translate a PortSet to a list of ifIndexes

sub portSetToList($$)
{
    my $self = shift;
    my $portset = shift;

    my ($max, $portbitstring, $portSet, $port);
    my @portbits;
    my @ports = ();

    $portbitstring = unpack "B*", $portset;
    @portbits = unpack "C*", $portbitstring;

    $max = scalar @portbits;
    $port = 0;
    while ($port < $max) {

	if ($portbits[$port] == 49) {
	    push @ports, $port;
	}
	$port++;
    }
    return @ports;
}

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
# Compare two PortSets for equality ignoring trailing zeroes, etc.

sub portSetDiffers($$$)
{
    my $self = shift;
    my $setA = shift;
    my $setB = shift;

    my @listA = $self->portSetToList($setA);
    my @listB = $self->portSetToList($setB);

    while (@listA) {
	my $itemA = pop @listA;
	my $itemB;
	if (@listB) { $itemB = pop @listB; } else { return 1;}
	if ($itemA != $itemB) {return 1;}
    }
    if (@listB) {return 1;} else {return 0;}
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
#
# 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).
    # Some commands involve multiple SNMP commands, so we need to make sure
    # we get all of them
    #
    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;
    } else {
	#
	# Command not supported
	#
	print STDERR "Unsupported port control command '$cmd' ignored.\n";
313
	return -1;
314 315 316 317 318 319 320 321 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 357 358 359 360 361 362
    }
}

#
# 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];
    if (!defined($sample)) {
	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; };
	(/^$self->{NAME}\.\d+\/\d+$/) && do { $input = $PORT_FORMAT_MODPORT;
		@ports = map {/^$self->{NAME}\.(\d+)\/(\d+)$/; "$1.$2";} @ports; last; };
	$input = $PORT_FORMAT_NODEPORT; last;
    }

    #
    # It's possible the ports are already in the right format
    #
    if ($input == $output) {
363
	$self->debug("Not converting, input format = output format\n",3);
364 365 366 367 368
	return @ports;
    }

    if ($input == $PORT_FORMAT_IFINDEX) {
	if ($output == $PORT_FORMAT_MODPORT) {
369
	    $self->debug("Converting ifindex to modport\n",3);
370 371
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
372
	    $self->debug("Converting ifindex to nodeport\n",3);
373 374 375 376
	    return map portnum($self->{NAME}.":".$self->{IFINDEX}{$_}), @ports;
	}
    } elsif ($input == $PORT_FORMAT_MODPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
377
	    $self->debug("Converting modport to ifindex\n",3);
378 379
	    return map $self->{IFINDEX}{$_}, @ports;
	} elsif ($output == $PORT_FORMAT_NODEPORT) {
380
	    $self->debug("Converting modport to nodeport\n",3);
381 382 383 384
	    return map portnum($self->{NAME} . ":$_"), @ports;
	}
    } elsif ($input == $PORT_FORMAT_NODEPORT) {
	if ($output == $PORT_FORMAT_IFINDEX) {
385
	    $self->debug("Converting nodeport to ifindex\n",3);
386 387
	    return map $self->{IFINDEX}{(split /:/,portnum($_))[1]}, @ports;
	} elsif ($output == $PORT_FORMAT_MODPORT) {
388
	    $self->debug("Converting nodeport to modport\n",3);
389 390 391 392 393 394 395 396 397 398 399
	    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;

}
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
# 
# Check to see if the given 802.1Q VLAN tag exists on the switch
#
# usage: vlanNumberExists($self, $vlan_number)
#        returns 1 if the VLAN exists, 0 otherwise
#
sub vlanNumberExists($$) {
    my ($self, $vlan_number) = @_;

    my $rv = $self->get1("rcVlanId", $vlan_number);
    if (!defined($rv) || !$rv || $rv eq "NOSUCHINSTANCE") {
	return 0;
    }
    return 1;
}
415 416 417 418 419 420 421 422 423 424 425 426 427 428

#
# Given VLAN indentifiers from the database, finds the 802.1Q 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 802.1Q VLAN numbers
#        any VLANs not found have NULL VLAN numbers
#
sub findVlans($@) { 
    my $self = shift;
    my @vlan_ids = @_;
    my %mapping = ();
429 430
    my $id = $self->{NAME} . "::findVlans";
    my ($count, $name, $vlan_number, $vlan_name) = (scalar(@vlan_ids));
431

432 433
    if ($count > 0) { @mapping{@vlan_ids} = undef; }

434
    #
435
    # Find all VLAN names. Do one to get the first field...
436
    #
437 438 439 440 441 442 443 444 445 446 447
    my ($rows) = $self->{SESS}->bulkwalk(0,32, ["rcVlanName"]);
    foreach my $rowref (@$rows) {
	($name,$vlan_number,$vlan_name) = @$rowref;
	$self->debug("$id: Got $name $vlan_number $vlan_name\n");
	#
	# We only want the names - we ignore everything else
	#
	    if (!@vlan_ids || exists $mapping{$vlan_name}) {
		$self->debug("$id: $vlan_name=>$vlan_number\n",2);
		$mapping{$vlan_name} = $vlan_number;
	    }
448
    }
449

450
    return %mapping;
451 452 453 454 455 456 457 458 459 460 461 462
}

#
# Given a VLAN identifier from the database, find the 802.1Q VLAN
# number that is assigned to that VLAN. Retries several times (to account
# for propagation delays) unless the $no_retry option is given.
#
# usage: findVlan($self, $vlan_id,$no_retry)
#        returns the VLAN number for the given vlan_id if it exists
#        returns undef if the VLAN id is not found
#
sub findVlan($$;$) { 
463 464 465 466
    my $self = shift;
    my $vlan_id = shift;
    my $no_retry = shift;
    my $id = $self->{NAME} . ":findVlan";
467

468 469
    $self->debug("$id ( $vlan_id )\n",2);
    my $max_tries = $no_retry ? 1 : 5;
470
    #
471 472
    # We try this a few times, with 5 second sleeps, since it can take
    # a while for VLAN information to propagate
473
    #
474 475 476 477 478 479 480 481
    my $closure = sub () {
	my %mapping = $self->findVlans($vlan_id);
	my $vlan_number = $mapping{$vlan_id};
	if (defined($vlan_number)) { return $vlan_number; }
	sleep 4;
	return undef;
    };
    return $self->hammer($closure,$id,$max_tries);
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
}

#   
# Create a VLAN on this switch, with the given identifier (which comes from
# the database) and given 802.1Q tag number.
#
# usage: createVlan($self, $vlan_id, $vlan_number)
#        returns the new VLAN number on success
#        returns 0 on failure
#
# Creation of a vlan under the RAPID-CITY MIB only seems to require
# the type (vlanbyport), and a spanning tree group, (all vlans
# can share the same universal STG), but it's convenient to also
# name it at this point.  We'll try to add ports later.
# we have to supply all parameters in the same SNMP packet, however.
#
sub createVlan($$$) {
499 500 501
    my $self = shift;
    my $vlan_id = shift;
    my $vlan_number = shift;
502
    my $id = $self->{NAME} . ":createVlan";
503

504 505 506 507 508 509 510 511 512 513 514 515 516
    if (!defined($vlan_number)) {
	warn "$id called without supplying vlan_number";
	return 0;
    }
    my $check_number = $self->findVlan($vlan_id,1);
    if (defined($check_number)) {
	if ($check_number != $vlan_number) {
		warn "$id: recreating vlan id $vlan_id which has ".
		     "existing vlan number $check_number with the new number ".
		     "$vlan_number\n";
		     return 0;
	}
     }
517
    my $vlan ="$vlan_number";
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 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    my $VlanRowStatus = 'rcVlanRowStatus'; # vlan # is index
    my $VlanName = 'rcVlanName'; # vlan # is index
    my $VlanType = 'rcVlanType'; # vlan # is index
    my $VlanStg = 'rcVlanStgId'; # vlan # is index
    $self->debug("createVlan: name $vlan_id number $vlan_number \n");
    #
    # Perform the actual creation. Yes, this next line MUST happen all in
    # one set command....
    #
    my $closure = sub () {
    	my $RetVal = $self->{SESS}->set(
	    [[$VlanRowStatus,$vlan, "createAndGo","INTEGER"],
	     [$VlanType,$vlan,"byPort","INTEGER"],
	     [$VlanStg,$vlan,1,"INTEGER"],
	     [$VlanName,$vlan,$vlan_id,"OCTETSTR"]]);
	if (defined($RetVal)) { return $RetVal; }
	#
	# Sometimes we loose responses, or on the second time around
	# it might refuse to create a vlan that's already there, so wait
	# a bit to see if it exists (also so as to not get too
	# agressive with the switch which can cause to crash with
	# certain sets, e.g. IGMP stuff)
	#
	sleep (9);
	$RetVal = $self->get1($VlanRowStatus, $vlan);
	if (defined($RetVal) && ($RetVal ne "active")) { return undef ;}
	return $RetVal;
    };
    my $RetVal = $self->hammer($closure, "$id: creation");
    if (!defined($RetVal)) { return 0; }
    print "  Creating VLAN $vlan_id as VLAN #$vlan_number on " .
	    "$self->{NAME} ... ";


    # You'ld think you'ld be able to add IgmpSnoopEnable to the above as one
    # more item, but that caused it to fail, even though it wins as a separate
    # packet.

    # There also something in the IGMP magic that causes the switch
    # to get totally confused, so we're going to throw in some superfluous
    # queries just to make sure things happened and slow down our interactions.

    $RetVal = $self->findVlan($vlan_id);
    if (!defined($RetVal) || ("$RetVal" ne $vlan)) {
	warn "$id: created vlan $vlan_id with number $RetVal" .
	  "instead of $vlan_number\n";
564
    }
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    if ($self->{SKIPIGMP}) { return $vlan_number ; }
    my $IgmpEnable = 'rcVlanIgmpSnoopEnable';
    $RetVal = $self->get1($IgmpEnable, $vlan);

    $closure = sub () {
	my $check = $self->{SESS}->set([[$IgmpEnable,$vlan,"true","INTEGER"]]);
	if (!defined($check) || ($check ne "true")) { sleep (19); return undef;}
	return $check;
    };
    $RetVal = $self->hammer($closure, "$id: setting snooping");
    if (!defined($RetVal)) { return 0; }

    $closure = sub () {
	my $check = $self->get1($IgmpEnable, $vlan);
	if (!defined($check) || ($check ne "true")) { sleep (4); return undef ;}
	return $check;
    };
    $RetVal = $self->hammer($closure, "$id: checking snooping");
    if (!defined($RetVal)) { return 0; }
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

    return $vlan_number;
}

sub snmpSetCheckPortSet($$$$)
{
    my ($self, $obj, $vlan_number, $SetVal) = @_;
    my $id = $self->{NAME} . "::SetCheckPortSet";
    my $set_arg = [$obj,$vlan_number,$SetVal,"OCTETSTR"];
    my $counter = 0;
    my ($inner_closure, $outer_closure, $final_check);

    $inner_closure = sub () {
	my $ctr_p =\$counter;
	$$ctr_p++;
	my $check = $self->get1($obj, $vlan_number);
	if (!defined($check)) { sleep 2; return undef; }
	if ($self->portSetDiffers($check, $SetVal)) {
	    if ($$ctr_p == 8) {
		my @oldIgmpList = $self->portSetToList($SetVal);
		my @newIgmpList = $self->portSetToList($check);
		print "SetCheckPortSet result for vlan # $vlan_number " 
		. "differs from what was set -  old is @oldIgmpList\n " 
		. "new is @newIgmpList \n";
	    }
	    return undef;
	}
	return $check;
    };
    $outer_closure = sub () {
	my $ctr_p = \$counter;
	$$ctr_p = 0;
	my $RetVal = $self->{SESS}->set($set_arg);
	if (!defined($RetVal)) {
	    my $reason = "";
	    if (defined($snmpit_lib::snmpitErrorString)) {
		    $reason = $snmpit_lib::snmpitErrorString;
	    };
	    warn "$id: SetCheckPortSet set $obj may have failed: $reason\n";
	    sleep 4;
	}
	return $self->hammer($inner_closure, $id, 8);
    };
    $final_check = $self->hammer($outer_closure, $id, 4);
    if (defined($final_check)) { return 0; }
    return 1;
631 632 633 634 635 636 637 638 639 640 641 642 643
}

#
# Put the given ports in the given VLAN. The VLAN is given as an 802.1Q 
# tag number.
#
# usage: setPortVlan($self, $vlan_number, @ports)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
# nortel specific: if the vlan_number < 0 *remove* the ports from the vlan
#
sub setPortVlan($$@) {
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
    my $self = shift;
    my $vlan_number = shift;
    my @ports = @_;

    my $errors = 0;
    my $obj = "rcVlanPortMembers";
    my $id = $self->{NAME} . "::setPortVlan";
    $self->debug("$id: $vlan_number ");
	   
    #
    # Run the port list through portmap to find the ports on the switch that
    # we are concerned with
    #

    my @portlist = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
    $self->debug("ports: " . join(",",@ports) . "\n");
    $self->debug("as ifIndexes: " . join(",",@portlist) . "\n");

    #
    # We need to remove any normal ports from other vlans to which
    # they may belong; the nortels don't automatically do this, unlike
    # foundry's and cisco's.
    #
    my (%vlansToPorts, $porttype, $vlans, $portIndex);
    my (@vlanList, $vlan, @memberlist);
    %vlansToPorts = ();
    foreach $portIndex (@portlist) {
	$porttype = $self->get1("rcVlanPortType", $portIndex);
	if (defined($porttype)) {
	    $self->debug("ifIndex $portIndex has type $porttype");
	    if ($porttype eq "access") {
		$vlans = $self->get1("rcVlanPortVlanIds", $portIndex);
		if (defined($vlans)) {
		    @vlanList = unpack "n*", $vlans;
		    $self->debug(" and is in vlans @vlanList");
		    foreach $vlan (@vlanList) {
			if ($vlan != $vlan_number) {
			    if (!defined($vlansToPorts{$vlan})) {
				$vlansToPorts{$vlan} = [];
			    }
			    push @{$vlansToPorts{$vlan}}, $portIndex;
685 686 687 688 689
			}
		    }
		}
	    }
	}
690 691 692 693 694 695 696 697
	$self->debug("\n");
    }
    my @bumpedlist = keys %vlansToPorts;
    foreach $vlan (@bumpedlist) {
	$self->delPortVlan($vlan, @{$vlansToPorts{$vlan}});
    }
    if (@bumpedlist = grep {$_ != 1;} @bumpedlist) {
	@{$self->{DISPLACED_VLANS}} = @bumpedlist;
698 699
    }

700 701 702 703 704
    my $portSet = $self->get1($obj, $vlan_number);
    if (!$portSet) {
	printf STDERR "$id: Could not get current list for VLAN $vlan_number\n";
	return 1;
    }
705
    $self->lock();
706 707 708 709 710 711
    my @newlist;
    my @oldlist = $self->portSetToList($portSet);
    push @oldlist, @portlist;
    my $SetVal = $self->listToPortSet(@oldlist);
    $self->debug("$id: members of VLAN $vlan_number [ @oldlist ]\n");

712 713 714
    $errors = $self->snmpSetCheckPortSet($obj, $vlan_number, $SetVal);
    $self->unlock();
    if ($errors) {
715 716 717 718 719
	return 1;
    }
    #
    # We need to make sure the ports get enabled.
    #
720

721 722 723 724 725
    $self->debug("Enabling "  . join(',',@ports) . "...\n");
    if ( my $rv = $self->portControl("enable",@ports) ) {
	print STDERR "Port enable had $rv failures.\n";
	$errors += $rv;
    }
726

727
    if ($self->{SKIPIGMP}) { return $errors; }
728

729
    $self->lock();
730 731
    my $igmp = "rcVlanIgmpVer1SnoopMRouterPorts";
    my $IgnoredVal = $self->{SESS}->get("$igmp.$vlan_number");
732
    $errors += $self->snmpSetCheckPortSet($igmp, $vlan_number, $SetVal);
733
    $self->unlock();
734

735
    return $errors;
736 737 738
}

sub not_in($$@) {
739 740 741
    my $self = shift;
    my $value = shift;
    my @list = @_;
742

743
    return 0 == scalar(grep {$_ == $value;} @list);
744 745 746 747 748 749 750 751 752 753 754
}

#
# Remove the given ports from the given VLAN. The VLAN is given as an 802.1Q 
# tag number.
#
# usage: delPortVlan($self, $vlan_number, @ports)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub delPortVlan($$@) {
755 756 757
    my $self = shift;
    my $vlan_number = shift;
    my @ports = @_;
758

759 760 761 762 763 764 765
    my $obj = "rcVlanPortMembers";
    $self->debug($self->{NAME} . "::delPortVlan $vlan_number ");
	   
    #
    # Run the port list through portmap to find the ports on the switch that
    # we are concerned with
    #
766

767 768 769
    my @portlist = $self->convertPortFormat($PORT_FORMAT_IFINDEX, @ports);
    $self->debug("ports: " . join(",",@ports) . "\n");
    $self->debug("as ifIndexes: " . join(",",@portlist) . "\n");
770

771
    $self->lock();
772
    my $portSet = $self->{SESS}->get("$obj.$vlan_number");
773

774 775
    if (!$portSet) {
	printf STDERR "Could not get current list for VLAN $vlan_number\n";
776
	$self->unlock();
777 778 779
	return 1;
    }
    my @oldlist = $self->portSetToList($portSet);
780

781 782 783 784
    $self->debug("oldlist of VLAN $vlan_number [ @oldlist ]\n");
    $self->debug("portlist to drop is [ @portlist ]\n");
    @oldlist =  grep {$self->not_in($_, @portlist);} @oldlist;
    $self->debug("after set diff oldlist is [ @oldlist ]\n");
785

786
    my $SetVal = $self->listToPortSet(@oldlist);
787

788 789 790
    my $result = $self->snmpSetCheckPortSet($obj, $vlan_number, $SetVal);
    $self->unlock();
    return $result;
791 792 793 794
}


#
795
# Disables all ports in the given VLANS. Each VLAN is given as a VLAN
796 797 798 799 800 801 802
# 802.1Q tag value.
#
# usage: removePortsFromVlan(self,@vlan)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub removePortsFromVlan($@) {
803 804 805 806
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
    my $id = $self->{NAME} . "::removePortsFromVlan";
807

808
    my ($name,$index,$value,$modport,$portIndex,$portString);
809
    foreach my $vlan_number (@vlan_numbers) {
810 811 812
	#
	# Do one to get the first field...
	#
813
	$self->debug("$id: number $vlan_number\n");
814 815
	my $field = ["rcVlanPortMembers",$vlan_number,"OCTETSTRING"];
	$value = $self->{SESS}->get($field);
816 817
	if (!$value) {
		print STDERR "No port member list for VLAN $vlan_number\n";
818
		return 1;
819 820
	}
	my @portlist = $self->portSetToList($value);
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
	$self->debug("removePortsFromVlan $vlan_number: @portlist\n");
	foreach $portIndex (@portlist) {
	    #
	    # disable this port, unless it is tagged.
	    #
	    $value= $self->{SESS}->get(["rcVlanPortType",$portIndex]);
	    if (defined($value) && ($value eq "access")) {
		$self->debug("disabling port $portIndex  "
				. "from vlan $vlan_number ( $value )\n" );
		$value = $self->{SESS}->set
		(["ifAdminStatus",$portIndex,"down","INTEGER"]);
		$value = $self->{SESS}->get
		(["ifAdminStatus",$portIndex]);
	    }
	}
836
    }
837
    return $errors;
838 839
}

840 841 842 843 844 845 846 847 848 849
#
# Removes and disables some ports in a given VLAN. The VLAN is given as a VLAN
# 802.1Q tag value.  Ports are known to be regular ports and not trunked.
#
# usage: removeSomePortsFromVlan(self,vlan,@ports)
#	 returns 0 on sucess.
#	 returns the number of failed ports on failure.
#
sub removeSomePortsFromVlan($$@) {
    my ($self, $vlan_number, @ports) = @_;
850
    my ($errors, $id, %hports) = (0,$self->{NAME}."::removeSomePortsFromVlan");
851 852
    @ports = $self->convertPortFormat($PORT_FORMAT_IFINDEX,@ports);

853 854 855 856 857
    my $value = $self->get1("rcVlanPortMembers",$vlan_number);
    return 1 if (!$value);

    @hports{@ports} = @ports;
    @ports = grep { $hports{$_};} $self->portSetToList($value);
858
    $errors += $self->delPortVlan($vlan_number,@ports);
859 860
    $errors += $self->portControl("disable",@ports);

861 862 863
    return $errors;
}

864 865 866 867 868 869 870 871 872 873 874
#
# Remove the given VLANs from this switch. Removes all ports from the VLAN,
# so it's not necessary to call removePortsFromVlan() first. The VLAN is
# given as a VLAN identifier from the database.
#
# usage: removeVlan(self,int vlan)
#	 returns 1 on success
#	 returns 0 on failure
#
#
sub removeVlan($@) {
875 876 877 878 879
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
    my $DeleteOID = "rcVlanRowStatus";
    my $name = $self->{NAME};
880 881


882

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    foreach my $vlan_number (@vlan_numbers) {
	#
	# Perform the actual removal
	#
	my $RetVal = undef;
	print "  Removing VLAN # $vlan_number ... ";
	$RetVal = $self->{SESS}->set([[$DeleteOID,$vlan_number,"destroy","INTEGER"]]);
	if ($RetVal) {
	    print "Removed VLAN $vlan_number on switch $name.\n";
	} else {
	    print STDERR "Removing VLAN $vlan_number failed on switch $name.\n";
	}
	# The next call is to buy time to let switch consolidate itself
	# we've seen bizarre failures when quickly creating and destroying
	# vlans with IGMP snooping enabled.

	$RetVal = $self->{SESS}->get([$DeleteOID,$vlan_number]);
	my ($rows) = $self->{SESS}->bulkwalk(0,32, ["rcVlanName"]);
901
    }
902
    return ($errors == 0) ? 1 : 0;
903 904 905 906 907 908
}

#
# XXX: Major cleanup
#
sub UpdateField($$$@) {
909 910
    my $self = shift;
    my ($OID,$val,@ports)= @_;
911
    my $id = $self->{NAME} . "::UpdateField";
912

913
    $self->debug("$id: OID $OID value $val ports @ports\n");
914

915 916 917 918 919
    my $Status = 0;
    my $result = 0;
    my ($portname, $module, $port, $row, $modport);


920
    foreach my $portname (@ports) {
921
	my ($row) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,$portname);
922 923
	$self->debug("checking row $row for $val ...\n");
	$Status = $self->{SESS}->get([$OID,$row]);
924
	if (!defined $Status) {
925 926
	    print STDERR "Port $portname, change to $val: No answer from device\n";
	    $result = -1;
927 928 929
	} else {
	    $self->debug("Port $portname, row $row was $Status\n");
	    if ($Status ne $val) {
930 931 932 933 934 935 936
		$self->debug("Setting $portname (r $row) to $val...");
		$self->{SESS}->set([[$OID,$row,$val,"INTEGER"]]);
		my $count = 6;
		while (($Status ne $val) && (--$count > 0)) { 
		    sleep 1;
		    $Status = $self->{SESS}->get([$OID,$row]);
		    $self->debug("Value for $portname is currently $Status\n");
937
		}
938 939
		$result =  ($count > 0) ? 0 : -1;
		$self->debug($result ? "failed.\n" : "succeeded.\n");
940 941
	    }
	}
942

943 944
    }
    return $result;
945
}
946 947 948 949 950 951 952 953 954 955 956 957 958 959

#
# Determine if a VLAN has any members 
# (Used by stack->switchesWithPortsInVlan())
#
sub vlanHasPorts($$) {
    my ($self, $vlan_number) = @_;

    my $portset = $self->get1("rcVlanPortMembers",$vlan_number);
    if (defined($portset)) {
	my @ports = $self->portSetToList($portset);
	if (@ports) { return 1; }
    }
    return 0;
960 961 962 963 964 965 966 967 968
}

#
# List all VLANs on the device
#
# usage: listVlans($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
sub listVlans($) {
969
    my $self = shift;
970

971 972 973 974 975 976
    my %Names = ();
    my %Numbers = ();
    my %Members = ();
    my ($vlan_name, $oid, $vlan_number, $value, $rowref);
    my ($modport, $node, $ifIndex, @portlist, @memberlist);
    $self->debug($self->{NAME} . ":listVlans()\n",3);
977

978 979 980 981 982 983 984 985 986 987 988
    #
    # Walk the tree to find the VLAN names
    #
    my ($rows) = $self->{SESS}->bulkwalk(0,32,"rcVlanName");
    foreach $rowref (@$rows) {
	($oid, $vlan_number, $vlan_name) = @$rowref;
	$self->debug("Got $oid $vlan_number $vlan_name\n",3);
	if (!$Names{$vlan_number}) {
	    $Names{$vlan_number} = $vlan_name;
	    @{$Members{$vlan_number}} = ();
	}
989
    }
990 991 992 993 994 995 996 997 998 999 1000 1001 1002

    #
    #  Walk the tree for the VLAN members
    #
    ($rows) = $self->{SESS}->bulkwalk(0,32,"rcVlanPortMembers");
    foreach $rowref (@$rows) {
	($oid,$vlan_number,$value) = @$rowref;
	@portlist = $self->portSetToList($value);
	$self->debug("Got $oid $vlan_number @portlist\n",3);

	foreach $ifIndex (@portlist) {
	    ($node) = $self->convertPortFormat($PORT_FORMAT_NODEPORT,$ifIndex);
	    if (!$node) {
1003
		($modport) = $self->convertPortFormat
1004
			($PORT_FORMAT_MODPORT,$ifIndex);
1005 1006
		$modport =~ s/\./\//;
		$node = $self->{NAME} . ".$modport";
1007 1008 1009
	    }
	    push @{$Members{$vlan_number}}, $node;
	    if (!$Names{$vlan_number}) {
1010
		$self->debug("listVlans: WARNING: port $node in non-existant " .
1011
		    "VLAN $vlan_number\n");
1012
	    }
1013
	}
1014
    }
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024
    #
    # Build a list from the name and membership lists
    #
    my @list = ();
    foreach my $vlan_id (sort keys %Names) {
	if ($vlan_id !=  1) {
	    push @list, [$Names{$vlan_id},$vlan_id,$Members{$vlan_id}];
	}
    }
1025

1026 1027
    #$self->debug($self->{NAME} .":". join("\n",(map {join ",", @$_} @list))."\n");
    return @list;
1028 1029 1030 1031 1032 1033 1034 1035 1036
}

#
# List all ports on the device
#
# usage: listPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
sub listPorts($) {
1037
    my $self = shift;
1038

1039 1040
    my %Able = ();
    my %Link = ();
1041
    my %auto = ();
1042 1043
    my %speed = ();
    my %duplex = ();
1044

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

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    #
    # Get the ifAdminStatus (enabled/disabled) and ifOperStatus
    # (up/down)
    #
    my ($varname, $modport, $ifIndex, $portIndex, $status, $portname);
    $self->{SESS}->getnext($ifTable);
    do {
	($varname,$ifIndex,$status) = @{$ifTable};
	$self->debug("$varname $ifIndex $status\n");
	if ($varname =~ /AdminStatus/) { 
	    $Able{$ifIndex} = ($status =~/up/ ? "yes" : "no");
	}
	$self->{SESS}->getnext($ifTable);
    } while ( $varname =~ /^ifAdminStatus$/) ;

    #
    # Get the port configuration, including speed, duplex, and whether or not
    # it is autoconfiguring
    #
    foreach $ifIndex (keys %Able) {
	$portIndex = $self->{PORTINDEX}{$ifIndex};
	if ($status = $self->{SESS}->get(["ifOperStatus",$ifIndex])) {
	    $Link{$ifIndex} = $status;
	}
	if ($status = $self->{SESS}->get(["rcPortOperDuplex",$ifIndex])) {
	    $duplex{$ifIndex} = $status;
	}
	if ($status = $self->{SESS}->get(["rcPortOperSpeed",$ifIndex])) {
	    $speed{$ifIndex} = $status;
	}
    };
1078 1079

    #
1080 1081
    # Put all of the data gathered in the loop into a list suitable for
    # returning
1082
    #
1083 1084
    my @rv = ();
    foreach my $id ( keys %Able ) {
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
	$modport = $self->{IFINDEX}{$id};
	$portname = $self->{NAME} . ":$modport";
	my $port = portnum($portname);

	#
	# Skip ports that don't seem to have anything interesting attached
	#
	if (!$port && $self->{DOALLPORTS}) {
#		$port = $portname;
		$port = "n:$modport";
	}
	if (!$port) {
	    $self->debug("$id ($modport) not connected, skipping\n");
	    next;
	}
1100 1101
	if (! defined ($speed{$id}) ) { $speed{$id} = " "; }
	if (! defined ($duplex{$id}) ) { $duplex{$id} = " "; }
1102
	push @rv, [$port,$Able{$id},$Link{$id},$speed{$id},$duplex{$id}];
1103
    }
1104
    return @rv;
1105 1106 1107 1108 1109
}

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

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 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    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=();
    my ($varname, $port, $value);

    #
    # Walk the whole stats tree, and fill these ha
    #
    $self->{SESS}->getnext($ifTable);
    do {
	($varname,$port,$value) = @{$ifTable};
	$self->debug("getStats: Got $varname, $port, $value\n");
	    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)/) ;
1166 1167

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

1175 1176 1177 1178 1179 1180
	#
	# 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;
1181
	}
1182 1183 1184 1185 1186
	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}];

1187
    }
1188
    return @rv;
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

}

#
# Used to flush FDB entries easily
#
# usage: resetVlanIfOnTrunk(self, modport, vlan)
#
sub resetVlanIfOnTrunk($$$) {
    my ($self, $modport, $vlan) = @_;
    my ($ifIndex) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,$modport);
1200
    $self->debug($self->{NAME} . "::resetVlanIfOnTrunk m $modport "
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
		    . "vlan $vlan ifIndex $ifIndex\n",1);
    my $vlans = $self->get1("rcVlanPortVlanIds", $ifIndex);
    if (defined($vlans)) {
	my @vlanList = unpack "n*", $vlans;
	if (grep {$_ == $vlan;} @vlanList) {
	    $self->setVlansOnTrunk($modport,0,$vlan);
	    $self->setVlansOnTrunk($modport,1,$vlan);
	}
    }
    return 0;
}
1212 1213

#
1214 1215 1216 1217 1218 1219 1220
# Get the ifindex for an EtherChannel (trunk given as a list of ports)
#
# usage: getChannelIfIndex(self, ports)
#        Returns: undef if more than one port is given, and no channel is found
#           an ifindex if a channel is found and/or only one port is given
#
# N.B. by Sklower - cisco's use this and so it gets called from _stack.pm
1221
#
1222 1223 1224 1225 1226
sub getChannelIfIndex($@) {
    my $self = shift;
    my @ports = @_;
    my @ifIndexes = $self->convertPortFormat($PORT_FORMAT_IFINDEX,@ports);
    my $ifindex = undef;
1227 1228

    #
1229 1230
    # Try to get a channel number for each one of the ports in turn - we'll
    # take the first one we get
1231
    #
1232 1233
    foreach my $port (@ifIndexes) {
        if ($port) { $ifindex = $port; last; }
1234
    }
1235
    return $ifindex;
1236
}
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248


#
# Enable, or disable,  port on a trunk
#
# usage: setVlansOnTrunk(self, modport, value, vlan_numbers)
#        modport: module.port of the trunk to operate on
#        value: 0 to disallow the VLAN on the trunk, 1 to allow it
#	 vlan_numbers: An array of 802.1Q VLAN numbers to operate on
#        Returns 1 on success, 0 otherwise
#
sub setVlansOnTrunk($$$$) {
1249 1250 1251 1252
    my ($self, $modport, $value, @vlan_numbers) = @_;
    my ($portindex,$RetVal);
    my $errors = 0;
    my $id = $self->{NAME} . "::setVlansOnTrunk";
1253

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    #
    # Some error checking
    #
    if (($value != 1) && ($value != 0)) {
	die "Invalid value $value passed to setVlansOnTrunk\n";
    }
    if (grep(/^1$/,@vlan_numbers)) {
	die "VLAN 1 passed to setVlansOnTrunk\n";
    }
    $self->debug("$id: m $modport v $value nums @vlan_numbers\n");
    my ($ifIndex) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,$modport);
    $portindex = $self->{PORTINDEX}{$ifIndex};
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275
    #
    # Make sure ostensible trunk is either trunk or dual mode
    #
    $RetVal = $self->get1("rcVlanPortType",$portindex);
    if (defined($RetVal) && ($RetVal eq "access")) {
	warn "$id: port $modport is normal port, " .
		"refusing to add vlan(s) @vlan_numbers\n";
	return 0;
    }
1276

1277 1278 1279 1280 1281 1282 1283
    foreach my $vlan_number (@vlan_numbers) {
	$RetVal = ($value == 1) ? $self->setPortVlan($vlan_number,$modport) :
				    $self->delPortVlan($vlan_number,$modport);
	if ($RetVal) {
	    $errors++;
	    warn "$id:couldn't add/remove port $modport on vlan $vlan_number\n";
	}
1284
    }
1285
    return !$errors;
1286 1287 1288 1289 1290 1291 1292 1293 1294
}
#
# Clear the list of allowed VLANs from a trunk
#
# usage: clearAllVlansOnTrunk(self, modport)
#        modport: module.port of the trunk to operate on
#        Returns 1 on success, 0 otherwise
#
sub clearAllVlansOnTrunk($$) {
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    my ($self, $modport) = @_;
    my ($portIndex) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,$modport);
    my $errors = 0;

    my $vlans = $self->get1("rcVlanPortVlanIds", $portIndex);
    if (defined($vlans)) {
	my @vlaninfo = unpack "n*", $vlans;
	while (scalar @vlaninfo) {
	    my $number = pop @vlaninfo;
	    my $RetVal = $self->delPortVlan($number , $modport);
	    if (!defined($RetVal) || ! $RetVal ) {
		print STDERR "Couldn't remove $modport from VLAN $number\n";
		$errors++;
	    }
1309
	}
1310 1311
    } else  { $errors++; }
    return !$errors;
1312
}
1313 1314 1315
#
# Enable trunking on a port
#
1316
# usage: enablePortTrunking2(self, modport, nativevlan, equaltrunking)
1317 1318
#        modport: module.port of the trunk to operate on
#        nativevlan: VLAN number of the native VLAN for this trunk
1319
#	 equaltrunk: don't do dual mode; tag PVID also.
1320 1321
#        Returns 1 on success, 0 otherwise
#
1322 1323
sub enablePortTrunking2($$$$) {
    my ($self,$port,$native_vlan,$equaltrunking) = @_;
1324

1325 1326 1327
    if ($equaltrunking) {
	if (!$native_vlan) { $native_vlan = 1; }
    } elsif (!defined($native_vlan) || ($native_vlan <= 1)) {
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
	warn "Error: innappropriate or missing PVID for trunk\n";
	return 0;
    }
    my ($ifIndex) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,$port);
    my $portIndex = $self->{PORTINDEX}{$ifIndex};
    #
    # temporarily set port type to "access" and add to native_vlan
    # portSetVlan will clear out all other vlans and set the PVID
    #
    my $portType = ["rcVlanPortType",$portIndex,1,"INTEGER"];
    my $rv = $self->{SESS}->set($portType);
    if (!defined($rv)) {
	warn "enablePortTrunking: Unable to set trunk port type to access\n";
	return 0;
    }
    $rv = $self->setPortVlan($native_vlan, $port);
    if ($rv) {
	warn "ERROR: Unable to add Trunk $port to PVID $native_vlan\n";
	return 0;
    } 
    #
1349
    # Set port type apropriately.
1350
    #
1351 1352 1353
    my $portTypeOid = 5; # "untagPvidOnly"
    if ($equaltrunking) { $portTypeOid = 2; } # "tagAll"
    $portType = ["rcVlanPortType",$portIndex,$portTypeOid,"INTEGER"];
1354 1355
    $rv = $self->{SESS}->set($portType);
    if (!defined($rv)) {
1356
	warn "enablePortTrunking: Unable to set port type\n";
1357 1358
	return 0;
    }
1359
    # Next call waits for switch to stabilize before proceeding.
1360 1361
    $rv = $self->{SESS}->get("rcVlanPortType.$portIndex");
    return 1;
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
}

#
# Disable trunking on a port
#
# usage: disablePortTrunking(self, modport)
#        modport: module.port of the trunk to operate on
#        Returns 1 on success, 0 otherwise
#
sub disablePortTrunking($$) {
1372 1373
    my $self = shift;
    my ($port) = @_;
1374

1375 1376 1377
    my ($ifIndex) = $self->convertPortFormat($PORT_FORMAT_IFINDEX,$port);
    my $portIndex = $self->{PORTINDEX}{$ifIndex};
    my $native_vlan = $self->{SESS}->get("rcVlanPortDefaultVlanId.$portIndex");
1378

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    #
    # Set port type back to "access", and adding it to its native Vlan
    # will remove it from any other vlans to which it may belong
    #
    my $portType = ["rcVlanPortType",$portIndex,1,"INTEGER"];
    my $rv = $self->{SESS}->set($portType);
    if (!defined($rv)) {
	warn "ERROR: Unable to set port type to access\n";
	return 0;
    }
    $rv = $self->{SESS}->set($portType);
    if (!defined($native_vlan) || ($native_vlan == 0)) {
	$native_vlan = 1;
    }
    $rv = $self->setPortVlan($native_vlan, $port);
	
    return ($rv == 0);
1396 1397 1398 1399 1400 1401 1402 1403 1404
}

# for accellar's this function is not necessary, the port index is the ifIndex
# it might be necessary for 5510's.
#
# 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,
#
1405 1406 1407
# Unlike Foundry's, Nortel's use same indexes for private port functions
# and IETF standard ifIndex-ed mibs.
#
1408 1409 1410 1411
# usage: readifIndex(self)
#        returns nothing but sets instance variables IFINDEX and PORTINDEX
#
sub readifIndex($) {
1412 1413 1414 1415
    my $self = shift;
    my ($name,$ifindex,$iidoid);
    my ($oidbits, $oidshift) = (15, 4);
    $self->debug($self->{NAME} . "readifIndex:\n",2);
1416

1417
    if (getDeviceType($self->{NAME}) =~ /^nortel5/) {
1418 1419 1420 1421 1422 1423 1424
	$self->{DESCR} =~ /SW:v(\d+)\./;
	my $version = $1;
	if ($version && ($version > 5)) {
	    ($oidbits, $oidshift) = (127, 7);
	} else {  
	    ($oidbits, $oidshift) = (63, 6);
	}
1425 1426 1427 1428 1429
    }
    my ($rows) = snmpitBulkwalkFatal($self->{SESS}, ["rcPortIndex"]);
    foreach my $rowref (@$rows) {
	($name,$ifindex,$iidoid) = @$rowref;
	$self->debug("got $name, $ifindex, iidoid $iidoid ",3);
1430 1431 1432 1433 1434 1435 1436 1437
	my $port = $iidoid & $oidbits;
	my $mod = 1 + ($iidoid >> $oidshift);
	my $modport = "$mod.$port";
	my $portindex = $iidoid ;
	$self->{IFINDEX}{$modport} = $ifindex;
	$self->{IFINDEX}{$ifindex} = $modport;
	$self->{PORTINDEX}{$modport} = $portindex;
	$self->{PORTINDEX}{$ifindex} = $portindex;
1438
	$self->debug("mod $mod, port $port, ",2);
1439
	$self->debug("modport $modport, portindex $portindex\n",3);
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
    }
}


#
# Read a set of values for all given ports.
#
# 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($$$) {
1454 1455
    my $self = shift;
    my ($ports,$oids) = @_;
1456

1457 1458
    my @ifindicies = $self->convertPortFormat($PORT_FORMAT_IFINDEX,@$ports);
    my @oids = @$oids;
1459 1460


1461 1462 1463 1464 1465 1466 1467 1468
    #
    # 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"];
	}
1469
    }
1470

1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    #
    # 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];
	}
1493 1494
    }

1495
    return @return;
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
}

#
# 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($$;$) {
1506 1507 1508 1509 1510 1511 1512 1513 1514
    my $self = shift;
    my $string = shift;
    my $debuglevel = shift;
    if (!(defined $debuglevel)) {
	$debuglevel = 1;
    }
    if ($self->{DEBUG} >= $debuglevel) {
	print STDERR $string;
    }
1515 1516
}

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
my $lock_held = 0;

sub lock($) {
    my $self = shift;
    my $token = "snmpit_" . $self->{NAME};
    if ($lock_held == 0) {
	my $old_umask = umask(0);
	die if (TBScriptLock($token,0,1800) != TBSCRIPTLOCK_OKAY());
	umask($old_umask);
    }
    $lock_held = 1;
}

sub unlock($) {
	if ($lock_held == 1) { TBScriptUnlock();}
	$lock_held = 0;
}

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

#
# Enable Openflow
#
sub enableOpenflow($$) {
    my $self = shift;
    my $vlan = shift;
    my $RetVal;
    
    #
    # Nortel switch doesn't support Openflow yet.
    #
    warn "ERROR: Nortel swith doesn't support Openflow now";
    return 0;
}

#
# Disable Openflow
#
sub disableOpenflow($$) {
    my $self = shift;
    my $vlan = shift;
    my $RetVal;
    
    #
    # Nortel switch doesn't support Openflow yet.
    #
    warn "ERROR: Nortel swith doesn't support Openflow now";
    return 0;
}

#
# Set controller
#
sub setOpenflowController($$$) {
    my $self = shift;
    my $vlan = shift;
    my $controller = shift;
    my $RetVal;
    
    #
    # Nortel switch doesn't support Openflow yet.
    #
    warn "ERROR: Nortel swith doesn't support Openflow now";
    return 0;
}

#
# Set listener
#
sub setOpenflowListener($$$) {
    my $self = shift;
    my $vlan = shift;
    my $listener = shift;
    my $RetVal;
    
    #
    # Nortel switch doesn't support Openflow yet.
    #
    warn "ERROR: Nortel swith doesn't support Openflow now";
    return 0;
}

#
# Get used listener ports
#
sub getUsedOpenflowListenerPorts($) {
    my $self = shift;
    my %ports = ();

    warn "ERROR: Nortel swith doesn't support Openflow now\n";

    return %ports;
}

#
# Check if Openflow is supported on this switch
#
sub isOpenflowSupported($) {
    #
    # Nortel switch doesn't support Openflow yet.
    #
    return 0;
}

1620 1621
# End with true
1;