snmpit_stack.pm 48.7 KB
Newer Older
1 2 3 4
#!/usr/bin/perl -w

#
# EMULAB-LGPL
5
# Copyright (c) 2000-2011 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
#

package snmpit_stack;
use strict;

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

use English;
use SNMP;
use snmpit_lib;
Weibin Sun's avatar
Weibin Sun committed
18
use Data::Dumper;
19 20

use libdb;
21
use libtestbed;
22
use overload ('""' => 'Stringify');
23

24 25 26
our %devices;
our $parallelized = 1;

27 28 29 30 31 32 33 34 35
#
# Creates a new object. A list of devices that will be operated on is given
# so that the object knows which to connect to. A future version may not 
# require the device list, and dynamically connect to devices as appropriate
#
# usage: new(string name, string stack_id, int debuglevel, list of devicenames)
# returns a new object blessed into the snmpit_stack class
#

36
sub new($$$@) {
37 38 39 40 41 42

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

    my $stack_id = shift;
43
    my $debuglevel = shift;
44 45 46 47 48 49 50 51 52 53 54
    my @devicenames = @_;

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

    #
    # Set up some defaults
    #
55 56
    if (defined $debuglevel) {
	$self->{DEBUG} = $debuglevel;
57
	$snmpit_stack_child::child_debug = $debuglevel;
58 59 60 61 62 63 64
    } else {
	$self->{DEBUG} = 0;
    }

    $self->{STACKID} = $stack_id;
    $self->{MAX_VLAN} = 4095;
    $self->{MIN_VLAN} = 2;
65 66 67 68 69 70 71 72 73 74
    #
    # The name of the leader of this stack. We fall back on the old behavior of
    # using the stack name as the leader if the leader is not set
    #
    my $leader_name = getStackLeader($stack_id);
    if (!$leader_name) {
	$leader_name = $stack_id;
    }
    $self->{LEADERNAME} = $leader_name;

75 76 77 78 79
    #
    # Store the list of devices we're supposed to operate on
    #
    @{$self->{DEVICENAMES}} = @devicenames;

80 81 82 83 84
    # The following line will let snmpit_stack be used interchangeably
    # with snmpit_cisco_stack
    # $self->{ALLVLANSONLEADER} = 1;
    $self->{ALLVLANSONLEADER} = 0;

85 86 87 88 89 90 91
    #
    # The following two lines will let us inherit snmpit_cisco_stack
    # (someday), (and can help pare down lines of diff in the meantime)
    #
    $self->{PRUNE_VLANS} = 1;
    $self->{VTP} = 0;

92 93 94 95 96 97 98 99 100 101 102
    # must do this before spawning each device object, which forks().
    bless($self,$class);

    # see if we can run parallelized
    if ($parallelized && (!(eval "require IO::EventMux") ||
				!(eval "require RPC::Async"))) {
	$parallelized = 0;
	if ($debuglevel) {
	    print "parallel snmpit_stack requires RPC::Async and friends\n";
	}
    }
103 104 105 106

    #
    # Make a device-dependant object for each switch
    # 
107 108 109
    foreach my $devicename (@devicenames) {
	print("Making device object for $devicename\n") if $self->{DEBUG};
	my $type = getDeviceType($devicename);
110
	my $device = $devices{$devicename};
111 112 113 114 115

	#
	# Check to see if this is a duplicate
	#
	if (defined($self->{DEVICES}{$devicename})) {
116
	    warn "WARNING: Device $devicename was specified twice, skipping\n";
117 118 119
	    next;
	}
	#
120 121 122 123 124 125
	# Also check to see if we already have made this device 
	# for a different stack ...
	# 
	if (defined($device)) {
	    $self->{DEVICES}{$devicename} = $device;
	    next;
126
	}
127

128 129
	$device = snmpit_jitdev->create($devicename,$type,$self) if (!$device);

130 131 132 133 134 135 136 137 138 139
		# indented to minimize diffs
		if (!$device) {
		    die "Failed to create a device object for $devicename\n";
		} else {
		    $self->{DEVICES}{$devicename} = $device;
		    if ($devicename eq $self->{LEADERNAME}) {
			$self->{LEADER} = $device;
		    }
		}

140 141 142 143 144 145 146 147 148
	if (defined($device->{MIN_VLAN}) &&
	    ($self->{MIN_VLAN} < $device->{MIN_VLAN}))
		{ $self->{MIN_VLAN} = $device->{MIN_VLAN}; }
	if (defined($device->{MAX_VLAN}) &&
	    ($self->{MAX_VLAN} > $device->{MAX_VLAN}))
		{ $self->{MAX_VLAN} = $device->{MAX_VLAN}; }

    }

149 150 151 152 153
    my %h = $self->reapCall("device_setup");
    while (my ($devicename, $aref) = each %h) {
       my $status = @$aref[0];
       die "$devicename $status\n" if ($status ne "OK");
    }
154
    return $self;
155 156
}

157 158 159 160 161 162 163 164 165 166 167 168
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;

    my $stack_id = $self->{STACKID};

    return "[Stack ${stack_id}]";
}

Weibin Sun's avatar
Weibin Sun committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
sub FlipDebug($$)
{
    my $self = shift;
    my $debug = shift;

    $self->{'DEBUG'} = $debug;
    $snmpit_stack_child::child_debug = $debug;

    foreach my $devicename (keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	$device->{'DEBUG'} = $debug;
    }
    foreach my $device (values(%devices)) {
	$device->{'DEBUG'} = $debug;
#	print Dumper($device);
    }
    return 0;
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
#
# List all VLANs on all switches in the stack
#
# usage: listVlans(self)
#
# returns: A list of VLAN information. Each entry is an array reference. The
#	array is in the form [id, num, members] where:
#		id is the VLAN identifier, as stored in the database
#		num is the 802.1Q vlan tag number.
#		members is a reference to an array of VLAN members
#
sub listVlans($) {
    my $self = shift;

    #
203
    # We need to 'collate' the results from each switch by putting together
204 205 206
    # the results from each switch, based on the VLAN identifier
    #
    my %vlans = ();
207 208 209 210
    while (my ($devicename, $device) = each %{$self->{DEVICES}}) {
	$device->listVlans_start();
    }
    my %collector = $self->reapCall("listVlans");
211
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
212 213 214
	my @dev_result = @{$collector{$devicename}};
	next if (!@dev_result);
	foreach my $line (@dev_result) {
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
	    my ($vlan_id, $vlan_number, $memberRef) = @$line;
	    ${$vlans{$vlan_id}}[0] = $vlan_number;
	    push @{${$vlans{$vlan_id}}[1]}, @$memberRef;
	}
    }

    #
    # Now, we put the information we've found in the format described by
    # the header comment for this function
    #
    my @vlanList;
    foreach my $vlan (sort {tbsort($a,$b)} keys %vlans) {
	push @vlanList, [$vlan, @{$vlans{$vlan}}];
    } 
    return @vlanList;
}

#
# List all ports on all switches in the stack
#
# usage: listPorts(self)
#
# returns: A list of port information. Each entry is an array reference. The
#	array is in the form [id, enabled, link, speed, duplex] where:
#		id is the port identifier (in node:port form)
#		enabled is "yes" if the port is enabled, "no" otherwise
#		link is "up" if the port has carrier, "down" otherwise
#		speed is in the form "XMbps"
#		duplex is "full" or "half"
#
sub listPorts($) {
    my $self = shift;

    #
249
    # All we really need to do here is collate the results of listing the
250 251 252 253 254 255
    # ports on all devices
    #
    my %portinfo = (); 
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	foreach my $line ($device->listPorts()) {
256 257 258
	    my $port = $$line[0];
	    if (defined $portinfo{$port}) {
		warn "WARNING: Two ports found for $port\n";
259
	    }
260
	    $portinfo{$port} = $line;
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	}
    }

    return map $portinfo{$_}, sort {tbsort($a,$b)} keys %portinfo;
}

# Puts ports in the VLAN with the given identifier. Contacts the device
# appropriate for each port.
#
# usage: setPortVlan(self, vlan_id, list of ports)
# returns: the number of errors encountered in processing the request
#
sub setPortVlan($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @ports = @_;

    my $errors = 0;

    #
    # Grab the VLAN number
    #
283
    my $vlan_number = $self->findVlan($vlan_id);
284
    if (!$vlan_number) {
285 286 287
	print STDERR
	"ERROR: VLAN with identifier $vlan_id does not exist on stack " .
	$self->{STACKID} . "\n" ;
288 289 290 291 292 293
	return 1;
    }

    #
    # Split up the ports among the devices involved
    #
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 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 363 364 365 366 367 368 369 370 371 372 373
    my %map = mapPortsToDevices(@ports);
    my %trunks = getTrunks();
    my @trunks;

    if (1) {
        #
        # Use this hash like a set to find out what switches might be involved
        # in this VLAN
        #
        my %switches;
        foreach my $switch (keys %map) {
            $switches{$switch} = 1;
        }

	#
	# Find out which ports are already in this VLAN - we might be adding
        # to an existing VLAN
        # TODO - provide a way to bypass this check for new VLANs, to speed
        # things up a bit
	#
        foreach my $switch ($self->switchesWithPortsInVlan($vlan_number)) {
            $switches{$switch} = 1;
        }

        #
        # Find out every switch which might have to transit this VLAN through
        # its trunks
        #
        @trunks = getTrunksFromSwitches(\%trunks, keys %switches);
        foreach my $trunk (@trunks) {
            my ($src,$dst) = @$trunk;
            $switches{$src} = $switches{$dst} = 1;
        }

        #
        # Create the VLAN (if it doesn't exist) on every switch involved
        #
        foreach my $switch (keys %switches) {
            #
            # Check to see if the VLAN already exists on this switch
            #
            my $dev = $self->{DEVICES}{$switch};
            if (!$dev) {
                warn "ERROR: VLAN uses switch $switch, which is not in ".
                    "this stack\n";
                $errors++;
                next;
            }
            if ($dev->vlanNumberExists($vlan_number)) {
                if ($self->{DEBUG}) {
                    print "Vlan $vlan_id already exists on $switch\n";
                }
            } else {
                #
                # Check to see if we had any special arguments saved up for
                # this VLAN
                #
                my @otherargs = ();
                if (exists $self->{VLAN_SPECIALARGS}{$vlan_id}) {
                    @otherargs = @{$self->{VLAN_SPECIALARGS}{$vlan_id}}
                }

                #
                # Create the VLAN
                #
                my $res = $dev->createVlan($vlan_id,$vlan_number);
                if ($res == 0) {
                    warn "Error: Failed to create VLAN $vlan_id ($vlan_number)".
                         " on $switch\n";
                    $errors++;
                    next;
                }
            }
        }
    }

    my %BumpedVlans = ();
    #
    # Perform the operation on each switch
    #
374 375 376 377 378 379 380 381
    foreach my $devicename (keys %map) {
	my $device = $self->{DEVICES}{$devicename};
    	if (!defined($device)) {
    	    warn "Unable to find device entry for $devicename - some ports " .
	    	"will not be set up properly\n";
    	    $errors++;
    	    next;
    	}
382

383
	#
384
	# Simply make the appropriate call on the device
385 386
	#
	$errors += $device->setPortVlan($vlan_number,@{$map{$devicename}});
387 388 389 390 391 392 393 394 395 396

	#
	# When making firewalls, may have to flush FDB entries from trunks
	#
	if (defined($device->{DISPLACED_VLANS})) {
	    foreach my $vlan (@{$device->{DISPLACED_VLANS}}) {
		$BumpedVlans{$vlan} = 1;
	    }
	    $device->{DISPLACED_VLANS} = undef;
	}
397 398
    }

399 400 401
    if ($vlan_id ne 'default') {
	$errors += (!$self->setVlanOnTrunks2($vlan_number,1,\%trunks,@trunks));
    }
402

403 404
    #
    # When making firewalls, may have to flush FDB entries from trunks
405
    #
406 407 408 409 410
    foreach my $vlan (keys %BumpedVlans) {
	foreach my $devicename ($self->switchesWithPortsInVlan($vlan)) {
	    my $dev = $self->{DEVICES}{$devicename};
	    foreach my $neighbor (keys %{$trunks{$devicename}}) {
		my $trunkIndex = $dev->getChannelIfIndex(
411
				    @{$trunks{$devicename}{$neighbor}});
412 413 414 415 416
		if (!defined($trunkIndex)) {
		    warn "unable to find channel information on $devicename ".
			 "for $devicename-$neighbor EtherChannel\n";
		    $errors += 1;
		} else {
417
		    $dev->resetVlanIfOnTrunk($trunkIndex,$vlan);
418 419 420 421
		}
	    }
	}
    }
422 423 424 425 426 427
    return $errors;
}

#
# Allocate a vlan number currently not in use on the stack.
#
428
# usage: newVlanNumber(self, vlan_identifier, vlan_dbindex)
429 430
#
# returns a number in $self->{VLAN_MIN} ... $self->{VLAN_MAX}
431
# or zero indicating that the id exists.
432
#
433
sub newVlanNumber($$$) {
434
    my $self = shift;
435
    my $device_id = shift;
436
    my $vlan_id = shift;
437
    my %vlans;
438
    my $limit;
439

440
    $self->debug("stack::newVlanNumber $device_id/$vlan_id\n");
441 442 443 444 445
    if ($self->{ALLVLANSONLEADER}) {
	%vlans = $self->{LEADER}->findVlans();
    } else {
	%vlans = $self->findVlans();
    }
446
    my $number = $vlans{$device_id};
447
    # Vlan exists, so tell caller a new number/vlan is not needed.
448
    if (defined($number)) { return 0; }
449

450
    my @numbers = sort values %vlans;
451
    $self->debug("newVlanNumbers: numbers ". "@numbers" . " \n");
452 453 454 455 456 457 458 459 460 461 462 463

    # XXX temp, see doMakeVlans in snmpit.in
    if ($::next_vlan_tag) {
	$number = $::next_vlan_tag;
	$::next_vlan_tag = 0;

	#
	# Reserve this number in the table. If we can actually
	# assign it (tables locked), then we call it good. 
	#
	if ((grep {$_ == $number} @numbers) ||
	    !defined(reserveVlanTag($vlan_id, $number))) {
464 465 466 467 468
	    my $vlan_using_tag = $self->findVlanUsingTag($number);
	    print STDERR
		"*** desired vlan tag $number for vlan $vlan_id already in " .
		"use" . ($vlan_using_tag ? " by vlan $vlan_using_tag" : "") .
		"\n";
469 470 471 472 473
	    # Indicates no tag assigned. 
	    return 0;
	}
	return $number;
    }
474 475 476 477 478 479 480 481
    #
    # See if there is a number already pre-assigned in the lans table.
    # But still make sure that the number does not conflict with an
    # existing vlan.
    #
    $number = getReservedVlanTag($vlan_id);
    if ($number) {
	if (grep {$_ == $number} @numbers) {
482 483 484 485 486
	    my $vlan_using_tag = $self->findVlanUsingTag($number);
	    print STDERR
		"*** reserved vlan tag $number for vlan $vlan_id already in " .
		"use" . ($vlan_using_tag ? " by vlan $vlan_using_tag" : "") .
		"\n";
487
	    return 0;
488 489 490
	}
	return $number;
    }
491
    $number = $self->{MIN_VLAN}-1;
492 493 494
    $limit  = $self->{MAX_VLAN};

    while (++$number < $limit) {
495 496 497 498
	# Temporary cisco hack to avoid reserved vlans.
	next
	    if ($number >= 1000 && $number <= 1024);
	
499 500 501 502 503 504 505 506 507 508 509 510 511
	if (!(grep {$_ == $number} @numbers)) {
	    #
	    # Reserve this number in the table. If we can actually
	    # assign it (tables locked), then we call it good. Else
	    # go around again.
	    #
	    if (reserveVlanTag($vlan_id, $number)) {
		$self->debug("Reserved tag $number to vlan $vlan_id\n");
		return $number;
	    }
	    $self->debug("Failed to reserve tag $number for vlan $vlan_id\n");
	}
    }
512
    return 0;
513 514 515 516 517 518 519
}

#
# Creates a VLAN with the given VLAN identifier on the stack. If ports are
# given, puts them into the newly created VLAN. It is an error to create a
# VLAN that already exists.
#
520
# usage: createVlan(self, vlan identfier, vlan DB index, port list)
521 522 523 524
#
# returns: 1 on success
# returns: 0 on failure
#
525
sub createVlan($$$$;$$$) {
526
    my $self = shift;
527
    my $device_id = shift;
528 529 530
    my $vlan_id = shift;
    my @ports = @{shift()};
    my @otherargs = @_;
531
    my $vlan_number;
532
    my %map;
533
    my $errortype = "Creating";
534 535 536 537 538 539 540 541 542 543


    # We ignore other args for now, since generic stacks don't support
    # private VLANs and VTP;

    $self->lock();
    LOCKBLOCK: {
	#
	# We need to create the VLAN on all pertinent devices
	#
544
	my ($res, $devicename, $device);
545
	$vlan_number = $self->newVlanNumber($device_id, $vlan_id);
546
	if ($vlan_number == 0) { last LOCKBLOCK;}
547
	print "Creating VLAN $vlan_id as VLAN #$vlan_number on stack " .
548
                 "$self->{STACKID} ... \n";
549 550 551 552 553
	if ($self->{ALLVLANSONLEADER}) {
		$res = $self->{LEADER}->createVlan($vlan_id, $vlan_number);
		$self->unlock();
		if (!$res) { goto failed; }
	}
554 555
	%map = mapPortsToDevices(@ports);
	foreach $devicename (sort {tbsort($a,$b)} keys %map) {
556 557
	    if ($self->{ALLVLANSONLEADER} &&
		($devicename eq $self->{LEADERNAME})) { next; }
558 559 560
	    $device = $self->{DEVICES}{$devicename};
	    $res = $device->createVlan($vlan_id, $vlan_number);
	    if (!$res) {
561 562 563 564 565 566 567
		goto failed;
	    }
	}

	#
	# We need to populate each VLAN on each switch.
	#
568
	$self->debug( "adding ports @ports to VLAN $vlan_id \n");
569 570 571
	if (@ports) {
	    if ($self->setPortVlan($vlan_id,@ports)) {
		$errortype = "Adding Ports to";
572
	    failed:
573 574 575
		#
		# Ooops, failed. Don't try any more
		#
576 577
		print STDERR "$errortype VLAN $vlan_id as VLAN #$vlan_number ".
		    "on stack $self->{STACKID} ... Failed\n";
578 579
		$vlan_number = 0;
		last LOCKBLOCK;
580 581
	    }
	}
582
	print "Succeeded\n";
583 584 585

    }
    $self->unlock();
586
    return ($vlan_number <= 0 ? 0 : $vlan_number);
587 588
}

589 590 591 592 593 594 595 596
#
# Given VLAN indentifiers from the database, finds the 802.1Q VLAN
# number for them. If no 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
#
597
sub findDeviceVlans($@) {
598 599
    my $self = shift;
    my @vlan_ids = @_;
600
    my ($device, $devicename);
601
    my %mapping = ();
602 603 604 605 606 607 608
    #
    # Each value in the mapping is:
    # {
    #  'tag'     => vlan tag number,
    #  'devices' => list of devices the vlan exists on
    # }
    #
609
    $self->debug("snmpit_stack::findVlans( @vlan_ids )\n");
610 611 612
    foreach $device (values %{$self->{DEVICES}})
	{ $device->findVlans_start(@vlan_ids); }
    my %results = $self->reapCall("findVlans");
613
    foreach $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
614
	$self->debug("stack::findVlans calling $devicename\n");
615
	my %dev_map = @{$results{$devicename}};
616 617
	my ($id,$num,$oldnum);
	while (($id,$num) = each %dev_map) {
618 619 620 621
	    next
		if (!defined($num));
	    
	    if (exists($mapping{$id})) {
622 623 624 625 626 627 628 629 630 631 632 633 634 635
		$oldnum = $mapping{$id}->{'tag'};
		if (defined($num) && ($num != $oldnum)) {
		    warn "Incompatible 802.1Q tag assignments for $id\n" .
			"    Saw $num on $device->{NAME}, but had " .
			"$oldnum before\n";
		}
		push(@{ $mapping{$id}->{'devices'} }, $devicename);
	    }
	    else {
		$mapping{$id} = {
		    'tag'     => $num,
		    'devices' => [ $devicename ],
		};
	    }
636 637 638 639 640
	}
    }
    return %mapping;
}

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
sub findVlans($@) {
    my $self = shift;
    my @vlan_ids = @_;
    my %mapping = $self->findDeviceVlans(@vlan_ids);
    my %result  = ();

    #
    # The caller just wants to know vlan_id to vlan_number.
    # This is how findVlans() has always operated, and do not
    # want to change all the calls to it, yet.
    #
    foreach my $id (keys(%mapping)) {
	my $ref = $mapping{$id};
	my $num = $ref->{'tag'};
	$result{$id} = $num;
    }
    return %result;
}

660 661 662 663 664 665 666 667 668 669 670
#
# Given a single VLAN indentifier, find the 802.1Q VLAN tag for it. 
# 
# usage: findVlan($self, $vlan_id)
#        returns the number if found
#        0 otherwise;
#
sub findVlan($$) {
    my ($self, $vlan_id) = @_;

    $self->debug("snmpit_stack::findVlan( $vlan_id )\n");
671 672 673 674 675
    if ($parallelized) {
	my %dev_map = $self->findVlans($vlan_id);
	my $vlan_num = $dev_map{$vlan_id};
	return defined($vlan_num) ? $vlan_num : 0;
    }
676 677 678 679 680 681 682 683 684
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}->{$devicename};
	my %dev_map = $device->findVlans($vlan_id);
	my $vlan_num = $dev_map{$vlan_id};
	if (defined($vlan_num)) { return $vlan_num; }
    }
    return 0;
}

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
#
# Find what vlan a tag is associated with.
# 
# usage: findVlanUsingTag($self, $number)
#        returns the vlan_id if found
#        0 otherwise;
#
sub findVlanUsingTag($$) {
    my ($self, $number) = @_;

    $self->debug("snmpit_stack::findVlanUsingTag( $number )\n");
    if ($parallelized) {
	my %dev_map = $self->findVlans();
	foreach my $vlan_id (keys(%dev_map)) {
	    return $vlan_id
		if ($number == $dev_map{$vlan_id});
	}
	return 0;
    }
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}->{$devicename};
	my %dev_map = $device->findVlans();
	foreach my $vlan_id (keys(%dev_map)) {
	    return $vlan_id
		if ($number == $dev_map{$vlan_id});
	}
	return 0;
    }
    return 0;
}

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
#
# Check to see if the given VLAN exists in the stack
#
# usage: vlanExists(self, vlan identifier)
#
# returns 1 if the VLAN exists
#         0 otherwise
#
sub vlanExists($$) {
    my $self = shift;
    my $vlan_id = shift;
    my %mapping = $self->findVlans();

    if (defined($mapping{$vlan_id})) {
	return 1;
    } else {
	return 0;
    }

}

#
# Return a list of which VLANs from the input set exist on this stack
#
# usage: existantVlans(self, vlan identifiers)
#
# returns: a list containing the VLANs from the input set that exist on this
# 	stack
#
sub existantVlans($@) {
    my $self = shift;
    my @vlan_ids = @_;

    my %mapping = $self->findVlans(@vlan_ids);

    my @existant = ();
    foreach my $vlan_id (@vlan_ids) {
	if (defined $mapping{$vlan_id}) {
	    push @existant, $vlan_id;
	}
    }

    return @existant;

}

#
# Removes a VLAN from the stack. This implicitly removes all ports from the
# VLAN. It is an error to remove a VLAN that does not exist.
#
# usage: removeVlan(self, vlan identifiers)
#
# returns: 1 on success
# returns: 0 on failure
#
sub removeVlan($@) {
    my $self = shift;
    my @vlan_ids = @_;
    my $errors = 0;

    #
    # Exit early if no VLANs given
    #
    if (!@vlan_ids) {
	return 1;
    }

    my %vlan_numbers = $self->findVlans(@vlan_ids);
    foreach my $vlan_id (@vlan_ids) {
	#
	# First, make sure that the VLAN really does exist
	#
	my $vlan_number = $vlan_numbers{$vlan_id};
	if (!$vlan_number) {
	    warn "ERROR: VLAN $vlan_id not found on switch!";
	    return 0;
	}

	#
	# Prevent the VLAN from being sent across trunks.
	#
	if (!$self->setVlanOnTrunks($vlan_number,0)) {
Mike Hibler's avatar
Mike Hibler committed
798
	    warn "ERROR: Unable to remove VLAN $vlan_number from trunks!\n";
799 800 801 802 803 804 805 806 807 808 809 810 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 844 845
	    #
	    # We can keep going, 'cause we can still remove the VLAN
	    #
	}
	
    }

    #
    # Now, we go through each device and remove all ports from the VLAN
    # on that device. Note the reverse sort order! This way, we do not
    # interfere with another snmpit processes, since createVlan tries
    # in 'forward' order (we will remove the VLAN from the 'last' switch
    # first, so the other snmpit will not see it free until it's been
    # removed from all switches)
    #
    LOOP: foreach my $devicename (sort {tbsort($b,$a)} keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
	my @existant_vlans = ();
	my %vlan_numbers = $device->findVlans(@vlan_ids);
	foreach my $vlan_id (@vlan_ids) {

	    #
	    # Only remove ports from the VLAN if it exists on this
	    # device. Do it in one pass for efficiency
	    #
	    if (defined $vlan_numbers{$vlan_id}) {
		push @existant_vlans, $vlan_numbers{$vlan_id};
	    }
	}
	next LOOP if (scalar(@existant_vlans) == 0);

	print "Removing ports on $devicename from VLANS " . 
	    join(",",@existant_vlans)."\n" if $self->{DEBUG};

	$errors += $device->removePortsFromVlan(@existant_vlans);

	#
	# Since mixed stacks doesn't use VTP, delete the VLAN, too.
	#
	my $ok = $device->removeVlan(@existant_vlans);
	if (!$ok) { $errors++; }
    }

    return ($errors == 0);
}

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
#
# Remove some ports from a single vlan. Ports should not be in trunk mode.
#
# usage: removeSomePortsFromVlan(self, vlanid, portlist)
#
# returns: 1 on success
# returns: 0 on failure
#
sub removeSomePortsFromVlan($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @ports = @_;
    my $errors = 0;
    
    my %vlan_numbers = $self->findVlans($vlan_id);
    
    #
    # First, make sure that the VLAN really does exist
    #
    if (!exists($vlan_numbers{$vlan_id})) {
	warn "ERROR: VLAN $vlan_id not found on switch!";
	return 0;
    }
Weibin Sun's avatar
Weibin Sun committed
869
    my %map = mapPortsToDevices(@ports);
870 871 872 873 874 875 876 877 878

    #
    # Now, we go through each device and remove all ports from the VLAN
    # on that device. Note the reverse sort order! This way, we do not
    # interfere with another snmpit processes, since createVlan tries
    # in 'forward' order (we will remove the VLAN from the 'last' switch
    # first, so the other snmpit will not see it free until it's been
    # removed from all switches)
    #
Weibin Sun's avatar
Weibin Sun committed
879
    foreach my $devicename (sort {tbsort($b,$a)} keys %map) {
880 881 882 883 884 885 886 887 888 889 890 891 892 893
	my $device = $self->{DEVICES}{$devicename};
	my %vlan_numbers = $device->findVlans($vlan_id);

	#
	# Only remove ports from the VLAN if it exists on this device.
	#
	next
	    if (!defined($vlan_numbers{$vlan_id}));

	my $vlan_number = $vlan_numbers{$vlan_id};
	    
	print "Removing ports on $devicename from VLAN $vlan_id ($vlan_number)\n"
	    if $self->{DEBUG};

894
	$errors += $device->removeSomePortsFromVlan($vlan_number,
Weibin Sun's avatar
Weibin Sun committed
895
						    @{$map{$devicename}});
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
    }
    return ($errors == 0);
}

#
# Remove some ports from a single trunk.
#
# usage: removeSomePortsFromTrunk(self, vlanid, portlist)
#
# returns: 1 on success
# returns: 0 on failure
#
sub removeSomePortsFromTrunk($$@) {
    my $self = shift;
    my $vlan_id = shift;
    my @ports = @_;
    my $errors = 0;
    
    my %vlan_numbers = $self->findVlans($vlan_id);
    
    #
    # First, make sure that the VLAN really does exist
    #
    if (!exists($vlan_numbers{$vlan_id})) {
	warn "ERROR: VLAN $vlan_id not found on switch!";
	return 0;
    }
Weibin Sun's avatar
Weibin Sun committed
923
    my %map = mapPortsToDevices(@ports);
924 925 926 927 928 929 930 931 932

    #
    # Now, we go through each device and remove all ports from the trunk
    # on that device. Note the reverse sort order! This way, we do not
    # interfere with another snmpit processes, since createVlan tries
    # in 'forward' order (we will remove the VLAN from the 'last' switch
    # first, so the other snmpit will not see it free until it's been
    # removed from all switches)
    #
Weibin Sun's avatar
Weibin Sun committed
933
    foreach my $devicename (sort {tbsort($b,$a)} keys %map) {
934 935 936 937 938 939 940 941 942 943 944
	my $device = $self->{DEVICES}{$devicename};
	my %vlan_numbers = $device->findVlans($vlan_id);

	#
	# Only remove ports from the VLAN if it exists on this device.
	#
	next
	    if (!defined($vlan_numbers{$vlan_id}));

	my $vlan_number = $vlan_numbers{$vlan_id};
	    
Weibin Sun's avatar
Weibin Sun committed
945 946
	print "Removing trunk ports on $devicename from VLAN ".
	    "$vlan_id ($vlan_number)\n"
947 948
	    if $self->{DEBUG};

Weibin Sun's avatar
Weibin Sun committed
949
	foreach my $port (@{$map{$devicename}}) {
950
	    return 0
951
		if (! $device->setVlansOnTrunk($port, 0, $vlan_number));
952 953 954 955 956 957
	}
    }

    return 1;
}

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
#
# Set a variable associated with a port. 
# TODO: Need a list of variables here
#
sub portControl ($$@) { 
    my $self = shift;
    my $cmd = shift;
    my @ports = @_;
    my %portDeviceMap = mapPortsToDevices(@ports);
    my $errors = 0;
    # XXX: each
    while (my ($devicename,$ports) = each %portDeviceMap) {
	$errors += $self->{DEVICES}{$devicename}->portControl($cmd,@$ports);
    }
    return $errors;
}

#
# Get port statistics for all devices in the stack
#
sub getStats($) {
    my $self = shift;

    #
982
    # All we really need to do here is collate the results of listing the
983 984 985 986 987 988 989
    # ports on all devices
    #
    my %stats = (); 
    foreach my $devicename (sort {tbsort($a,$b)} keys %{$self->{DEVICES}}) {
	my $device = $self->{DEVICES}{$devicename};
	foreach my $line ($device->getStats()) {
	    my $port = $$line[0];
990 991
	    if (defined $stats{$port}) {
		warn "WARNING: Two ports found for $port\n";
992
	    }
993
	    $stats{$port} = $line;
994 995 996 997
	}
    }
    return map $stats{$_}, sort {tbsort($a,$b)} keys %stats;
}
998 999 1000
#
# Turns on trunking on a given port, allowing only the given VLANs on it
#
1001 1002 1003 1004
# usage: enableTrunking2(self, port, equaltrunking, vlan identifier list)
#
# formerly was enableTrunking() without the predicate to decline to put
# the port in dual mode.
1005 1006 1007 1008
#
# returns: 1 on success
# returns: 0 on failure
#
1009
sub enableTrunking2($$$@) {
1010 1011
    my $self = shift;
    my $port = shift;
1012
    my $equaltrunking = shift;
1013 1014 1015
    my @vlan_ids = @_;

    #
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    # Split up the ports among the devices involved
    #
    my %map = mapPortsToDevices($port);
    my ($devicename) = keys %map;
    my $device = $self->{DEVICES}{$devicename};
    if (!defined($device)) {
	warn "ERROR: Unable to find device entry for $devicename\n";
	return 0;
    }
    #
1026
    # If !equaltrunking, the first VLAN given becomes the PVID for the trunk
1027
    #
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    my ($native_vlan_id, $vlan_number);
    if ($equaltrunking) {
	$native_vlan_id = "default";
	$vlan_number = 1;
    } else {
	$native_vlan_id = shift @vlan_ids;
	if (!$native_vlan_id) {
	    warn "ERROR: No VLAN passed to enableTrunking()!\n";
	    return 0;
	}
	#
	# Grab the VLAN number for the native VLAN
	#
	$vlan_number = $device->findVlan($native_vlan_id);
	if (!$vlan_number) {
	    warn "Native VLAN $native_vlan_id was not on $devicename";
	    # This is painful
	    my $error = $self->setPortVlan($native_vlan_id,$port);
	    if ($error) {
		    warn ", and couldn't add it\n"; return 0;
	    } else { warn "\n"; } 
	}
1050 1051 1052 1053
    }
    #
    # Simply make the appropriate call on the device
    #
1054
    print "Enable trunking: Port is $port, native VLAN is $native_vlan_id\n"
1055
	if ($self->{DEBUG});
1056
    my $rv = $device->enablePortTrunking2($port, $vlan_number, $equaltrunking);
1057 1058 1059 1060 1061 1062 1063 1064

    #
    # If other VLANs were given, add them to the port too
    #
    if (@vlan_ids) {
	my @vlan_numbers;
	foreach my $vlan_id (@vlan_ids) {
	    #
1065 1066 1067
	    # setPortVlan makes sure that the VLAN really does exist
	    # and will set up intervening trunks as well as adding the
	    # trunked port to that VLAN
1068
	    #
1069 1070
	    my $error = $self->setPortVlan($vlan_id,$port);
	    if ($error) {
1071
		warn "ERROR: could not add VLAN $vlan_id to trunk $port\n";
1072
		next;
1073
	    }
1074
	    push @vlan_numbers, $vlan_number;
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
	}
    }
    return $rv;
}

#
# Turns off trunking for a given port
#
# usage: disableTrunking(self, ports)
#
# returns: 1 on success
# returns: 0 on failure
#
sub disableTrunking($$) {
    my $self = shift;
    my $port = shift;

    #
    # Split up the ports among the devices involved
    #
    my %map = mapPortsToDevices($port);
    my ($devicename) = keys %map;
    my $device = $self->{DEVICES}{$devicename};
    if (!defined($device)) {
	warn "ERROR: Unable to find device entry for $devicename\n";
	return 0;
    }

    #
    # Simply make the appropriate call on the device
    #
    my $rv = $device->disablePortTrunking($port);

    return $rv;
}
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

#
# Not a 'public' function - only needs to get called by other functions in
# this file, not external functions.
#
# Enables or disables (depending on $value) a VLAN on all appropriate
# switches in a stack. Returns 1 on sucess, 0 on failure.
#
# ONLY pass in @ports if you're SURE that they are the only ports in the
# VLAN - basically, only if you just created it. This is a shortcut, so
# that we don't have to ask all switches if they have any ports in the VLAN.
#
sub setVlanOnTrunks($$$;@) {
    my $self = shift;
    my $vlan_number = shift;
    my $value = shift;
    my @ports = @_;

    #
    # First, get a list of all trunks
    #
    my %trunks = getTrunks();

    #
    # Next, figure out which switches this VLAN exists on
    #
    my @switches;
    if (@ports) {
	#
	# I'd rather not have to go out to the switches to ask which ones
	# have ports in the VLAN. So, if they gave me ports, I'll just 
	# trust that those are the only ones in the VLAN
	#
	@switches = getDeviceNames(@ports);
    } else {
	#
	# Since this may be a hand-created (not from the database) VLAN, the
	# only way we can figure out which swtiches this VLAN spans is to
	# ask them all.
	#
1150
        @switches = $self->switchesWithPortsInVlan($vlan_number);
1151 1152 1153 1154 1155 1156 1157
    }

    #
    # Next, get a list of the trunks that are used to move between these
    # switches
    #
    my @trunks = getTrunksFromSwitches(\%trunks,@switches);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    return $self->setVlanOnTrunks2($vlan_number,$value,\%trunks,@trunks);
}
#
# Enables or disables (depending on $value) a VLAN on all the supplied
# trunks. Returns 1 on sucess, 0 on failure.
#
sub setVlanOnTrunks2($$$$@) {
    my $self = shift;
    my $vlan_number = shift;
    my $value = shift;
    my $trunkref = shift;
    my @trunks = @_;
1170 1171 1172 1173 1174 1175 1176 1177 1178

    #
    # Now, we go through the list of trunks that need to be modifed, and
    # do it! We have to modify both ends of the trunk, or we'll end up wasting
    # the trunk bandwidth.
    #
    my $errors = 0;
    foreach my $trunk (@trunks) {
	my ($src,$dst) = @$trunk;
1179 1180 1181 1182 1183 1184 1185 1186 1187

        #
        # For now - ignore trunks that leave the stack. We may have to revisit
        # this at some point.
        #
        if (!$self->{DEVICES}{$src} || !$self->{DEVICES}{$dst}) {
            next;
        }

1188 1189 1190 1191 1192
	if (!$self->{DEVICES}{$src}) {
	    warn "ERROR - Bad device $src found in setVlanOnTrunks!\n";
	    $errors++;
	} else {
	    #
1193
	    # Trunks might be EtherChannels, find the ifIndex
1194
	    #
1195 1196 1197 1198 1199 1200
            my $trunkIndex = $self->{DEVICES}{$src}->
                             getChannelIfIndex(@{ $$trunkref{$src}{$dst} });
            if (!defined($trunkIndex)) {
                warn "ERROR - unable to find channel information on $src ".
		     "for $src-$dst EtherChannel\n";
                $errors += 1;
1201
            } else {
1202 1203 1204 1205 1206 1207
		if (!$self->{DEVICES}{$src}->
                        setVlansOnTrunk($trunkIndex,$value,$vlan_number)) {
                    warn "ERROR - unable to set trunk on switch $src\n";
                    $errors += 1;
                }
	    }
1208 1209 1210 1211 1212 1213
	}
	if (!$self->{DEVICES}{$dst}) {
	    warn "ERROR - Bad device $dst found in setVlanOnTrunks!\n";
	    $errors++;
	} else {
	    #
1214
	    # Trunks might be EtherChannels, find the ifIndex
1215
	    #
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
            my $trunkIndex = $self->{DEVICES}{$dst}->
                             getChannelIfIndex(@{ $$trunkref{$dst}{$src} });
            if (!defined($trunkIndex)) {
                warn "ERROR - unable to find channel information on $dst ".
		     "for $src-$dst EtherChannel\n";
                $errors += 1;
            } else {
		if (!$self->{DEVICES}{$dst}->
                        setVlansOnTrunk($trunkIndex,$value,$vlan_number)) {
                    warn "ERROR - unable to set trunk on switch $dst\n";
                    $errors += 1;
                }
	    }
1229 1230 1231 1232 1233 1234
	}
    }

    return (!$errors);
}

1235 1236 1237 1238 1239
#
# Not a 'public' function - only needs to get called by other functions in
# this file, not external functions.
#
# Get a list of all switches that have at least one port in the given
1240
# VLAN - note that this takes a VLAN number, not a VLAN ID
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
#
# Returns a possibly-empty list of switch names
#
# PS By sklower since this is only used in adding ports or even more
# interswitch trunks, no harm is done if we ask if the the vlan exists
# (we erroneously include interswitch trunks).  doing a listVlans() is a
# VERY expensive operation.

sub switchesWithPortsInVlan($$) {
    my $self = shift;
    my $vlan_number = shift;
1252 1253 1254 1255 1256 1257 1258
    my %mapping = $self->findDeviceVlans();

    foreach my $id (keys(%mapping)) {
	my $ref = $mapping{$id};
	my $num = $ref->{'tag'};

	return @{ $ref->{'devices'} } if ($num == $vlan_number);
1259
    }
1260
    return ();
1261 1262
}

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
#
# Prints out a debugging message, but only if debugging is on. If a level is
# given, the debuglevel must be >= that level for the message to print. If
# the level is omitted, 1 is assumed
#
# Usage: debug($self, $message, $level)
#
sub debug($$;$) {
    my $self = shift;
    my $string = shift;
    my $debuglevel = shift;
   if (!(defined $debuglevel)) {
	$debuglevel = 1;
    }
    if ($self->{DEBUG} >= $debuglevel) {
	print STDERR $string;
    }
}

1282 1283
my $lock_held = 0;

1284 1285 1286 1287 1288
sub lock($) {
    my $self = shift;
    my $stackid = $self->{STACKID};
    my $token = "snmpit_$stackid";
    my $old_umask = umask(0);
1289
    die if (TBScriptLock($token,0,1800) != TBSCRIPTLOCK_OKAY());
1290
    umask($old_umask);
1291
    $lock_held = 1;
1292 1293 1294
}

sub unlock($) {
1295
	if ($lock_held) { TBScriptUnlock(); $lock_held = 0;}
1296 1297
}

1298 1299 1300 1301 1302 1303
sub reapCall($$) {
    my ($self,$proc) = @_;
    $self->debug("snmpit_stack::reapCall($proc)\n");
    return snmpit_jitdev::reapCall($proc);
}

1304 1305 1306 1307 1308 1309
#
# Enable Openflow
#
# enableOpenflow(self, vlan_id);
# return # of errors
#
Weibin Sun's avatar
Weibin Sun committed
1310 1311
sub enableOpenflow($$) {
    my $self = shift;
1312
    my $vlan_id = shift;
Weibin Sun's avatar
Weibin Sun committed
1313
    
1314
    my $errors = 0;
Weibin Sun's avatar
Weibin Sun committed
1315 1316 1317
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1318 1319 1320 1321 1322 1323 1324 1325 1326
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1327
		print "Enabling Openflow on $devicename for VLAN $vlan_id".
1328
		    "..." if $self->{DEBUG};
1329 1330 1331

		my $ok = $device->enableOpenflow($vlan_number);
		if (!$ok) { $errors++; }
1332 1333 1334 1335 1336 1337 1338 1339
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
Weibin Sun's avatar
Weibin Sun committed
1340 1341
	}
    }
1342 1343
        
    return $errors;
Weibin Sun's avatar
Weibin Sun committed
1344 1345
}

1346 1347 1348 1349 1350 1351
#
# Disable Openflow
# 
# disableOpenflow(self, vlan_id);
# return # of errors
#
Weibin Sun's avatar
Weibin Sun committed
1352 1353
sub disableOpenflow($$) {
    my $self = shift;
1354
    my $vlan_id = shift;
Weibin Sun's avatar
Weibin Sun committed
1355
    
1356 1357 1358 1359
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1360 1361 1362 1363 1364 1365 1366 1367 1368
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1369
		print "Disabling Openflow on $devicename for VLAN $vlan_id".
1370
		    "..." if $self->{DEBUG};
1371 1372 1373

		my $ok = $device->disableOpenflow($vlan_number);
		if (!$ok) { $errors++; }
1374 1375 1376 1377 1378 1379 1380 1381
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
1382 1383 1384 1385
	}
    }
        
    return $errors;
Weibin Sun's avatar
Weibin Sun committed
1386 1387
}

1388 1389 1390 1391 1392 1393
#
# Set Openflow controller on VLAN
# 
# setController(self, vlan_id, controller);
# return # of errors
#
1394
sub setOpenflowController($$$) {
Weibin Sun's avatar
Weibin Sun committed
1395
    my $self = shift;
1396
    my $vlan_id = shift;
Weibin Sun's avatar
Weibin Sun committed
1397 1398
    my $controller = shift;
    
1399 1400 1401 1402
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1403 1404 1405 1406 1407 1408 1409 1410 1411
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1412
		print "Setting Openflow controller on $devicename for VLAN $vlan_id".
1413
		    "..." if $self->{DEBUG};
1414

1415
		my $ok = $device->setOpenflowController($vlan_number, $controller);
1416
		if (!$ok) { $errors++; }
1417 1418 1419 1420 1421 1422 1423 1424
		else {print "Done! \n" if $self->{DEBUG};}
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
1425 1426 1427 1428
	}
    }
        
    return $errors;
Weibin Sun's avatar
Weibin Sun committed
1429 1430
}

1431 1432 1433 1434 1435 1436
#
# Set Openflow listener on VLAN
#
# setListener(self, vlan_id, listener);
# return # of errors
#
1437
sub setOpenflowListener($$$) {
Weibin Sun's avatar
Weibin Sun committed
1438
    my $self = shift;
1439
    my $vlan_id = shift;
Weibin Sun's avatar
Weibin Sun committed
1440 1441
    my $listener = shift;
    
1442 1443 1444 1445
    my $errors = 0;
    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1446 1447 1448 1449 1450 1451 1452 1453 1454
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {
1455
		print "Setting Openflow listener on $devicename for VLAN $vlan_id".
1456
		    "..." if $self->{DEBUG};
1457

1458
		my $ok = $device->setOpenflowListener($vlan_number, $listener);
1459
		if (!$ok) { $errors++; }
1460 1461 1462 1463
		else {
		    print "Done! \n" if $self->{DEBUG};
		    print "  Openflow listener on $devicename for VLAN $vlan_id is $listener \n";
		}
1464 1465 1466 1467 1468 1469 1470 1471
	    } else {
		#
		# TODO: Should this be an error?
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
		$errors++;
	    }
	}	
1472 1473 1474
    }
        
    return $errors;
Weibin Sun's avatar
Weibin Sun committed
1475 1476
}

1477 1478 1479
#
# Get used Openflow listener ports
#
1480 1481
# getUsedOpenflowListenerPorts(self, vlan_id)
#
1482 1483
sub getUsedOpenflowListenerPorts($$) {
    my $self = shift;
1484 1485
    my $vlan_id = shift;
    my %ports = ();
1486 1487 1488 1489

    foreach my $devicename (keys %{$self->{DEVICES}})
    {
	my $device = $self->{DEVICES}{$devicename};
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
	my $vlan_number = $device->findVlan($vlan_id, 2);
	if (!$vlan_number) {
	    #
	    # Not sure if this is an error or not.
	    # It might be possible that not all devices in a stack have the given VLAN.
	    #
	    print "$device has no VLAN $vlan_id, ignore it. \n" if $self->{DEBUG};
	} else {
	    if ($device->isOpenflowSupported()) {		
		my %tmports = $device->getUsedOpenflowListenerPorts();
		@ports{ keys %tmports } = values %tmports;		
	    } else {
		#
		# YES this be an error because the VLAN is on it.
		#
		warn "ERROR: Openflow is not supported on $devicename \n";
	    }
	}	
1508
    }
1509 1510

    return %ports;
1511
}
1512

1513

1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
package snmpit_jitdev;
use Dumpvalue;
our $jitdev_dumper;

# class method to do lazy creation of devs.
# don't want to do an snmp connect, walk tables unless we have to.
# snmpit_jitdev->create($devicename, $type, $parent);


sub create($$$$) {
    my ($class, $name, $type, $parent) = @_;
    my $self = { NAME => $name, TYPE => $type,
		PARENT => $parent, DEBUG => $parent->{DEBUG}};
    if ($parent->{DEBUG} && !$jitdev_dumper) { $jitdev_dumper = new Dumpvalue; }
1528 1529 1530 1531 1532
    # The device options get recorded in the fork,
    # so we have to do them here too (so we can fish out # min and max vlan)
    my $options = snmpit_lib::getDeviceOptions($name);
    $self->{MIN_VLAN} = $options->{'min_vlan'} if ($options);
    $self->{MAX_VLAN} = $options->{'max_vlan'} if ($options);
1533 1534 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
    bless ($self, $class);
    $devices{$name} = $self;
    $self->spawn() if ($snmpit_stack::parallelized);
    $self->startChildCall("device_setup",$name);
    # reapCall("device_setup"); done in snmpit_stack::new();
    return $self;
}

sub debug($$;$) { return &snmpit_stack::debug(@_); }

sub snap($) {
    my ($self) = @_;

    if (!defined($self->{OBJ})) {
	my $devicename = $self->{NAME};
	my $type = $self->{TYPE};
	my $device;

	if ($self->{DEBUG}) { print "snapping $devicename \n"; }

	#
	# We check the type for two reasons: to determine which kind of
	# object to create, and for some sanity checking to make sure
	# we weren't given devicenames for devices that aren't switches.
	#
	SWITCH: for ($type) {
	    (/cisco/) && do {
1560
		require snmpit_cisco;
1561 1562 1563 1564 1565
		$device = new snmpit_cisco($devicename,$self->{DEBUG});
		last;
		}; # /cisco/
	    (/foundry1500/ || /foundry9604/)
		    && do {
1566
		require snmpit_foundry;
1567 1568 1569 1570 1571
		$device = new snmpit_foundry($devicename,$self->{DEBUG});
		last;
		}; # /foundry.*/
	    (/nortel1100/ || /nortel5510/)
		    && do {
1572
		require snmpit_nortel;
1573 1574 1575 1576 1577
		$device = new snmpit_nortel($devicename,$self->{DEBUG});
		last;
		}; # /nortel.*/
	    (/hp/)
		    && do {
1578
		require snmpit_hp;
1579 1580 1581
		$device = new snmpit_hp($devicename,$self->{DEBUG});
		last;
		}; # /hp.*/
1582 1583
	    (/apcon/)
		    && do {
1584
		require snmpit_apcon;
1585 1586 1587
		$device = new snmpit_apcon($devicename,$self->{DEBUG});
		last;
	        }; # /apcon.*/
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 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778