snmpit_lib.pm 50.6 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LGPL
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
# License for more details.
# 
# You should have received a copy of the GNU Lesser General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33 34
#

#
# Module of subroutines useful to snmpit and its modules
#

package snmpit_lib;

use Exporter;
@ISA = ("Exporter");
@EXPORT = qw( macport portnum portiface Dev vlanmemb vlanid
		getTestSwitches getControlSwitches getSwitchesInStack
35 36
                getSwitchesInStacks
		getVlanPorts
37 38 39 40 41 42 43 44 45 46 47 48 49
		getExperimentTrunks setVlanStack
		getExperimentVlans getDeviceNames getDeviceType
		getInterfaceSettings mapPortsToDevices getSwitchPrimaryStack
		getSwitchStacks getStacksForSwitches
		getStackType getStackLeader filterVlansBySwitches
		getDeviceOptions getTrunks getTrunksFromSwitches
                getTrunkHash 
		getExperimentPorts snmpitGet snmpitGetWarn snmpitGetFatal
                getExperimentControlPorts
                getPlannedStacksForVlans getActualStacksForVlans
                filterPlannedVlans
		snmpitSet snmpitSetWarn snmpitSetFatal 
                snmpitBulkwalk snmpitBulkwalkWarn snmpitBulkwalkFatal
50
	        setPortEnabled setPortTagged IsPortTagged
51 52 53 54
		printVars tbsort getExperimentCurrentTrunks
	        getExperimentVlanPorts
                uniq isSwitchPort getPathVlanIfaces
		reserveVlanTag getReservedVlanTag clearReservedVlanTag
55 56
                convertPortFromString convertPortsFromStrings
                mapVlansToSwitches mapStaleVlansToSwitches
57
		getTrunksForVlan getExperimentTrunksForVlan
58
		setSwitchTrunkPath mapPortsToSwitches 
59 60 61 62 63 64 65 66
);

use English;
use libdb;
use libtestbed;
use libtblog qw(tbdie tbwarn tbreport SEV_ERROR);
use Experiment;
use Lan;
67
use emutil qw(SpanningTree);
68 69
use strict;
use SNMP;
70
use Port;
71
use Carp qw(cluck);
72 73 74 75 76 77 78 79 80 81 82

my $TBOPS = libtestbed::TB_OPSEMAIL;

my $debug = 0;

my $DEFAULT_RETRIES = 10;

my $SNMPIT_GET = 0;
my $SNMPIT_SET = 1;
my $SNMPIT_BULKWALK = 2;

83 84 85
##################################################
# deprecated:

86 87 88 89 90 91 92 93 94
my %Devices=();
# Devices maps device names to device IPs

my %Interfaces=();
# Interfaces maps pcX:Y<==>MAC

my %PortIface=();
# Maps pcX:Y<==>pcX:iface

95 96 97
my %IfaceModPorts=();
# Maps switch:iface <=> switch:card.port

98 99 100
my %Ports=();
# Ports maps pcX:Y<==>switch:port

101 102
##################################################

103 104 105 106 107 108
my %vlanmembers=();
# vlanmembers maps id -> members

my %vlanids=();
# vlanids maps pid:eid <==> id

109 110 111
my %DeviceOptions=();
# Maps devicename -> hash of options to avoid db call after forking;

112 113 114 115 116 117 118 119 120
my $snmpitErrorString;

# Protos
sub getTrunkPath($$$$);

#
# Initialize the library
#
sub init($) {
121
    $debug = shift || $debug;    
Mike Hibler's avatar
Mike Hibler committed
122
    &ReadDeviceOptions;
123 124 125 126
    return 0;
}

#
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
# Very very powerful converter: string -> Port instance
# the string can be iface or card+port format
#
sub convertPortFromString($;$)
{
    my ($str, $dev) = @_;

    if (ref($str) =~ /Port/) {
	return $str;
    }

    my $p = Port->LookupByIface($str);
    return $p if $p;

    $p = Port->LookupByTriple($str);
    return $p if $p;

    if (defined($dev)) {
	$p = Port->LookupByIface(Port->Tokens2IfaceString($dev, $str));
	return $p if $p;

	my ($card, $port) = Port->ParseCardPortString($str);
	if ($card) {
	    $p = Port->LookupByTriple(Port->Tokens2TripleString($dev, $card, $port));
	    return $p if $p;
	}
Weibin Sun's avatar
Weibin Sun committed
153
    } elsif ($str =~ /^(.+):(.+)$/) {
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	my $node = $1;
	my $card = $2;

	my $result = DBQueryFatal("SELECT isswitch FROM node_types WHERE type IN ".
				  "(SELECT type FROM nodes WHERE node_id='$node')");

	#
	# Make sure this is not switch port
	#
	if ($result->numrows() != 1 || ($result->fetchrow())[0] != 1) {
	    #
	    # deal with old node:card format
	    #
	    $p = Port->LookupByTriple(Port->Tokens2TripleString($node, $card, "1"));
	    return $p if $p;
	}
170 171 172 173 174
    }

    return undef;			      
}

175
sub convertPortsFromStrings($@)
176
{
177 178
    my ($dev, @strs) = @_;

179 180 181 182 183
    return grep(defined($_), map(convertPortFromString($_, $dev), @strs)); 
}

#
# Deprecated
184 185
# Map between interfaces and mac addresses
#
186 187
sub macport { 
    return undef;
188 189 190
}

#
191
# Deprecated
192 193
# Map between node:iface and port numbers
#
194 195
sub portiface { 
    return undef;
196 197
}

198

199
#
200
# Deprecated
201 202 203
# Map between switch interfaces and port numbers
#
sub portnum {
204
    return undef;
205 206 207
}

#
208
# Deprecated
209 210
# Map between interfaces and the devices they are attached to
#
211 212
sub Dev { 
    return undef;
213 214 215
}

#
216 217
# Deprecated
# Map between ifaces and switch port
218
#
219 220
sub ifacemodport { 
    return undef;
221 222 223 224 225 226 227 228 229 230 231
}

#
# Get real ifaces on switch node in a VLAN that implements a path
# that consists of two layer 1 connections and also has a switch as
# the middle node.
#
sub getPathVlanIfaces($$) {
    my $vlanid = shift;
    my $ifaces = shift;

232 233
    my $vlan  = VLan->Lookup($vlanid);
    my $vname = $vlan->vname();
234 235 236 237 238 239 240 241 242
    my $experiment = $vlan->GetExperiment();
    my $pid = $experiment->pid();
    my $eid = $experiment->eid();
    
    my %ifacesonswitchnode = ();
    
    # find the underline path of the link
    my $query_result =
	DBQueryWarn("select distinct implemented_by_path from ".
243 244
		    "virt_lans where pid='$pid' and eid='$eid' ".
		    "          and vname='$vname'");
245
    if (!$query_result || !$query_result->numrows) {
246 247 248
	# Not an error since encapsulation vlans have generated names.
	%$ifaces = %ifacesonswitchnode;
	return 1;
249 250 251 252
    }

    # default implemented_by is empty
    my ($path) = $query_result->fetchrow_array();
253 254 255 256
    if (!defined($path) || $path eq "") {
	# Also not an error.
	%$ifaces = %ifacesonswitchnode;
	return 1;
257 258 259
    }

    # find the segments of the path
260
    $query_result = DBQueryWarn("select segmentname, segmentindex, layer from virt_paths ".
261 262 263 264 265
				"where pid='$pid' and eid='$eid' and pathname='$path';");
    if (!$query_result || !$query_result->numrows) {
	warn "Can't find path $path definition in DB.";
	return -1;
    }
266
    
267
    if ($query_result->numrows > 2) {
268 269 270 271 272 273
	my ($segname, $segindex, $layer) = $query_result->fetchrow();

	# only print warning msg when we are dealing with layer 1 links
	if ($layer == 1) {
	    warn "We can't handle the path with more than two segments.";
	}
274 275 276 277 278 279
	return -1;
    }
    
    my @vlans = ();
    VLan->ExperimentVLans($experiment, \@vlans);
    
280
    while (my ($segname, $segindex, $layer) = $query_result->fetchrow())
281
    {
282 283 284 285 286 287 288
	#
	# we only deal with layer 1 links
	#
	if ($layer != 1) {
	    return -1;
	}
	
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	foreach my $myvlan (@vlans)
	{	    
	    if ($myvlan->vname eq $segname) {
		my @members;

		$vlan->MemberList(\@members);		
		foreach my $member (@members) {
		    my ($node,$iface);

		    $member->GetAttribute("node_id",  \$node);
		    $member->GetAttribute("iface", \$iface);

		    if ($myvlan->IsMember($node, $iface)) {
			my @pref;

			$myvlan->PortList(\@pref);

			# only two ports allowed in the vlan
			if (@pref != 2) {
			    warn "Vlan ".$myvlan->id()." doesnot have exact two ports.\n";
			    return -1;
			}
311
				       
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
			if ($pref[0] eq "$node:$iface") {
			    $ifacesonswitchnode{"$node:$iface"} = $pref[1];
			} else {
			    $ifacesonswitchnode{"$node:$iface"} = $pref[0];
			}
		    }
		}
	    }
	}
    }

    %$ifaces = %ifacesonswitchnode;
    return 0;
}


#
# Returns an array of ports (in node:card form) used by the given VLANs
#
331
sub getVlanPorts (@) { 
332 333 334 335 336 337 338
    my @vlans = @_;
    # Silently exit if they passed us no VLANs
    if (!@vlans) {
	return ();
    }
    my @ports = ();

339 340 341 342 343 344
    foreach my $vlanid (@vlans) {
	my $vlan = $vlanid;
	
	if (!ref($vlan)) {
	    $vlan = VLan->Lookup($vlanid);
	    if (!defined($vlan)) {
345 346
        	die("*** $0:\n".
		    "    No vlanid $vlanid in the DB!\n");
347 348
	    }
	}
349 350 351 352 353
    	my @members;
    	if ($vlan->MemberList(\@members) != 0) {
        	die("*** $0:\n".
		    "    Unable to load members for $vlan\n");
	}
354 355 356 357 358 359 360 361 362 363 364 365 366
	
	#
	# getPathVlanIfaces call removed because we've made
	# virtual ports and wires.
	#
	foreach my $member (@members) {
	    my $nodeid;
	    my $iface;
	    
	    if ($member->GetAttribute("node_id", \$nodeid) != 0 ||
		$member->GetAttribute("iface", \$iface) != 0) {
		die("*** $0:\n".
		    "    Missing attributes for $member in $vlan\n");
367
	    }
368 369
	    push(@ports, Port->LookupByIface($nodeid, $iface));
	}	
370
    }
371
    return @ports;
372 373
}

374 375 376 377 378 379 380
sub getExperimentTrunks($$@)
{
    my ($pid, $eid, @vlans) = @_;

    return getExperimentTrunksHelper(0, $pid, $eid, @vlans);
}

381 382
#
# Returns an an array of trunked ports (in node:card form) used by an
383 384
# experiment. These are ports that must be in trunk mode; whether they
# are currently *in* trunk mode is not relevant.
385
#
386
sub getExperimentTrunksHelper($$$@) {
387
    my ($current, $pid, $eid, @vlans) = @_;
388
    my %ports = ();
389

390 391 392 393 394 395 396 397
    # For debugging only.
    @vlans = getExperimentVlans($pid, $eid)
	if (!@vlans);

    my $experiment = Experiment->Lookup($pid, $eid);
    return undef
	if (!defined($experiment));

398 399
    #
    # We want to restrict the set of ports to just those in the
400 401 402 403
    # provided vlans, lest we get into a problem with a missing device from
    # the stack. This became necessary after adding shared vlans, since
    # those ports technically belong to the current experiment, but are
    # setup in the context of a different experiment.
404
    #
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    # Consider these different setups.
    # 1. Normal:
    #    The vlans and the ports belong to the experiment in question.
    # 2. Shared Nodes:
    #    There is a base vlan (dual mode) for the shared node experiment
    #    and all of the ports belong to that experiment. That vlan is setup
    #    at the beginning of time when swapping in the shared node
    #    experiment. When experiments that use the shared nodes are
    #    swapped, we never want to touch the port trunk mode, just add
    #    vlans to those ports since they will already be tagged.
    #    NOTE: Fake nodes (like ion) are also considered shared nodes,
    #    but in a different holding experiment. 
    # 3. Shared vlans:
    #    These vlans exist in a holding experiment, but the ports that we
    #    put into those vlans belong to nodes in other experiments.
    #    Basically the reverse of the situation above with shared nodes.
    #    We run snmpit in the context of the holding experiment, and so the
    #    ports we want to trunk belong to another experiment. See, exactly
    #    the opposite of above. Ick.
    #    NOTE: If we a shared vlan is being used by a shared node, we
    #    do not want to mess with trunk mode on those ports.
426
    #
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    # So the cases are:
    # 1. Swapin/Swapout normal experiment.
    # 2. Swapin/Swapout the shared node experiment.
    # 3. Swapin/Swapout experiments using shared nodes.
    # 4. Swapin/Swapout experiments using shared vlans.
    # 5. Swapin/Swapout experiments using shared nodes AND shared vlans.
    #
    # Remember, for 4 that we run snmpit in the context of the holding
    # experiment that owns the shared vlan. AND we run snmpit in the
    # context of the experiment swaping.
    #
    # So we have to check each node (its ports) in a vlan against the
    # current experiment. We skip those ports that do not belong to it if
    # the experiment they belong to is a shared node holding experiment).
    # We can determine this by looking in the reserved table for the node.
    # A physical node is a shared host and a virtual node is a shared node.
    # But if the port does not belong to it, is a shared vlan port, and
    # not a shared node port, we have to trunk/untrunk it!
    # 
446
    foreach my $vlanid (@vlans) {
Leigh B Stoller's avatar
Leigh B Stoller committed
447 448 449
	# Allow vlan list to be vlan objects.
	$vlanid = $vlanid->id()
	    if (ref($vlanid));
450 451 452

	my @vlanports =
	    ($current ? getExperimentVlanPorts($vlanid) :getVlanPorts($vlanid));
Leigh B Stoller's avatar
Leigh B Stoller committed
453
	
454
	foreach my $port (@vlanports) {
455 456 457 458 459
	    next
		if (!$port->trunk());

	    my $node = Node->Lookup($port->node_id());
	    if (!defined($node)) {
460 461
		print STDERR "*** getExperimentTrunks: ".
		    "*** No such node for $port\n";
462 463 464
		next;
	    }
	    my $reservation = $node->Reservation();
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
	    if (!defined($reservation)) {
		print STDERR "*** getExperimentTrunks: ".
		    "$node is not reserved!\n";
		next;
	    }

	    #
	    # Case #1 and #2.
	    #
	    if ($experiment->SameExperiment($reservation)) {
		$ports{$port->toString()} = $port;
		next;
	    }
	    #
	    # Case #3; skip ports belonging to a shared physical host.
	    # They are already in trunk mode and should be left alone,
	    # or we risk losing all of the vlans that port is tagged on. 
	    #
	    # XXX Sanity check to make sure?
	    #
485
	    next
486 487 488 489 490 491 492 493 494 495 496 497 498
		if ($node->sharing_mode());
	    
	    #
	    # Case #4: Running snmpit on a shared vlan, all ports belong
	    # to other experiments, they are need to be trunked, and we
	    # know from case #3 above that they are not shared hosts.
	    #
	    my $query_result =
		DBQueryFatal("select lanid from shared_vlans ".
			     "where lanid='$vlanid'");
	    if ($query_result->numrows) {
		$ports{$port->toString()} = $port;
		next;
499
	    }
500 501
	    print STDERR "*** getExperimentTrunks: ".
		"Do not know trunk mode for $port in $vlanid!\n";
502
	}
503
    }
504
    return %ports;
505 506 507 508 509 510 511
}

#
# Returns an an array of trunked ports (in node:card form) used by an
# experiment. These are the ports that are actually in trunk mode,
# rather then the ports we want to be in trunk mode (above function).
#
512 513
sub getExperimentCurrentTrunks($$@) {
    my ($pid, $eid, @vlans) = @_;
514
    my %ports = ();
515
    
516
    #
517
    # Get all of the ports we are allowed to act on from above function.
518
    #
519
    my %allports = getExperimentTrunksHelper(1, $pid, $eid, @vlans);
520

521 522 523 524 525 526 527
    #
    # Check which of these ports is actually in trunk mode. 
    #
    foreach my $key (keys(%allports)) {
	my $port    = $allports{$key};
	my $node_id = $port->node_id();
	my $iface   = $port->iface();
528
	
529 530 531 532
	my $query_result =
	    DBQueryFatal("select tagged from interface_state ".
			 "where node_id='$node_id' and iface='$iface' and ".
			 "      tagged!=0");
533

534 535
	next
	    if (! $query_result->numrows);
536

537
	$ports{$key} = $port;
538
    }
539
    return %ports;
540 541 542
}

#
543
# Returns an an array of ports that currently in
544 545
# the given vlan.
#
546
sub getExperimentVlanPorts($) { 
547 548 549 550 551 552 553 554 555 556 557
    my ($vlanid) = @_;

    my $query_result =
	DBQueryFatal("select members from vlans as v ".
		     "where v.id='$vlanid'");
    return ()
	if (!$query_result->numrows());

    my ($members) = $query_result->fetchrow_array();
    my @members   = split(/\s+/, $members);

558
    return Port->LookupByIfaces(@members); 
559 560 561 562 563 564
}

#
# Get the list of stacks that the given set of VLANs *will* or *should* exist
# on
#
565
sub getPlannedStacksForVlans(@) { 
566 567 568 569 570 571
    my @vlans = @_;

    # Get VLAN members, then go from there to devices, then from there to
    # stacks
    my @ports = getVlanPorts(@vlans);
    if ($debug) {
572
        print "getPlannedStacksForVlans: got ports " . Port->toStrings(@ports) . "\n";
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    }
    my @devices = getDeviceNames(@ports);
    if ($debug) {
        print("getPlannedStacksForVlans: got devices " . join(",",@devices)
            . "\n");
    }
    my @stacks = getStacksForSwitches(@devices);
    if ($debug) {
        print("getPlannedStacksForVlans: got stacks " . join(",",@stacks) . "\n");
    }
    return @stacks;
}

#
# Filter a set of vlans by devices; return only those vlans that exist
# on the set of provided stacks. Do not worry about vlans that cross
# stacks; that is caught higher up.
#
sub filterVlansBySwitches($@) {
    my ($devref, @vlans) = @_;
    my @result   = ();
    my %devices  = ();

    if ($debug) {
	print("filterVlansBySwitches: " . join(",", @{ $devref }) . "\n");
    }

    foreach my $device (@{ $devref }) {
	$devices{$device} = $device;
    }
    
    foreach my $vlanid (@vlans) {
	my @ports = getVlanPorts($vlanid);
	if ($debug) {
	    print("filterVlansBySwitches: ".
608
		  "ports for $vlanid: " . Port->toStrings(@ports) . "\n");
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
	}
	my @tmp = getDeviceNames(@ports);
	if ($debug) {
	    print("filterVlansBySwitches: ".
		  "devices for $vlanid: " . join(",",@tmp) . "\n");
	}
	foreach my $device (@tmp) {
	    if (exists($devices{$device})) {
		push(@result, $vlanid);
		last;
	    }
	}
    }
    return @result;
}

#
# Get the list of stacks that the given VLANs actually occupy
#
sub getActualStacksForVlans(@) {
    my @vlans = @_;

    # Run through all the VLANs and make a list of the stacks they
    # use
    my @stacks;
    foreach my $vlan (@vlans) {
        my ($vlanobj, $stack);
        if ($debug) {
            print("getActualStacksForVlans: looking up ($vlan)\n");
        }
        if (defined($vlanobj = VLan->Lookup($vlan)) &&
            defined($stack = $vlanobj->GetStack())) {

            if ($debug) {
                print("getActualStacksForVlans: found stack $stack in database\n");
            }
            push @stacks, $stack;
        }
    }
    return uniq(@stacks);
}

#
# Ditto for stack that VLAN exists on
#
sub setVlanStack($$) {
    my ($vlan_id, $stack_id) = @_;
    
    my $vlan = VLan->Lookup($vlan_id);
    return ()
	if (!defined($vlan));
    return ()
	if ($vlan->SetStack($stack_id) != 0);

    return 0;
}

#
# Update database to reserve a vlan tag. The tables will be locked to
# make sure we can get it. 
#
sub reserveVlanTag ($$) {
    my ($vlan_id, $tag) = @_;
    
    if (!$vlan_id || !defined($tag)) {
	return 0;
    }

    my $vlan = VLan->Lookup($vlan_id);
    return 0
	if (!defined($vlan));

    return $vlan->ReserveVlanTag($tag);
}

sub clearReservedVlanTag ($) {
    my ($vlan_id) = @_;
    
    my $vlan = VLan->Lookup($vlan_id);
    return -1
	if (!defined($vlan));

    return $vlan->ClearReservedVlanTag();
}

sub getReservedVlanTag ($) {
    my ($vlan_id) = @_;

    my $vlan = VLan->Lookup($vlan_id);
    return 0
	if (!defined($vlan));

    return $vlan->GetReservedVlanTag();
}

#
# Given a list of VLANs, return only the VLANs that are beleived to actually
# exist on the switches
#
sub filterPlannedVlans(@) {
    my @vlans = @_;
    my @out;
    foreach my $vlan (@vlans) {
        my $vlanobj = VLan->Lookup($vlan);
        if (!defined($vlanobj)) {
            warn "snmpit: Warning, tried to check status of non-existant " .
                "VLAN $vlan\n";
            next;
        }
        if ($vlanobj->CreatedOnSwitches()) {
            push @out, $vlan;
        }
    }
    return @out;
}

#
# Update database to mark port as enabled or disabled.
#
728
sub setPortEnabled($$) { 
729 730
    my ($port, $enabled) = @_;

731
    my ($node, $card) = ($port->node_id(), $port->card());
732 733 734 735 736 737 738
    $enabled = ($enabled ? 1 : 0);

    DBQueryFatal("update interface_state set enabled=$enabled ".
		 "where node_id='$node' and card='$card'");
    
    return 0;
}
739

740
# Ditto for trunked.
741
sub setPortTagged($$) { 
742 743
    my ($port, $tagged) = @_;

744
    my ($node, $card) = ($port->node_id(), $port->card());
745 746 747 748 749 750
    $tagged = ($tagged ? 1 : 0);

    DBQueryFatal("update interface_state set tagged=$tagged ".
		 "where node_id='$node' and card='$card'");
}

751 752 753 754 755 756 757 758 759 760 761 762 763
# Ditto for trunked.
sub IsPortTagged($) { 
    my ($port) = @_;

    my ($node, $card) = ($port->node_id(), $port->card());

    my $query_result =
	DBQueryFatal("select tagged from interface_state ".
		     "where node_id='$node' and card='$card' and tagged!=0");
    
    return $query_result->numrows();
}

764 765 766 767 768
#                                                                                    
# If a port is on switch, some port ops in snmpit                                    
# should be avoided.                                                                 
#                                                                                    
sub isSwitchPort($) {
769 770 771 772 773 774 775 776 777 778 779 780 781
	my $port = shift;

	my $node = $port->node_id();	
	my $result = DBQueryFatal("SELECT isswitch FROM node_types WHERE type IN ".
				  "(SELECT type FROM nodes WHERE node_id='$node')");
				  
	if ($result->numrows() != 1) {
	    return 0;
	}
	
	if (($result->fetchrow())[0] == 1) {
	    return 1;
	}
782

783
	return 0;
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
}

#
# Returns an array of all VLAN id's used by a given experiment.
# Optional list of vlan ids restricts operation to just those vlans,
#
sub getExperimentVlans ($$@) {
    my ($pid, $eid, @optvlans) = @_;

    my $experiment = Experiment->Lookup($pid, $eid);
    if (!defined($experiment)) {
	die("*** $0:\n".
	    "    getExperimentVlans($pid,$eid) - no such experiment\n");
    }
    my @vlans;
    if (VLan->ExperimentVLans($experiment, \@vlans) != 0) {
	die("*** $0:\n".
	    "    Unable to load VLANs for $experiment\n");
    }

    # Convert to how the rest of snmpit wants to see this stuff.
    my @result = ();
    foreach my $vlan (@vlans) {
	push(@result, $vlan->id())
	    if (!@optvlans || grep {$_ == $vlan->id()} @optvlans);
    }
    return @result;
}

#
# Returns an array of all ports used by a given experiment
#
sub getExperimentPorts ($$) {
    my ($pid, $eid) = @_;

    return getVlanPorts(getExperimentVlans($pid,$eid));
}

#
# Returns an array of control net ports used by a given experiment
#
sub getExperimentControlPorts ($$) {
    my ($pid, $eid) = @_;

    # 
    # Get a list of all *physical* nodes in the experiment
    #
    my $exp = Experiment->Lookup($pid,$eid);
    my @nodes = $exp->NodeList(0,0);
    # plab and related nodes are still in the list, so filter them out
    @nodes = grep {$_->control_iface()} @nodes; 

    #
    # Get control net interfaces
    #
839
    my @ports = map { Port->LookupByIface($_->node_id(), $_->control_iface()) } @nodes;
840 841 842 843

    #
    # Convert from iface to port number when we return
    #
844
    return @ports; 
845 846 847 848 849 850 851
}

#
# Usage: getDeviceNames(@ports)
#
# Returns an array of the names of all devices used in the given ports
#
852
sub getDeviceNames(@) { 
853 854 855
    my @ports = @_;
    my %devices = ();
    foreach my $port (@ports) {
Leigh B Stoller's avatar
Leigh B Stoller committed
856 857 858
	if (!defined($port)) {
	    die("getDeviceNames: undefined port");
	}
859
	my $device = $port->switch_node_id();
860 861 862 863

	$devices{$device} = 1;

        if ($debug) {
864
            print "getDevicesNames: Mapping ".$port->toTripleString()." to $device\n";
865 866 867 868 869 870 871 872 873
        }
    }
    return (sort {tbsort($a,$b)} keys %devices);
}

#
# Returns a hash, keyed by device, of all ports in the given list that are
# on that device
#
874
sub mapPortsToDevices(@) { 
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    my @ports = @_;
    my %map = ();
    foreach my $port (@ports) {
	my ($device) = getDeviceNames($port);
	if (defined($device)) { # getDeviceNames does the job of warning users
	    push @{$map{$device}},$port;
	}
    }
    return %map;
}

#
# Returns the device type for the given node_id
#
sub getDeviceType ($) {

    my ($node) = @_;

    my $result =
	DBQueryFatal("SELECT type FROM nodes WHERE node_id='$node'");

    my @row = $result->fetchrow();
    # Sanity check - make sure the node exists
    if (!@row) {
	die "No such node: $node\n";
    }

    return $row[0];
}

#
# Returns (current_speed,duplex) for the given interface (in node:port form)
#
908
sub getInterfaceSettings ($) { 
909 910 911 912 913 914 915 916 917

    my ($interface) = @_;

    #
    # Switch ports are evil and we don't touch them.
    #
    if (isSwitchPort($interface)) {
	return ();
    }
918 919
    
    my $node = $interface->node_id();
920
    my $card = $interface->card();
921
    my $port = $interface->port();
922 923 924 925 926 927 928

    my $result =
	DBQueryFatal("SELECT i.current_speed,i.duplex,ic.capval ".
		     "  FROM interfaces as i " .
		     "left join interface_capabilities as ic on ".
		     "     ic.type=i.interface_type and ".
		     "     capkey='noportcontrol' ".
929 930
		     "WHERE i.node_id='$node' and i.card=$card ".
		     "and i.port=$port");
931 932 933

    # Sanity check - make sure the interface exists
    if ($result->numrows() != 1) {
934
	die "No such interface: ".$interface->toString()."\n";
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    }
    my ($speed,$duplex,$noportcontrol) = $result->fetchrow_array();

    # If the port does not support portcontrol, ignore it.
    if (defined($noportcontrol) && $noportcontrol) {
	return ();
    }
    return ($speed,$duplex);
}

#
# Returns an array with then names of all switches identified as test switches
#
sub getTestSwitches () {
    my $result =
	DBQueryFatal("SELECT node_id FROM nodes WHERE role='testswitch'");
    my @switches = (); 
    while (my @row = $result->fetchrow()) {
953 954 955 956 957 958
	my $node = Node->Lookup($row[0]);
	my $disabled;
	$node->NodeAttribute("snmpit_disable", \$disabled);
	if (! defined($disabled) || !$disabled) {
	    push @switches, $row[0];
	}
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    }

    return @switches;
}

#
# Returns an array with the names of all switches identified as control switches
#
sub getControlSwitches () {
    my $result =
	DBQueryFatal("SELECT node_id FROM nodes WHERE role='ctrlswitch'");
    my @switches = (); 
    while (my @row = $result->fetchrow()) {
	push @switches, $row[0];
    }

    return @switches;
}

#
# Returns an array with the names of all switches in the given stack
#
sub getSwitchesInStack ($) {
    my ($stack_id) = @_;
    my $result = DBQueryFatal("SELECT node_id FROM switch_stacks " .
	"WHERE stack_id='$stack_id'");
    my @switches = (); 
    while (my @row = $result->fetchrow()) {
	push @switches, $row[0];
    }

    return @switches;
}

#
# Returns an array with the names of all switches in the given *stacks*, with
# no switches duplicated
#
sub getSwitchesInStacks (@) {
    my @stack_ids = @_;
    my @switches;
    foreach my $stack_id (@stack_ids) {
        push @switches, getSwitchesInStack($stack_id);
    }

    return uniq(@switches);
}

#
# Returns the stack_id of a switch's primary stack
#
sub getSwitchPrimaryStack($) {
    my $switch = shift;
    my $result = DBQueryFatal("SELECT stack_id FROM switch_stacks WHERE " .
    		"node_id='$switch' and is_primary=1");
    if (!$result->numrows()) {
1015 1016
	print STDERR "No primary stack_id found for switch $switch\n"
	    if ($debug);
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 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 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
	return undef;
    } elsif ($result->numrows() > 1) {
	print STDERR "Switch $switch is marked as primary in more than one " .
	    "stack\n";
	return undef;
    } else {
	my ($stack_id) = ($result->fetchrow());
	return $stack_id;
    }
}

#
# Returns the stack_ids of the primary stacks for the given switches.
# Surpresses duplicates.
#
sub getStacksForSwitches(@) {
    my (@switches) = @_;
    my @stacks;
    foreach my $switch (@switches) {
        push @stacks, getSwitchPrimaryStack($switch);
    }

    return uniq(@stacks);
}

#
# Returns a list of all stack_ids that a switch belongs to
#
sub getSwitchStacks($) {
    my $switch = shift;
    my $result = DBQueryFatal("SELECT stack_id FROM switch_stacks WHERE " .
    		"node_id='$switch'");
    if (!$result->numrows()) {
	print STDERR "No stack_id found for switch $switch\n";
	return undef;
    } else {
	my @stack_ids;
	while (my ($stack_id) = ($result->fetchrow())) {
	    push @stack_ids, $stack_id;
	}
	return @stack_ids;
    }
}

#
# Returns the type of the given stack_id. If called in list context, also
# returns whether or not the stack supports private VLANs, whether it
# uses a single VLAN domain, and the SNMP community to use.
#
sub getStackType($) {
    my $stack = shift;
    my $result = DBQueryFatal("SELECT stack_type, supports_private, " .
	"single_domain, snmp_community FROM switch_stack_types " .
	"WHERE stack_id='$stack'");
    if (!$result->numrows()) {
	print STDERR "No stack found called $stack\n";
	return undef;
    } else {
	my ($stack_type,$supports_private,$single_domain,$community)
	    = ($result->fetchrow());
	if (defined wantarray) {
	    return ($stack_type,$supports_private,$single_domain, $community);
	} else {
	    return $stack_type;
	}
    }
}

#
# Returns the leader for the given stack - the meaning of this is vendor-
# specific. May be undefined.
#
sub getStackLeader($) {
    my $stack = shift;
    my $result = DBQueryFatal("SELECT leader FROM switch_stack_types " .
	"WHERE stack_id='$stack'");
    if (!$result->numrows()) {
	print STDERR "No stack found called $stack\n";
	return undef;
    } else {
	my ($leader) = ($result->fetchrow());
	return $leader;
    }
}

#
# Get a hash that describes the configuration options for a switch. The idea is
# that the device's object will call this method to get some options.  Right
# now, all this stuff actually comes from the stack, but there could be
# switch-specific configuration in the future. Provides defaults for NULL
# columns
#
# We could probably make this look more like an object, for type checking, but
# that just doesn't seem necessary yet.
#
sub getDeviceOptions($) {
    my $switch = shift;
    my %options;

1116 1117 1118
    if (my $cached_options = $DeviceOptions{$switch}) {
	return $cached_options;
    }
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
    my $result = DBQueryFatal("SELECT supports_private, " .
	"single_domain, s.snmp_community as device_community, ".
        "t.min_vlan, t.max_vlan, " .
	"t.snmp_community as stack_community, ".
	"s.min_vlan as device_min, s.max_vlan as device_max ".
	"FROM switch_stacks AS s left join switch_stack_types AS t " .
	"    ON s.stack_id = t.stack_id ".
	"WHERE s.node_id='$switch'");

    if (!$result->numrows()) {
	print STDERR "No switch $switch found, or it is not in a stack\n";
	return undef;
    }

    my ($supports_private, $single_domain, $device_community, $min_vlan,
	$max_vlan, $stack_community, $device_min, $device_max) =
	    $result->fetchrow();

    $options{'supports_private'} = $supports_private;
    $options{'single_domain'} = $single_domain;
    $options{'snmp_community'} =
 	$device_community || $stack_community || "public";
    $options{'min_vlan'} = $device_min || $min_vlan || 2;
    $options{'max_vlan'} = $device_max || $max_vlan || 1000;

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    my $type = $options{'type'} = getDeviceType($switch);

    my $q = "(select \"default\" source, attrkey, attrvalue from ".
	    "node_type_attributes where type='$type' ".
	    "and attrkey like 'snmpit%') union ".
	    "(select \"override\" source, attrkey, attrvalue from ".
	    "node_attributes where node_id='$switch' ".
	    "and attrkey like 'snmpit%') order by source";
	   
    $result = DBQuery($q);
    if ($result && $result->numrows()) {
	while (my ($source, $key, $value) = $result->fetchrow()) {
		$key =~ s/^snmpit_//;
		$options{$key} = $value;
	}
    }
    $DeviceOptions{$switch} = \%options;
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

    if ($debug) {
	print "Options for $switch:\n";
	while (my ($key,$value) = each %options) {
	    print "$key = $value\n"
	}
    }

    return \%options;
}

1172 1173 1174 1175 1176 1177 1178
sub ReadDeviceOptions() {
    my $result = DBQuery("select distinct node_id from switch_stacks");
    print STDERR "No switch found in any stack\n"
	unless ($result && $result->numrows());
    while (my ($switch) = $result->fetchrow()) { getDeviceOptions($switch); }
}

1179 1180 1181 1182 1183 1184 1185 1186
#
# Returns a structure representing all trunk links. It's a hash, keyed by
# switch, that contains hash references. Each of the second level hashes
# is keyed by destination, with the value being an array reference that
# contains the card.port pairs to which the trunk is conencted. For exammple,
# ('cisco1' => { 'cisco3' => ['1.1','1.2'] },
#  'cisco3' => { 'cisco1' => ['2.1','2.2'] } )
#
1187 1188 1189
# After port refactoring:
# ( 'src' => { 'dst' => [ port1, port2 ] }, ... )
#
1190 1191 1192
sub getTrunks() {

    my %trunks = ();
1193 1194 1195 1196 1197
    
    my @ports = Port->LookupByWireType("Trunk");
    
    foreach my $p (@ports) {
	    push @{ $trunks{$p->node_id()}{$p->other_end_node_id()} }, $p;
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    }

    return %trunks;
	
}

#
# Find the best path from one switch to another. Returns an empty list if no
# path exists, otherwise returns a list of switch names. Arguments are:
# A reference to a hash, as returned by the getTrunks() function
# A reference to an array of unvisited switches: Use [keys %trunks]
# Two siwtch names, the source and the destination 
#
sub getTrunkPath($$$$) {
    my ($trunks, $unvisited, $src,$dst) = @_;
    if ($src eq $dst) {
	#
	# The source and destination are the same
	#
	return ($src);
    } elsif ($trunks->{$src}{$dst}) {
	#
	# The source and destination are directly connected
	#
	return ($src,$dst);
    } else {
	# The source and destination aren't directly connected. We'll need to 
	# recurse across other trunks to find solution
	my @minPath = ();

	#
	# We use the @$unvisited list to pick switches to traverse to, so
	# that we don't re-visit switches we've already been to, which would 
	# cause infinite recursion
	#
	foreach my $i (0 .. $#{$unvisited}) {
	    if ($trunks->{$src}{$$unvisited[$i]}) {

		#
		# We need to pull theswitch out of the unvisted list that we
		# pass to it.
		#
		my @list = @$unvisited;
		splice(@list,$i,1);

		#
		# Check to see if the path we get with this switch is the 
		# best one found so far
		#
		my @path = getTrunkPath($trunks,\@list,$$unvisited[$i],$dst);
		if (@path && ((!@minPath) || (@path < @minPath))) {
		    @minPath = @path;
		}
	    }

	}

	#
	# If we found a path, tack ourselves on the front and return. If not,
	# return the empty list of failure.
	#
	if (@minPath) {
	    return ($src,@minPath);
	} else {
	    return ();
	}
    }
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
#
# This is a replacement for getTrunksFromSwitches, used by the stack
# module.  The idea is to use the path in the DB, as computed by
# assign. Fall back to old method method if no path defined in the DB.
# We need the switches in case we fall back, otherwise we do what
# the DB says (as computed by assign), ignoring the switches. 
#
sub getTrunksForVlan($@)
{
    my ($vlan_id, @switches) = @_;
    my %trunks = getTrunks();
    
    my $vlan = VLan->Lookup($vlan_id);
    return ()
	if (!defined($vlan));

    print STDERR "getTrunksForVlan: $vlan_id: @switches\n";
    
    #
    # We want to use the path that is in the DB.
    #
    my $path = $vlan->GetSwitchPath();
    if (!defined($path) || $path eq "") {
	#
	# Nothing defined in the DB, so fall back to old method.
	#
	# One switch, cannot be a path.
	# 
	return ()
	    if (scalar(@switches) < 2);
	
	my @trunks = getTrunksFromSwitches(\%trunks, @switches);

	#
	# Now form a spanning tree to ensure there are no loops.
	#
	@trunks = SpanningTree(\@trunks);

	print STDERR " old style path: " .
	    join(" ", map { join(":", @$_) } @trunks) . "\n";
	return @trunks;
    }
    print STDERR " DB path: $path\n";
    my @path = ();
    foreach my $p (split(" ", $path)) {
	my ($a,$b) = split(":", $p);
	if (!exists($trunks{$a})) {
	    print STDERR "No trunk entry for $a\n";
	    next;
	}
	if (!exists($trunks{$a}->{$b})) {
	    print STDERR "No trunk entry for $a:$b\n";
	    next;
	}
	push(@path, [$a, $b]);
    }
    if (@path) {
	print STDERR " new style path: ".
	    join(" ", map { join(":", @$_) } @path) . "\n";
    }
    return @path;
}

#
# Same as above, only we want the recorded switch path from vlans table,
# since this might be a swapmod and the contents of the lans table is
# not how things are now, but how they will be later. 
#
sub getExperimentTrunksForVlan($@)
{
    my ($vlan_id, @switches) = @_;
    my %trunks = getTrunks();
    
    my $vlan = VLan->Lookup($vlan_id);
    return ()
	if (!defined($vlan));

    print STDERR "getExperimentTrunksForVlan: $vlan_id: @switches\n";

    #
    # We want to use the path that is in the DB.
    #
    my $path = VLan->GetVlanSwitchPath($vlan);
    if (!defined($path) || $path eq "") {
	#
	# Nothing defined in the DB, so fall back to old method.
	#
	# One switch, cannot be a path.
	# 
	return ()
	    if (scalar(@switches) < 2);
	
	my @trunks = getTrunksFromSwitches(\%trunks, @switches);

	#
	# Now form a spanning tree to ensure there are no loops.
	#
	@trunks = SpanningTree(\@trunks);

	print STDERR " old style path: " .
	    join(" ", map { join(":", @$_) } @trunks) . "\n";
	return @trunks;
    }
    print STDERR " DB path: $path\n";
    my @path = ();
    foreach my $p (split(" ", $path)) {
	my ($a,$b) = split(":", $p);
	if (!exists($trunks{$a})) {
	    print STDERR "No trunk entry for $a\n";
	    next;
	}
	if (!exists($trunks{$a}->{$b})) {
	    print STDERR "No trunk entry for $a:$b\n";
	    next;
	}
	push(@path, [$a, $b]);
    }
    if (@path) {
	print STDERR " new style path: ".
	    join(" ", map { join(":", @$_) } @path) . "\n";
    }
    return @path;
}

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
#
# Given a set of vlans, determine *exactly* what devices are needed
# for the ports and any trunks that need to be crossed. This is done
# in the stack module, but really want to do this before the stack
# is created so that we do not add extra devices if not needed.
#
sub mapVlansToSwitches(@)
{
    my @vlan_ids = @_;
    my %switches = ();

    #
    # This code is lifted from setPortVlan() in snmpit_stack.pm
    #
    foreach my $vlan_id (@vlan_ids) {
1406
	my @ports   = uniq_ports(getVlanPorts($vlan_id),
1407 1408 1409
				 getExperimentVlanPorts($vlan_id));
	my %map     = mapPortsToDevices(@ports);

1410 1411 1412 1413 1414 1415 1416
	#
	# Initial set of switches.
	#
	foreach my $switch (keys(%map)) {
	    $switches{$switch} = 1;
	}

1417 1418 1419 1420
	#
	# We want to use the DB path if it exists.
	#
	my @trunks = getTrunksForVlan($vlan_id, keys(%map));
1421 1422

	# And update the total set of switches.
1423 1424 1425
	foreach my $trunk (@trunks) {
	    my ($src,$dst) = @$trunk;
	    $switches{$src} = $switches{$dst} = 1;
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
	}
    }
    my @sorted = sort {tbsort($a,$b)} keys %switches;
    print "mapVlansToSwitches: @sorted\n";
    return @sorted;
}

#
# An alternate version for a "stale" vlan; one that is destroyed cause of
# a swapmod (syncVlansFromTables). 
#
sub mapStaleVlansToSwitches(@)
{
    my @vlan_ids = @_;
    my %switches = ();

    foreach my $vlan_id (@vlan_ids) {
	#
	# Get the ports that we think are already in the vlan, since
	# this might be a remove/modify operation. Can probably optimize
	# this. 
	#
	my @ports   = getExperimentVlanPorts($vlan_id);
1449 1450
	my %map     = mapPortsToDevices(@ports);

1451 1452 1453 1454 1455 1456 1457
	#
	# Initial set of switches.
	#
	foreach my $switch (keys(%map)) {
	    $switches{$switch} = 1;
	}

1458 1459 1460 1461
	#
	# We want to use the DB path if it exists.
	#
	my @trunks = getExperimentTrunksForVlan($vlan_id, keys(%map));
1462 1463

	# And update the total set of switches.
1464 1465 1466
	foreach my $trunk (@trunks) {
	    my ($src,$dst) = @$trunk;
	    $switches{$src} = $switches{$dst} = 1;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
	}
    }
    my @sorted = sort {tbsort($a,$b)} keys %switches;
    print "mapStaleVlansToSwitches: @sorted\n";
    return @sorted;
}

#
# Map a set of ports to the devices they are on plus the trunks.
# See above.
#
sub mapPortsToSwitches(@)
{
    my @ports    = @_;
    my %switches = ();
    my %trunks   = getTrunks();
    my %map      = mapPortsToDevices(@ports);
    my %devices  = ();
1485 1486 1487 1488 1489 1490

    #
    # Watch for one device, no trunks to worry about.
    #
    return (keys(%map))
	if (scalar(keys(%map)) == 1);
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    
    foreach my $device (keys %map) {
	$devices{$device} = 1;
    }

    #
    # This code is lifted from setPortVlan() in snmpit_stack.pm
    #
    # Find every switch which might have to transit this VLAN through
    # its trunks.
    #
    my @trunks = getTrunksFromSwitches(\%trunks, keys %devices);
1503 1504 1505 1506 1507 1508

    #
    # Now form a spanning tree to ensure there are no loops.
    #
    @trunks = SpanningTree(\@trunks);
    
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
    foreach my $trunk (@trunks) {
	my ($src,$dst) = @$trunk;
	$devices{$src} = $devices{$dst} = 1;
    }
    # And update the total set of switches.
    foreach my $device (keys(%devices)) {
	$switches{$device} = 1;
    }
    my @sorted = sort {tbsort($a,$b)} keys %switches;
    return @sorted;
}

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
#
# 
#
sub setSwitchTrunkPath($)
{
    my ($vlan) = @_;
    my %switches = ();

    my @ports   = getVlanPorts($vlan->lanid());
    my %map     = mapPortsToDevices(@ports);
    my @trunks  = getTrunksForVlan($vlan->lanid(), keys(%map));
    my $path    = join(" ", map { join(":", @$_) } @trunks);

    return $vlan->SetSwitchPath($path);
}

1537 1538 1539 1540 1541 1542
#
# Returns a list of trunks, in the form [src, dest], from a path (as returned
# by getTrunkPath() ). For example, if the input is:
# (cisco1, cisco3, cisco4), the return value is:
# ([cisco1, cisco3], [cisco3, cisco4])
#
1543
sub getTrunksFromPath(@) { 
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
    my @path = @_;
    my @trunks = ();
    my $lastswitch = "";
    foreach my $switch (@path) {
	if ($lastswitch) {
	    push @trunks, [$lastswitch, $switch];
	}
	$lastswitch = $switch;
    }

    return @trunks;
}

#
# Given a list of lists of trunks (returned by multiple getTrunksFromPath() 
# calls), return a list of the unique trunks found in this list
#
1561
sub getUniqueTrunks(@) { 
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
    my @trunkLists = @_;
    my @unique = ();
    foreach my $trunkref (@trunkLists) {
	my @trunks = @$trunkref;
	TRUNK: foreach my $trunk (@trunks) {
	    # Since source and destination are interchangable, we have to
	    # check both possible orderings
	    foreach my $unique (@unique) {
		if ((($unique->[0] eq $trunk->[0]) &&
		     ($unique->[1] eq $trunk->[1])) ||
		    (($unique->[0] eq $trunk->[1]) &&
		     ($unique->[1] eq $trunk->[0]))) {
			 # Yep, it's already in the list - go to the next one
			 next TRUNK;
		}
	    }

	    # Made it through, we must not have seen this one before
	    push @unique, $trunk;
	}
    }

    return @unique;
}

#
# Given a trunk structure (as returned by getTrunks() ), and a list of switches,
# return a list of all trunks (in the [src, dest] form) that are needed to span
# all the switches (ie. which trunks the VLAN must be allowed on)
#
1592
sub getTrunksFromSwitches($@) { 
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    my $trunks = shift;
    my @switches = @_;

    #
    # First, find the paths between each set of switches
    #
    my @paths = ();
    foreach my $switch1 (@switches) {
	foreach my $switch2 (@switches) {
	    push @paths, [ getTrunkPath($trunks, [ keys %$trunks ],
					$switch1, $switch2) ];
	}
    }

    #
    # Now, make a list of all the the trunks used by these paths
    #
    my @trunkList = ();
    foreach my $path (@paths) {
	push @trunkList, [ getTrunksFromPath(@$path) ];
    }

    #
1616
    # Remove any duplicates from the list of trunks
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    #
    my @trunks = getUniqueTrunks(@trunkList);

    return @trunks;
}

#
# Make a hash of all trunk ports for easy checking - the keys into the hash are
# in the form "switch/mod.port" - the contents are 1 if the port belongs to a
# trunk, and undef if not
#
# ('cisco1' => { 'cisco3' => ['1.1','1.2'] },
#  'cisco3' => { 'cisco1' => ['2.1','2.2'] } )
#
1631
sub getTrunkHash() { 
1632 1633 1634 1635 1636
    my %trunks = getTrunks();
    my %trunkhash = ();
    foreach my $switch1 (keys %trunks) {
        foreach my $switch2 (keys %{$trunks{$switch1}}) {
            foreach my $port (@{$trunks{$switch1}{$switch2}}) {
1637 1638
                # XXX backward compat
                my $portstr = "$switch1/".$port->card().".".$port->port();
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 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
                $trunkhash{$portstr} = 1;
            }
        }
    }
    return %trunkhash;
}

#
# Execute and SNMP command, retrying in case there are transient errors.
#
# usage: snmpitDoIt(getOrSet, session, var, [retries])
# args:  getOrSet - either $SNMPIT_GET or $SNMPIT_SET
#        session - SNMP::Session object, already connected to the SNMP
#                  device
#        var     - An SNMP::Varbind or a reference to a two-element array
#                  (similar to a single Varbind)
#        retries - Number of times to retry in case of failure
# returns: the value on sucess, undef on failure
#
sub snmpitDoIt($$$;$) {

    my ($getOrSet,$sess,$var,$retries) = @_;

    if (! defined($retries) ) {
	$retries = $DEFAULT_RETRIES;
    }

    #
    # Make sure we're given valid inputs
    #
    if (!$sess) {
	$snmpitErrorString = "No valid SNMP session given!\n";
	return undef;
    }

    my $array_size;
    if ($getOrSet == $SNMPIT_GET) {
	$array_size = 2;
    } elsif ($getOrSet == $SNMPIT_BULKWALK) {
	$array_size = 1;
    } else {
	$array_size = 4;
    }

    if (((ref($var) ne "SNMP::Varbind") && (ref($var) ne "SNMP::VarList")) &&
	    ((ref($var) ne "ARRAY") || ((@$var != $array_size) && (@$var != 4)))) {
	$snmpitErrorString = "Invalid SNMP variable given ($var)!\n";
	return undef;
    }

    #
    # Retry several times
    #
    foreach my $retry ( 1 .. $retries) {
	my $status;
        my @return;
	if ($getOrSet == $SNMPIT_GET) {
	    $status = $sess->get($var);
	} elsif ($getOrSet == $SNMPIT_BULKWALK) {
	    @return = $sess->bulkwalk(0,32,$var);
	} else {
	    $status = $sess->set($var);
	}

	#
	# Avoid unitialized variable warnings when printing errors
	#
	if (! defined($status)) {
	    $status = "(undefined)";
	}

	#
	# We detect errors by looking at the ErrorNumber variable from the
	# session
	#
	if ($sess->{ErrorNum}) {
	    my $type;
	    if ($getOrSet == $SNMPIT_GET) {
		$type = "get";
	    } elsif ($getOrSet == $SNMPIT_BULKWALK) {
		$type = "bulkwalk";
	    } else {
		$type = "set";
	    }
	    $snmpitErrorString  = "SNMPIT $type failed for device " .
                "$sess->{DestHost} (try $retry of $retries)\n";
            $snmpitErrorString .= "Variable was " .  printVars($var) . "\n";
	    $snmpitErrorString .= "Returned $status, ErrorNum was " .
		   "$sess->{ErrorNum}\n";
	    if ($sess->{ErrorStr}) {
		$snmpitErrorString .= "Error string is: $sess->{ErrorStr}\n";
	    }
	} else {
	    if ($getOrSet == $SNMPIT_GET) {
		return $var->[2];
	    } elsif ($getOrSet == $SNMPIT_BULKWALK) {
                return @return;
	    } else {
	        return 1;
	    }
	}

	#
	# Don't flood requests too fast. Randomize the sleep a little so that
	# we don't end up with all our retries coming in at the same time.
	#
        sleep(1);
	select(undef, undef, undef, rand(1));
    }

    #
    # If we made it out, all of the attempts must have failed
    #
    return undef;
}

#
# usage: snmpitGet(session, var, [retries])
# args:  session - SNMP::Session object, already connected to the SNMP
#                  device
#        var     - An SNMP::Varbind or a reference to a two-element array
#                  (similar to a single Varbind)
#        retries - Number of times to retry in case of failure
# returns: the value on sucess, undef on failure
#
sub snmpitGet($$;$) {
    my ($sess,$var,$retries) = @_;
    my $result;

    $result = snmpitDoIt($SNMPIT_GET,$sess,$var,$retries);

    return $result;
}

#
# Same as snmpitGet, but send mail if any error occur
#
sub snmpitGetWarn($$;$) {
    my ($sess,$var,$retries) = @_;
    my $result;

    $result = snmpitDoIt($SNMPIT_GET,$sess,$var,$retries);

    if (! defined $result) {
	snmpitWarn("SNMP GET failed");
    }
    return $result;
}

#
# Same as snmpitGetWarn, but also exits from the program if there is a 
# failure.
#
sub snmpitGetFatal($$;$) {
    my ($sess,$var,$retries) = @_;
    my $result;

    $result = snmpitDoIt($SNMPIT_GET,$sess,$var,$retries);

    if (! defined $result) {
	tbreport(SEV_ERROR, 'snmp_get_fatal');
	snmpitFatal("SNMP GET failed");
    }
    return $result;
}

#
# usage: snmpitSet(session, var, [retries])
# args:  session - SNMP::Session object, already connected to the SNMP
#                  device
#        var     - An SNMP::Varbind or a reference to a two-element array
#                  (similar to a single Varbind)
#        retries - Number of times to retry in case of failure
# returns: true on success, undef on failure
#
sub snmpitSet($$;$) {
    my ($sess,$var,$retries) = @_;
    my $result;

    $result = snmpitDoIt($SNMPIT_SET,$sess,$var,$retries);

    return $result;
}

#
# Same as snmpitSet, but send mail if any error occur
#
sub snmpitSetWarn($$;$) {
    my ($sess,$var,$retries) = @_;
    my $result;

    $result = snmpitDoIt($SNMPIT_SET,$sess,$var,$retries);

    if (! defined $result) {
	snmpitWarn("SNMP SET failed");
    }
    return $result;
}

#
# Same as snmpitSetWarn, but also exits from the program if there is a 
# failure.
#
sub snmpitSetFatal($$;$) {
    my ($sess,$var,$retries) = @_;
    my $result;

    $result = snmpitDoIt($SNMPIT_SET,$sess,$var,$retries);

    if (! defined $result) {
	tbreport(SEV_ERROR, 'snmp_set_fatal');
	snmpitFatal("SNMP SET failed");
    }
    return $result;
}

#
# usage: snmpitBulkwalk(session, var, [retries])
# args:  session - SNMP::Session object, already connected to the SNMP
#                  device
#        var     - An SNMP::Varbind or a reference to a single-element array
#        retries - Number of times to retry in case of failure
# returns: an array of values on success, undef on failure
#
sub snmpitBulkwalk($$;$) {
    my ($sess,$var,$retries) = @_;
    my @result;

    @result = snmpitDoIt($SNMPIT_BULKWALK,$sess,$var,$retries);

    return @result;
}

#
# Same as snmpitBulkwalk, but send mail if any errors occur
#
sub snmpitBulkwalkWarn($$;$) {
    my ($sess,$var,$retries) = @_;
    my @result;

    @result = snmpitDoIt($SNMPIT_BULKWALK,$sess,$var,$retries);

    if (! @result) {
	snmpitWarn("SNMP Bulkwalk failed");
    }
    return @result;
}

#
# Same as snmpitBulkwalkWarn, but also exits from the program if there is a 
# failure.
#
sub snmpitBulkwalkFatal($$;$) {
    my ($sess,$var,$retries) = @_;
    my @result;

    @result = snmpitDoIt($SNMPIT_BULKWALK,$sess,$var,$retries);

    if (! @result) {
	snmpitFatal("SNMP Bulkwalk failed");
    }
    return @result;
}

#
# Print out SNMP::VarList and SNMP::Varbind structures. Useful for debugging
#
sub printVars($) {
    my ($vars) = @_;
    if (!defined($vars)) {
	return "[(undefined)]";
    } elsif (ref($vars) eq "SNMP::VarList") {
	return "[" . join(", ",map( {"[".join(",",@$_)."\]";}  @$vars)) . "]";
    } elsif (ref($vars) eq "SNMP::Varbind") {
	return "[" . join(",",@$vars) . "]";
    } elsif (ref($vars) eq "ARRAY") {
	return "[" . join(",",map( {defined($_)? $_ : "(undefined)"} @$vars))
		. "]";
    } else {
	return "[unknown value]";
    }
}

#
# Both print out an error message and mail it to the testbed ops. Prints out
# the snmpitErrorString set by snmpitGet.
#
# usage: snmpitWarn(message,fatal)
#
sub snmpitWarn($$) {

    my ($message,$fatal) = @_;

    #
    # Untaint $PRORAM_NAME
    #
    my $progname;
    if ($PROGRAM_NAME =~ /^([-\w.\/]+)$/) {
	$progname = $1;
    } else {
	$progname = "Tainted";
    }

    my $text = "$message - In $progname\n" .
    	       "$snmpitErrorString\n";
	
    if ($fatal) {
        tbdie({cause => 'hardware'}, $text);
    } else {
        tbwarn({cause => 'hardware'}, $text);
    }

}

#
# Like snmpitWarn, but die too
#
sub snmpitFatal($) {
    my ($message) = @_;
    snmpitWarn($message,1);
}

#
# Used to sort a set of nodes in testbed order (ie. pc2 < pc10)
#
# usage: tbsort($a,$b)
#        returns -1 if $a < $b
#        returns  0 if $a == $b
#        returns  1 if $a > $b
#
sub tbsort { 
    my ($a,$b) = @_;
    $a =~ /^([a-z]*)([0-9]*):?([0-9]*)/;
    my $a_let = ($1 || "");
    my $a_num = ($2 || 0);
    my $a_num2 = ($3 || 0);
    $b =~ /^([a-z]*)([0-9]*):?([0-9]*)/;
    my $b_let = ($1 || "");
    my $b_num = ($2 || 0);
    my $b_num2 = ($3 || 0);
    if ($a_let eq $b_let) {
	if ($a_num == $b_num) {
	    return $a_num2 <=> $b_num2;
	} else {
	    return $a_num <=> $b_num;
	}
    } else {
	return $a_let cmp $b_let;
    }
    return 0;
}


#
# Silly helper function - returns its input array with duplicates removed
# (ordering is likely to be changed)
#
sub uniq(@) {
    my %elts;
    foreach my $elt (@_) { $elts{$elt} = 1; }
    return keys %elts;
}

2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
#                                                                                                                                                                                                                  
# uniq for ports
#                                                                                                                                                                                                                  
sub uniq_ports(@) {
    my %elts;
    my @pts;
    foreach my $p (@_) {
        if (!exists($elts{$p->toString()})) {
            $elts{$p->toString()} = 1;
            push @pts, $p;
	}
    }
    return @pts;
}


2018 2019 2020
# End with true
1;