snmpit_test.in 102 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/perl -w
#
# EMULAB-LGPL
# Copyright (c) 2000-2011 University of Utah and the Flux Group.
# All rights reserved.
#

#
# snmpit - A tool for setting up VLANs on SNMP-controllable switches
#

#
# Configure variables
#
my $TESTMODE   = @TESTMODE@;
my $ELABINELAB = @ELABINELAB@;
my $NOSTACKMIB = @NOSTACKMIB@;
my $MAINSITE   = @TBMAINSITE@;
my $TB = '@prefix@';

21
use lib '@prefix@/lib';
22 23 24 25 26 27 28 29
use libdb;
use User;
use Experiment;
use libtblog;
use EmulabFeatures;
use Lan;
use English;
use Getopt::Long;
30
use emutil;
31 32
use strict;

33 34 35 36 37
# Optional alternate version of libraries.
use lib '@prefix@/lib/snmpit_test';
use snmpit_lib;
use snmpit_remote;

38 39
# Protos
sub parseStatusString($);
40
sub filterList($$);
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
sub debug($);
sub doListVlans($);
sub doListPorts($);
sub doPortStatus($@);
sub doGetStats($);
sub doVlansFromTables($$@);
sub syncVlansFromTables($$);
sub doSyncVlansWithDB($);
sub doReset($@);
sub doMakeVlan($$@);
sub doDeleteVlan($@);
sub doVlanNumber($$);
sub doPortControl($$@);
sub doRecreateVlans($);
sub doTrunkEnable($$$@);
sub doTrunkDisable($$);
sub doRestorePortStatus($@);
sub doSynchLeader($);
sub CreateOneVlan($$$@);
sub doOpenflowEnable($$);
sub doOpenflowDisable($$);
sub doSetOpenflowController($$$);
sub doSetOpenflowListener($$$);
sub doEnableOpenflowListener($$);
sub doReserveVlanTags($$@);
sub doUnReserveVlanTags($$@);

#
# Defaults
#
my $debug = 0;
my $quiet = 0;
my $impotent = 0;
my $minOpenflowListenerPort = 5000;
my $maxOpenflowListenerPort = 65535;

######################################################################
# Step 1 - Process command-line arguments
#
# We have a fairly complex set of command line arguments, and we
# need to make sure that the user only specifies one command at a
# time.
######################################################################
sub usage {
    print << "END";
Usage: $0 [-h] [-v level] [-q] [-n] [-i device] [-S stack]
	  [-l] [-s] [-g] [-O]
	  [-m name pid eid [ports]]
	  [-T port name]
	  [-U port]
	  [-o name pid eid]
          [-N name]
          [-r pid eid]
	  [-t pid eid]
	  [-d ports] [-e ports] [-a ports]
	  [-p <10|100|1000> ports] [-u <half|full> ports]
	  [-c]
          [--redirect-err]
          [--of-disable vlanid pid eid]
          [--of-enable vlanid pid eid]
          [--of-controller vlanid pid eid tcp:ip:port]
          [--of-listener vlanid pid eid]
General:
  -h              Display this help message
  -v <level>      Verbose mode
  -q              Quiet mode
  -n              Test mode - don't actually make any changes
  -i <device>     Operate on <device>, overriding default device list. Can be
                      given multiple times
  -S <stack>      Operate on the given stack, instead of the default of the
                      experimental network
112 113
  --skip-supplied If the -S option was given, start with the default stacks, 
                      but skip any switches in the stacks listed in -S.
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  --redirect-err  Redirect STDERR to STDOUT, for easier capturing in logfiles

VLAN Control:
  -t <pid> <eid>    Create all VLANs for an experiment
  -r <pid> <eid>    Remove all VLANs for an experiment
                        (you can provide an optional list of vlan ids)
  -l                List all VLANs associated with experiments.
                        A second -l will list ALL vlans.
  -w                Used with -l, includes device-specific VLAN number
  -M                Used with -l, print MAC addresses instead of port numbers
  -O                Used with -l, list only orphaned VLANs
  -L <out#in[,o2#i2,...]> stylized -l for snmpit.proxy of specific vlans
  -m <name> <pid> <eid> [ports]
                    Create a new VLAN with name <name>, if it doesn't exist,
                        and put [ports] in it. The new VLAN will be
                        associated with the priject and experiment given
  -y <type>         When used with -m, the new VLAN becomes a private VLAN
                        of type <type>
  -x <primary>      When used with -y, assocates the new private VLAN with
                        the primary VLAN named <primary>
  -z <port>         Used with -y and -x, to specify which port is to be used
                        with the private VLAN
  -o <name> <pid> <eid>
                    Delete the VLAN with name <name>, which is associated with
                        the given experiment
  -N <name>         Print out the VLAN number for the named VLAN
  -c                Delete ALL VLANs, and recreate from the database. ** USE
                        WITH EXTREME CAUTION **
  -F                Create all vlans in the given stack on the leader for
		    use in leader->{ALLVLANSONLEADER} (Internal use only)
  --of-enable <vlanid> <pid> <eid> 
                    Enable Openflow on VLAN with the id <vlanid> that is 
		        associated with the given experiment 
  --of-disable <vlanid> <pid> <eid>
                    Disable Openflow on VLAN with the id <vlanid> that is 
		        associated with the given experiment
  --of-controller <vlanid> <pid> <eid> tcp:ip:port
                    Set controller for Openflow-enabled VLAN with the 
		        id <vlanid> that is associated with the given 
			experiment
  --of-listener <vlanid> <pid> <eid> 
                    Enable listener for Openflow-enabled VLAN with the 
		        id <vlanid> that is associated with the given 
			experiment, snmpit will print out the listener 
			connection string

Port Control:
  -s                     List all ports, and show configuration information
  -g                     Get port statistics
  -d <ports>             Disable <ports>
  -e <ports>             Enable <ports>
  -a <ports>             Enable auto-negotiation of port speed/duplex
  -p <10|100> <ports>    Set speed of <ports> to 10 or 100 Mbps
  -u <half|full> <ports> Set duplex of <ports> to half or full
  -T <port> <names>      Enable trunking on the given <port>, and allow VLANs
                             with the given <names> across it
  -E <port> <names>      Like -T, but "Equal" mode; PVID is also tagged
  -U <port>              Turn off trunking for the given <port>
  -b <ports>             Print out port status for a set of ports
  -B <statstring>        Pass in a stat string from -b to restore status
  -D <pid> <eid>         Disable all control net ports for an experiment
  -R <pid> <eid>         (Re)enable all control net ports for an experiment

More than one operation can be specified - However, beware that the order in
which operations will occur is undefined, and some combinations of operations
(ie. -d and -e) are non-sensical.
END

    return 1;
}

my @SAVEARGV = @ARGV;
my %opt = ();
Getopt::Long::Configure("no_ignore_case");
GetOptions(\%opt,
    'a','c','d','e','b','B=s@','g','h','i=s@','l+','m=s@','M','n', 'A', 'C',
    'N=s@','p=s','q','r','s', 'S=s@','t','E=s','T=s','u=s','U','v=s','w',
    'y=s','x=s','z=s','F','L=s','O', 'D', 'R', 'f', 'X', 'Z', 'vlan_tag=i', 
    'of-disable=s', 'of-enable=s', 'of-controller=s', 'of-listener=s',
    'o=s@{1,1}', 'redirect-err', 'blockmode', 'syncvlans', 'impotent',
194
    'shadow', 'skip-supplied', 'whol-magic', 'backtraceonwarning');
195 196 197 198 199 200 201 202 203 204 205 206

if ($opt{h}) {
    exit &usage;
}

#
# If requested, redirect STDERR to STDOUT - this makes it easier to capture
# error output in logfiles
#
if ($opt{'redirect-err'}) {
    open(STDERR, ">&STDOUT");
}
207 208 209
if ($opt{'backtraceonwarning'}) {
    BackTraceOnWarning(1);
}
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
if ($opt{'impotent'}) {
    $impotent = 1;
}

if ($opt{v}) {
    $debug = $opt{v};
    print "Debug level is $debug\n";
}

if ($opt{q}) {
    $quiet = 1;
    if ($opt{m} || $opt{o} || $opt{t} || $opt{r} || $opt{X} || $opt{T} ||
	  $opt{E} || $opt{U} || $opt{u} || $opt{d} || $opt{p} || $opt{e} ||
	  $opt{'of-enable'} || $opt{'of-disable'} || $opt{'of-controller'} || 
	  $opt{'of-listener'}) {
	my $nulldev;
        open($nulldev, ">>/dev/null");
	select $nulldev; # supresses print foo(); without explicit fileglob
    }
}

#if ($opt{F}) { push @commands, ["synchleader"]; }
# Values that may have been passed on the command line
#
my $pid;
my $eid;
my $experiment;
my @ports;
my @optvlanids  = ();
my %optvlantags = ();
my $equaltrunking = 0;
my $this_user;
my $ofconnstr; # Openflow connection string, for controller 
our $next_vlan_tag; # XXX see doMakeVlan for explanation
my %stack_ids = ();
my $optdev; # when -i only specify a single device


#
# Move this initialization ahead from its previous location so that
# the ports converters can be used when parsing command line args.
#
# snmpit_lib fills out some hashes for speed of lookup later. Initialize
# them now
#
snmpit_lib::init($debug);

if ($opt{i} && @{$opt{i}} == 1) {
    $optdev = $opt{i}->[0];
}

#
# Verify user and get his DB uid for later. 
#
if ($UID) {
    $this_user = User->ThisUser();
    if (! defined($this_user)) {
	die("*** $0:\n".
	    "    You ($UID) do not exist!\n");
    }
}

#
# Some operations have mandatory agruments - for others, make sure that
# the user didn't give any extraneous arguments
#
if ($opt{m} || $opt{o}) {
    if (@ARGV < 2 ||
	($opt{m} && ($ARGV[0] =~ /:/ || $ARGV[1] =~ /:/)) ||
	($opt{o} && ($ARGV[0] =~ /^\d+$/ || $ARGV[1] =~ /^\d+$/))) {
	if (! $opt{f}) {
	    tberror "pid/eid reqired!";
	    exit(usage());
	}
	$pid = VLAN_PID();
	$eid = VLAN_EID();
	print "Using internal experiment $pid/$eid for operations\n";
    }
    else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
    }
}
if ($opt{'syncvlans'} || $opt{l} || $opt{F}) {
    $pid = VLAN_PID();
    $eid = VLAN_EID();
    print "Using internal experiment $pid/$eid for operations\n";
}
if ($opt{t} || $opt{r} || $opt{D} || $opt{R} || $opt{X} ||
    $opt{A} || ($opt{C} && !$opt{o})) {
    #
    # Options that take 'pid eid'
    #
    if (!defined($pid)) {
	if (@ARGV < 2) {
	    tberror "pid/eid reqired!";
	    exit &usage;
	} else {
	    ($pid, $eid) = (shift @ARGV, shift @ARGV);
	}
    }
    if (@ARGV) {
	if ($opt{A} || ($opt{C} && !($opt{r} || $opt{o}))) {
	    # Allow a comma separated list of tags per lan.
	    foreach my $arg (@ARGV) {
		if ($arg =~ /^[-\w]*,\d*/) {
		    my @tmp = split(',', $arg);
		    my $id  = shift(@tmp);
		    push(@optvlanids, $id);
		    $optvlantags{$id} = \@tmp;
		}
		else {
		    push(@optvlanids, $arg);
		}
	    }
	}
	else {
	    @optvlanids = @ARGV;
	}
    }
} elsif ($opt{d} || $opt{e} || $opt{a} || $opt{p} || $opt{u} || $opt{m}
         || $opt{U} || $opt{b}) {
    #
    # Options that take a list of ports
    #
    @ports = @ARGV;
} elsif ($opt{T} || $opt{E}) {
    #
    # Options that take both a port and a list of VLANs - we require at least
    # one VLAN to be given
    #
    if ($opt{E}) { $opt{T} = $opt{E}; $equaltrunking = 1;}
    elsif (!@ARGV) {
	tberror "At least one VLAN required";
	exit &usage;
    }
    @optvlanids = @ARGV;

    #
    # Set the @ports array so that we'll do proper permission checking on it
    #
    @ports = ($opt{T});
} elsif ($opt{'of-controller'}) {
    #
    # Options that take the pid eid and connection string
    #
    if (@ARGV < 2) {
	tberror "pid/eid reqired!";
	exit &usage;
    } else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
    }
    if (@ARGV < 0) {
	tberror "Controller connection string reqired!";
	exit &usage;
    } else {
	$ofconnstr = shift @ARGV;
    }
} elsif ($opt{'of-enable'} || $opt{'of-disable'} || $opt{'of-listener'}) {
    #
    # Options that need pid eid
    #
    if (@ARGV < 1) {
	tberror "pid/eid reqired!";
	exit &usage;
    } else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
    }    
} else {
    #
    # Everything else
    #
    if (@ARGV) {
	tberror({type => 'primary', severity => SEV_ERROR,
		 error => ['too_many_arguments']},
		"Too many arguments!");
	exit &usage;
    }
}

#
# Save the ports given in command line for future comparison
#
my @optports = @ports;

#
# Determine which operation we're performing. This is just for convenience,
# so that we can use switch-like constructs later. While we're at it, we
# pull out any arguments that were given in the $opt{} values.
#
my @commands;

#
# Simple commands
#
if ($opt{l}) { push @commands, ["listvlans"]; }
if ($opt{L}) { push @commands, ["listvlans"]; }
if ($opt{s}) { push @commands, ["listports"]; }
if ($opt{g}) { push @commands, ["getstats"]; }
if ($opt{t}) { push @commands, ["tables"]; }
if ($opt{r}) { push @commands, ["reset"]; }
if ($opt{X}) { push @commands, ["synctables"]; }
if ($opt{c}) { push @commands, ["recreate"]; }
if ($opt{U}) { push @commands, ["trunkdisable"]; }
if ($opt{b}) { push @commands, ["portstatus"]; }
if ($opt{F}) { push @commands, ["synchleader"]; }
if ($opt{A}) { push @commands, ["reservetags"]; }
if ($opt{'syncvlans'}) { push @commands, ["syncvlans"]; }

# This option combines with reset/remove
if ($opt{C} && !($opt{r} || $opt{o})) { push @commands, ["unreservetags"]; }

#
# Commands that can appear once, and take an argument
#
if ($opt{d}) { push @commands, ["portcontrol","disable"]; }
if ($opt{e}) { push @commands, ["portcontrol","enable"]; }
if ($opt{a}) { push @commands, ["portcontrol","auto"]; }
if ($opt{D}) { push @commands, ["expcnetcontrol", "disable"]; }
if ($opt{R}) { push @commands, ["expcnetcontrol", "enable"]; }
if ($opt{T}) { push @commands, ["trunkenable", $opt{T}]; }
if ($opt{'of-enable'}) { push @commands, ["ofenable", $opt{'of-enable'}]; }
if ($opt{'of-disable'}) { push @commands, ["ofdisable", $opt{'of-disable'}]; }
if ($opt{'of-controller'}) { push @commands, ["ofcontroller", $opt{'of-controller'}]; }
if ($opt{'of-listener'}) { push @commands, ["oflistener", $opt{'of-listener'}]; }

#
# Commands that can occur more than once
#
if ($opt{m}) {
    foreach my $name (@{$opt{m}}) {
	push @commands, ["make",$name];
    }
}

if ($opt{o}) {
    foreach my $name (@{$opt{o}}) {
	push @commands, ["remove",$name];
    }
}

if ($opt{N}) {
    foreach my $name (@{$opt{N}}) {
	push @commands, ["vlannumber",$name];
    }
}

if ($opt{B}) {
    foreach my $statstring (@{$opt{B}}) {
	push @commands, ["restorestatus",$statstring];
        # Set up the @ports variable so that we get permissions checking. Note,
        # though, that we re-parse the strings again later, this is just for
        # permissions
        my %args = parseStatusString($statstring);
        if (!$args{port}) {
            tbdie "No port given in status string";
        }
        if ($args{port}) {
467
            push @ports, convertPortsFromStrings($optdev, $args{port});
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        }
    }
}

#
# Commands that require 'translation' of their arguments
#
if ($opt{p}) {
    #
    # We'll put the argument in the form needed by the portControl function
    #
    if ($opt{p} =~ /^1000/) {
	push @commands, ["portcontrol","1000mbit"];
    } elsif ($opt{p} =~ /^100/) {
	push @commands, ["portcontrol","100mbit"];
    } elsif ($opt{p} =~ /^10/) {
	push @commands, ["portcontrol","10mbit"];
    } else {
	tbreport(SEV_ERROR, 'bad_data', 'port_speed', $opt{p});
	die "Bad port speed: $opt{p}. Valid values are 10, 100, and 1000\n";
    }
}
if ($opt{u}) {
    #
    # We'll put the argument in the form needed by the portControl function
    #
    if ($opt{u} =~ /half/) {
	push @commands, ["portcontrol","half"];
    } elsif ($opt{u} =~ /full/) {
	push @commands, ["portcontrol","full"];
    } else {
	die "Bad port duplex: $opt{u}. Valid values are full and half\n";
    }
}

#
# If this is an operation on an experiment, make sure that they have permission
# to modify that experiment
#
if ($pid && $eid) {
    #
    # First, make sure the experiment exists
    #
    $experiment = Experiment->Lookup($pid,$eid);
    if (!defined($experiment)) {
	die "There is no experiment $eid in project $pid\n";
    }
    # XXX Do not make this check when -f is used; called in user context.
    if (defined($this_user) && !$opt{f} && 
	!$experiment->AccessCheck($this_user, TB_EXPT_MODIFY)) {
	die "You do not have permission to modify experiment $pid/$eid\n";
    }
}
#
# See if we use the alternate version of snmpit from Rob.
#
if ($MAINSITE && $TB eq "/usr/testbed" && !$opt{Z}) {
    my $group = (defined($experiment) ? $experiment->GetGroup() : undef);
    $EmulabFeatures::verbose = 0;
    my $newsnmpit =
        (EmulabFeatures->FeatureEnabled("RobSnmpit",
					$this_user, $group, $experiment));
    if ($newsnmpit) {
	# Rob, change this path:
	my $newpath = "$TB/bin/snmpit";
	print STDERR "Invoking alternate snmpit from $newpath\n";
	
        unshift(@SAVEARGV, "-Z");
	exec $newpath, @SAVEARGV;
	die("*** $0:\n".
	    "    Could not exec $newpath: $!");
    }
}

if (!@commands) {
    tbreport(SEV_ERROR, 'no_operation');
    die "No operation given\n";
}

#
# Options that affect other commands
#

#
# User-supplied switch lists
#
554 555 556 557 558 559 560

# See if we should we flip the behavior of -S and -i ?
my $skip_supplied = 0;
if ($opt{'skip-supplied'} && $opt{S}) {
    $skip_supplied = 1;
}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
my @supplied_switches = ();
my @supplied_stacks   = ();
my $supplied_switches = 0; # Whether -i or -S was given
if ($opt{i}) {
    $supplied_switches = 1;
    push @supplied_switches, @{$opt{i}};
}
if ($opt{S}) {
    foreach my $stack (@{$opt{S}}) {
	if ($ELABINELAB) {
	    # We are going to pass the stack argument through in the rpc call.
	    push(@supplied_stacks, $stack);
	}
	else {
	    $supplied_switches = 1;
	    my @switches = getSwitchesInStack($stack);
	    if (@switches) {
		push @supplied_stacks, $stack;
		push @supplied_switches, @switches;
	    } else {
		tbdie({type => 'primary', severity => SEV_ERROR,
		       error => ['invalid_switch_stack', $stack]},
		      "No such switch stack: $stack");
	    }
	}
    }
}
@supplied_switches = uniq(@supplied_switches);
@supplied_stacks   = uniq(@supplied_stacks);

#
# Arguments for making private VLANs
#
# Build up a list of extra arguments to be passed to createVlan()
my @pvlanArgs = ();
if ($opt{y}) {
    #
    # Make sure the private VLAN type they gave is valid, and make sure they
    # gave the other required arugments for certain types
    #
    if ($opt{y} ne "primary" && $opt{y} ne "isolated" &&
	$opt{y} ne "community") {
	die "Unknown private VLAN type $opt{y}\n";
    }
    @pvlanArgs = $opt{y};
    if ($opt{y} ne "primary") {
	if (!$opt{x} || !$opt{z}) {
	    tberror "-x and -z must be given when -y is $opt{y}!";
	    exit &usage;
	}
	#
	# Fix up ports given in the module/port format, like we do below for
	# ports from @ARGV
	#
	my ($c, $p) = Port->ParseCardPortString($opt{z});
	if (defined($c) && defined($p)) {
	    if (defined($optdev)) {
		$opt{z} = Port->Triple2Iface(Port->Tokens2TripleString($optdev, $c, $p));
		if (!defined($opt{z})) {
		    tbdie "Port $c:$p not found";
		}
	    } else {
		tbdie "The module/port format is only legal if exactly one -i " .
		    "argument has been given";
	    }
	}
	push @pvlanArgs,$opt{x},$opt{z};
    }
}

######################################################################
# Step 3 - Set up the stack objects
#
# Determine which devices to talk to, and make the appropriate
# stack objects
######################################################################

#
# If their operation involves a set of ports, make sure that the caller has
# access to the nodes that the ports are on
#
# Convert ports into the correct format
if (@ports) {	
644
    @ports = convertPortsFromStrings($optdev, @ports);
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
    if (scalar(@optports) != scalar(@ports)) {
	die "Bad format for ports: ".join(" ", @optports)."\n";
    }
}

if (@ports) {
    #
    # Allow ports to be given in one of two forms: node:port, or switch.port.
    # Only admins can do the latter, of course...
    #

    my @pcports = grep {!$_->is_switch_side()} @ports;
    my @nodes = map {$_->node_id()} @pcports;
    my @switchports = grep {$_->is_switch_side()} @ports;

    if (@pcports + @switchports != @ports) {
	tbreport(SEV_ERROR, 'bad_data', 'port', join(" ", @optports));
	die "Bad format for port ".join(" ", @optports)."\n";
    }

    if ($UID && !TBNodeAccessCheck($UID,TB_NODEACCESS_MODIFYVLANS,@nodes)) {
	tbreport(SEV_ERROR, 'insufficient_permissions');
	die "You do not have permission to modify some or all of the nodes\n" .
		"that will be affected by the operation you requested\n";
    }

    if (@switchports && !TBAdmin()) {
	die "Only admins are allowed to modify switch ports directly\n";
    }
}

if ($TESTMODE) {
    print "Test mode, exiting without touching hardware\n";
    exit(0);
}

my $exitval = 0;
COMMAND: foreach my $command (@commands) {

    #
    # Pull the operation and the arugments to it.
    #
    my ($operation,@args) = @$command;

    debug("Operation is $operation\n");

    #
    # Discover the set of devices we need to talk to. This differs depending
    # on the operation which we're performing. We also get a list of all ports
    # and vlan IDs involved in this operation, if appropriate. We use this
    # opportunity to bail out of the command if it appears we have no work
    # to do
    #
    my @devicenames;
    my @vlans;
    SWITCH: for ($operation) {
	(/listvlans/ || /getstats/ || /vlannumber/ || /synchleader/ ||
	 /syncvlans/) && do {
703
	    @devicenames = ($supplied_switches && !$skip_supplied)?
704 705 706 707
			   @supplied_switches : getTestSwitches();
	    last;
	};
	(/listports/) && do {
708 709 710
	    @devicenames = ($supplied_switches && !$skip_supplied)? 
		           @supplied_switches :
			   (@ports? getDeviceNames(@ports) : getTestSwitches());
711 712 713
	    last;
	};
	( /make/ ) && do {
714 715
	    my ($vlan_name) = @args;

716
            if ($supplied_switches && !$skip_supplied) {
717 718
                @devicenames = @supplied_switches;
            } elsif (@ports) {
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
		my $vlanobj;
		if ($vlan_name =~ /^\d*$/) {
		    $vlanobj = VLan->Lookup($vlan_name);
		}
		else {
		    $vlanobj = VLan->Lookup($experiment, $vlan_name);
		}
		if (defined($vlanobj)) {
		    #
		    # Need to know the entire port set, since -m is also
		    # used to add ports to existing vlans.
		    #
		    # All devices needed includes trunks to transit.
		    @devicenames = mapPortsToSwitches(
			snmpit_lib::uniq_ports(getVlanPorts($vlanobj->lanid()),
					       @ports));
		}
		else {
		    # All devices needed includes trunks to transit.
		    @devicenames = mapPortsToSwitches(@ports);
		}
Leigh Stoller's avatar
Leigh Stoller committed
740
		debug("make: switch list: " . join(",",@devicenames) . "\n");
741 742 743 744 745 746 747 748 749 750 751
            } else {
                @devicenames = getTestSwitches();
            }
	    last;
	};
        (/remove/) && do {
            # Three levels of possible sources for device names (in order):
            #   passed in on command line
            #   vlan from the db
            #   if others fail, default to experimental switches
	    my ($vlan_name) = @args;
752
            if ($supplied_switches && !$skip_supplied) {
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
                debug("Remove: using supplied switches\n");
                @devicenames = @supplied_switches;
            }
	    else {
		my $vlanobj;
		if ($vlan_name =~ /^\d*$/) {
		    $vlanobj = VLan->Lookup($vlan_name);
		}
		else {
		    $vlanobj = VLan->Lookup($experiment, $vlan_name);
		}
		if (defined($vlanobj) && !$vlanobj->IsInternal()) {
		    @devicenames = mapVlansToSwitches($vlanobj->lanid());
		    debug("Remove: list from database: " . join(",",@devicenames) .
			  "\n");
		}
            }
            if (scalar(@devicenames == 0)) {
                debug("Remove: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
            last;
        };
        (/^tables$/ || /^reservetags$/ || /^unreservetags$/) && do {
            # Grab all stacks that any ports in the experiment are members
            # of.
            # (We need the entire stack, since the VLAN may have to traverse
            # devices that don't explicitly have a port in the VLAN.)
            @vlans = getExperimentVlans($pid,$eid,@optvlanids);
            if (!@vlans) {
                print "snmpit: $pid/$eid has no VLANs to create, skipping\n"
		    if (!$quiet);
                next COMMAND;
            }
787
            if ($supplied_switches && !$skip_supplied) {
788 789 790 791 792 793 794 795 796 797 798 799 800 801
                debug("Tables: using supplied switches\n");
                @devicenames = @supplied_switches;
		@vlans = filterVlansBySwitches(\@supplied_switches, @vlans);
		if (!@vlans) {
		    print "snmpit: $pid/$eid has no VLANs to create ".
			"on supplied devices, skipping\n"
			if (!$quiet);
		    next COMMAND;
		}
            } else {
                @devicenames = mapVlansToSwitches(@vlans);
                debug("Tables: list from database: " . join(",",@devicenames) .
		      "\n");
            }
802 803 804 805 806 807 808 809 810 811 812
            if ($skip_supplied) {
                debug("Tables: skipping supplied switches\n");
		@devicenames = filterList(\@devicenames,\@supplied_switches);
		@vlans = filterVlansBySwitches(\@devicenames, @vlans);
		if (!@devicenames || !@vlans) {
		    print "snmpit: $pid/$eid has no VLANs to create ".
			"on skip-filtered device list, skipping\n"
			if (!$quiet);
		    next COMMAND;
		}
            }
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
            if (scalar(@devicenames == 0)) {
                debug("Tables: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
            last;
        };
	(/reset/) && do {
	    #
            # We operate on all stacks that we have recorded as having VLANs
            # that belong to this experiment.
	    #
	    @vlans = getExperimentVlans($pid,$eid,@optvlanids);
            if (!@vlans) {
                print "snmpit: $pid/$eid has no VLANs, skipping\n"
		    if (!$quiet);
                next COMMAND;
            }
	    if ($ELABINELAB) {
		#
		# Do not worry about the local state. Always go to outer
		# boss to make sure that the vlans are removed.
		#
		@devicenames = getTestSwitches();
		last;
	    }
            @vlans = filterPlannedVlans(@vlans);
            if (!@vlans) {
                print "snmpit: $pid/$eid has VLANs, but none have been " .
                    "created on switches\n  ... skipping\n";
                next COMMAND;
            }
844
            if ($supplied_switches && !$skip_supplied) {
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
                debug("Reset: using supplied switches\n");
                @devicenames = @supplied_switches;
		@vlans = filterVlansBySwitches(\@supplied_switches, @vlans);
		if (!@vlans) {
		    print "snmpit: $pid/$eid has no VLANs to reset ".
			"on supplied devices, skipping\n"
			if (!$quiet);
		    next COMMAND;
		}
            } else {
                @devicenames = mapVlansToSwitches(@vlans);
                debug("Reset: list from database: " . join(",",@devicenames) .
                    "\n");
            }

860 861 862 863 864 865 866 867 868 869 870 871
            if ($skip_supplied) {
                debug("Reset: skipping supplied switches\n");
		@devicenames = filterList(\@devicenames,\@supplied_switches);
		@vlans = filterVlansBySwitches(\@devicenames, @vlans);
		if (!@devicenames || !@vlans) {
		    print "snmpit: $pid/$eid has no VLANs to reset ".
			"on skip-filtered device list, skipping\n"
			if (!$quiet);
		    next COMMAND;
		}
            }

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
            # Fallthrough - if we haven't found any switches yet, operate
            # on the whole experimetnal net
            if (scalar(@devicenames) == 0) {
                debug("Reset: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
	    last;
	};
	(/synctables/) && do {
            # We operate on all stacks on which we think VLANs do, or should,
            # exist.
	    my @newvlans = getExperimentVlans($pid,$eid,@optvlanids);
	    my @oldvlans;
	    VLan->StaleVlanList($experiment,\@oldvlans);

887 888 889 890 891 892 893 894 895
	    #
	    # No old or new vlans, then skip all of this. 
	    #
	    if (! (@newvlans || @oldvlans)) {
                print "snmpit: $pid/$eid has no old or new VLANs ... ".
		    "skipping\n";
                next COMMAND;
	    }

896
            if ($supplied_switches && !$skip_supplied) {
897 898 899 900 901 902 903 904
		die("-X and -i cannot be used together\n");
            }
	    else {
                @devicenames = uniq(mapVlansToSwitches(@newvlans),
				    mapStaleVlansToSwitches(@oldvlans));
                debug("Sync: list from database: " . join(",",@devicenames) .
		      "\n");
            }
905 906 907 908 909 910 911 912 913 914 915 916 917

            if ($skip_supplied) {
                debug("Sync: skipping supplied switches (dangerous!)\n");
		@devicenames = filterList(\@devicenames,\@supplied_switches);
		@vlans = filterVlansBySwitches(\@devicenames, @vlans);
		if (!@devicenames || !@vlans) {
		    print "snmpit: $pid/$eid has no VLANs to sync ".
			"on skip-filtered device list, skipping\n"
			if (!$quiet);
		    next COMMAND;
		}
            }

918 919 920 921 922 923 924 925 926
            # Fallthrough - if we haven't found any switches yet, operate
            # on the whole experimental net
            if (scalar(@devicenames) == 0) {
                debug("Reset: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
	    last;
	};
	(/portcontrol/ || /trunkdisable/ || /portstatus/) && do {
927
	    @devicenames = ($supplied_switches && !$skip_supplied)?
928 929 930 931 932 933 934 935 936 937 938 939
	    		   @supplied_switches : getDeviceNames(@ports);
	    last;
	};
	(/expcnetcontrol/) && do {
	    @ports = getExperimentControlPorts($pid, $eid);
	    @devicenames = getDeviceNames(@ports);
	};
	(/recreate/) && do {
	    #
	    # Safety check - cannot be used with -i . We have to operate on
	    # all experimental switches
	    #
940
	    if ($supplied_switches && !$skip_supplied) {
941 942 943 944 945 946
		die "-c and -i or -S cannot be used together\n";
	    }
	    @devicenames = getTestSwitches();
	    last;
	};
	(/trunkenable/) && do {
947
	    @devicenames = ($supplied_switches && !$skip_supplied)?
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
	    		   @supplied_switches : getDeviceNames(@ports);
	    @vlans = @optvlanids;
	    last;
	};
        (/restorestatus/) && do {
            # We start by parsing out the options string, then we'll reset
            # @args
            my ($statusarg) = @args;
            my %args = parseStatusString($statusarg);
            if (!$args{port}) {
                tbdie "No port given in status string";
            }
            @ports = Port->converPortsFromStrings($args{port}); 
            if ($args{vlan}) {
                @vlans = ($args{vlan});
            }
964
	    @devicenames = ($supplied_switches && !$skip_supplied)?
965 966 967 968 969 970 971 972 973
		           @supplied_switches : getDeviceNames(@ports);
            @args = %args;
            last;
        };
	(/ofenable/ || /ofdisable/ || /ofcontroller/ || /oflistener/) && do {
	    @vlans = @args;

	    # Same to 'remove', we find stacks by VLAN 
	    my ($vlanobj, $stack);
974
            if ($supplied_switches && !$skip_supplied) {
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
                debug("Openflow operations: using supplied switches\n");
                @devicenames = @supplied_switches;
            } elsif (defined($experiment) &&
                     defined($vlanobj = VLan->Lookup($experiment,$vlans[0])) &&
                     defined($stack = $vlanobj->GetStack())) {
                debug("Openflow operations: found stack $stack in database\n");
                @devicenames = getSwitchesInStack($stack);
            } else {
                debug("Openflow operations: using test switches\n");
                @devicenames = getTestSwitches();
            }
	    last;
	};
    }

990 991 992 993 994 995 996
    #
    # No matter what operation we're doing, we're safe to filter the 
    # devicenames list now!
    #
    @devicenames = filterList(\@devicenames,\@supplied_switches)
        if ($skip_supplied);

997
    debug("Device names: " . join(",",@devicenames) . "\n");
998 999 1000 1001 1002
    debug("Ports: " . join(",", map($_->toIfaceString(), @ports)) . "\n");

    #
    # Order the vlans using the dependency information in the link field.
    #
Leigh Stoller's avatar
Leigh Stoller committed
1003 1004
    if (@vlans && ($opt{m} || $opt{t})) {
	my %vlans    = ();
1005 1006
 	my @newvlans = ();
 	my %newvlans = ();
Leigh Stoller's avatar
Leigh Stoller committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

	foreach my $vlanid (@vlans) {
	    #
	    # Lookup the vlan, but only numeric ones. Named vlans are
	    # special and not something we need to worry about here. 
	    #
	    if (! ($vlanid =~ /^\d*$/)) {
		push(@newvlans, $vlanid);
		next;
	    }
	    my $vlan = VLan->Lookup($vlanid);
	    if (!defined($vlan)) {
		# Bad.
		die("Cannot lookup vlan $vlanid\n");
	    }
	    $vlans{$vlanid} = $vlan;
	}
1024 1025 1026 1027 1028
 	#
 	# The "link" field in the vlan points to the vlan it is dependent
 	# on. So, we actually build up the list in reverse order, and then
 	# flip it around at the end. 
 	#
Leigh Stoller's avatar
Leigh Stoller committed
1029 1030 1031 1032 1033 1034 1035 1036
	while (@vlans) {
	    my @tmp = ();
	    foreach my $vlanid (@vlans) {
		my $vlan = $vlans{$vlanid};

		if (!$vlan->link() ||
		    exists($newvlans{$vlan->link()}) ||
		    !exists($vlans{$vlan->link()})) {
1037
		    push(@newvlans, $vlanid);
Leigh Stoller's avatar
Leigh Stoller committed
1038
		    $newvlans{$vlanid} = $vlanid;
1039
		}
Leigh Stoller's avatar
Leigh Stoller committed
1040 1041
		else {
		    push(@tmp, $vlanid);
1042
		}
Leigh Stoller's avatar
Leigh Stoller committed
1043 1044 1045
	    }
	    @vlans = @tmp;
	}
1046 1047 1048
 	@vlans = reverse(@newvlans);
 	debug("VLANs: " . join(",",@vlans) . "\n");
    }
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 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 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 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 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 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 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 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

    my %stacks = ();
    if (! $ELABINELAB) {
	#
	# Map all the devices to stacks.
	#
	foreach my $devicename (@devicenames) {
	    my $stack = getSwitchPrimaryStack($devicename);
	    if (defined($stack)) {
		push @{$stacks{$stack}}, $devicename;
	    }
	}
    }

    #
    # Now, make the object for each stack that we discovered
    #
    my @stacks;
    %stack_ids = ();
    foreach my $stack_id (keys %stacks) {
	my ($stack_type, $supports_private, $single_domain, $community)
		= getStackType($stack_id);
	#
	# Safety check - make sure the stack supports private VLANs if -y was
	# given
	#
	if ($opt{y} && !$supports_private) {
	    die "Switch stack $stack_id does not support private VLANs\n";
	}

	my $stack;
	debug("Stack $stack_id has type $stack_type\n");
	SWITCH: for ($stack_type) {
	    (/cisco/ || /catalyst/) && do {
		require snmpit_cisco_stack;
		$stack = new snmpit_cisco_stack($stack_id,$debug,$single_domain,
 						@{$stacks{$stack_id}});
		last;
	    }; # /cisco/
	    /intel/ && do {
		require snmpit_intel_stack;
		$stack = new snmpit_intel_stack($stack_id,$debug,
						@{$stacks{$stack_id}});
		last;
	    };
	    /generic/ && do {
		require snmpit_stack;
		$stack = new snmpit_stack($stack_id,$debug,
					  @{$stacks{$stack_id}});
		last;
	    }; # /generic/

	    # 'default' case
	    die "Unknown stack type $stack_type for stack $stack_id\n";
	}

	#
	# Check for error in object creation and bail
	#
	if (!$stack) {
	    die "Unable to connect to one or more switches, exiting\n";
	} else {
	    push @stacks, $stack;
	    $stack_ids{$stack_id} = $stack;
	}
    }


    #
    # If we were given ports, make sure that the stack(s) that got created
    # cover all of them
    #
    if (@ports && !$ELABINELAB) {
	my %devicemap = mapPortsToDevices(@ports);
	my @devices = keys %devicemap;
	foreach my $device (@devices) {
	    my @stack_ids = getSwitchStacks($device);
	    my $matched = 0;
	    foreach my $stack_id (@stack_ids) {
		if ($stack_id && $stack_ids{$stack_id}) {
		    $matched = 1;
		}
	    }
	    if (!$matched) {
		tbdie({type => 'primary', severity => SEV_ERROR,
		       error => ['device_not_in_stack', $device]},
		      "One or more ports are on $device, but no " .
		      "stack containing it was specified!");
	    }
	}
    }
    if ($ELABINELAB) {
	#
	# Okay, now that we skipped all that stack stuff ...
	#
	@stacks = @supplied_stacks;
    }

######################################################################
# Step 4 - Actually perfrom the operation
#
# Finally, we just call the helper function for the operation that
# is to be performed.
######################################################################
    if ($opt{n}) {
	print "Test mode, skipping operation\n";
	next;
    }

    SWITCH: for ($operation) {
	/listvlans/ && do {
	    $exitval += doListVlans(\@stacks);
	    last;
	}; # /listvlans/ && do 
	/synchleader/ && do {
	    $exitval += doSynchLeader(\@stacks);
	    last;
	}; # /listvlans/ && do 
	/syncvlans/ && do {
	    $exitval += doSyncVlansWithDB(\@stacks);
	    last;
	}; # /listvlans/ && do 
	/listports/ && do {
	    $exitval += doListPorts(\@stacks);
	    last;
	}; # /listports/ && do
	/getstats/ && do {
	    $exitval += doGetStats(\@stacks);
	    last;
	}; # /ports/ && do
	/^tables$/ && do {
	    $exitval += doVlansFromTables($experiment,\@stacks,@vlans);
	    last;
	}; # /tables/ && do
	/^reservetags$/ && do {
	    $exitval += doReserveVlanTags($experiment,\@stacks,@vlans);
	    last;
	}; # /reservetags/ && do
	/^unreservetags$/ && do {
	    $exitval += doUnReserveVlanTags($experiment,\@stacks,@vlans);
	    last;
	}; # /reservetags/ && do
	/synctables/ && do {
	    $exitval += syncVlansFromTables($experiment,\@stacks);
	    last;
	}; # /tables/ && do
	/reset/ && do {
	    $exitval += doReset(\@stacks,@vlans);
	    last;
	};
	/make/ && do {
	    my ($vlan_name) = @args;
	    $exitval += doMakeVlan(\@stacks,$vlan_name,@ports);
	    last;
	};
	/remove/ && do {
	    my ($vlan_name) = @args;
	    $exitval += doDeleteVlan(\@stacks,$vlan_name);
	    last;
	};
	/portcontrol/ && do {
	    my ($portcommand) = @args;
	    $exitval += doPortControl(\@stacks,$portcommand,@ports);
	    last;
	};
	/expcnetcontrol/ && do {
	    my ($portcommand) = @args;
	    $exitval += doPortControl(\@stacks,$portcommand,@ports);
	    last;
	};
	/recreate/ && do {
	    $exitval += doRecreateVlans(\@stacks);
	    last;
	};
	/trunkenable/ && do {
	    $exitval += doTrunkEnable(\@stacks,$ports[0],
				      $equaltrunking,@vlans);
	    last;
	}; # /trunkenable/ && do
	/trunkdisable/ && do {
	    $exitval += doTrunkDisable(\@stacks,$ports[0]);
	    last;
	}; # /trunkdisable/ && do
	/portstatus/ && do {
	    $exitval += doPortStatus(\@stacks,@ports);
	    last;
	}; # /portstatus/ && do
	/vlannumber/ && do {
	    my ($vlan_name) = @args;
	    $exitval += doVlanNumber(\@stacks,$vlan_name);
	    last;
	}; # /portstatus/ && do
	/restorestatus/ && do {
	    $exitval += doRestorePortStatus(\@stacks,@args);
	    last;
	}; # /portstatus/ && do
	(/ofenable/) && do {
	    $exitval += doOpenflowEnable(\@stacks,$vlans[0]);
	    last;
	}; # /ofenable/ && do
	(/ofdisable/) && do {
	    $exitval += doOpenflowDisable(\@stacks,$vlans[0]);
	    last;
	}; # /ofdisable/ && do
	(/ofcontroller/) && do {
	    $exitval += doSetOpenflowController(\@stacks,$vlans[0],$ofconnstr);
	    last;
	}; # /ofcontroller/ && do
	(/oflistener/) && do {
	    $exitval += doEnableOpenflowListener(\@stacks,$vlans[0]);
	    last;
	}; # /oflistener/ && do
    }
}

exit $exitval;

######################################################################
# Subs
######################################################################

#
# Print given message to STDERR, only if debug mode is on
#
sub debug($) {
    if ($debug) {
	print STDERR @_;
    }
}

#
# Parse a port status string. Returns a key-value hash pair
#
sub parseStatusString($) {
    my ($string) = @_;
    chomp $string;

    my %pairs;
    foreach my $pair (split /;/, $string) {
        my ($key, $value) = split /=/,$pair,2;
        if (!$key || !$value) {
            tbdie "Bad port status string: $string";
        } else {
            $pairs{$key} = $value;
        }
    }

    return %pairs;
}

#
# Lists all vlans on all stacks
#
sub doListVlans ($) {

    my $stacks = shift;
    my %vlans;
    my %tags;
    my @vlanList;

    #
    # We need to 'coallate' the results from each stack by putting together
    # the results from each stack, based on the VLAN identifier
    #
    if ($ELABINELAB) {
        #
        # Sklower deliberately uglified this.  The intent is that eventually
        # $stack->listVlans() will call a $<remotedevobj>->listVlans() and
        # it will just work.  For now, we dup the code.
        #
        @vlanList = RemoteDoList();
        foreach my $vlan (@vlanList) {
            my ($id,$ddep,$memberref) = @$vlan;
            ${$vlans{$id}}[0] = $ddep;
	    $tags{$ddep} = $id;
            push @{${$vlans{$id}}[1]}, @$memberref;
        }
    } else {
        foreach my $stack (@$stacks) {
            @vlanList = $stack->listVlans();
            foreach my $vlan (@vlanList) {
                my ($id,$ddep,$memberref) = @$vlan;
                ${$vlans{$id}}[0] = $ddep;
		$tags{$ddep} = $id;
                push @{${$vlans{$id}}[1]}, @$memberref;
            }
        }
    }

    #
    # less code to do this for snmpit.proxy than for it to popen snmpit
    # parse the output, and glue it back together.
    #
    if ($opt{L}) {
	my @results;
	foreach my $pair (split ',', $opt{L}) {
	    my ($out,$in) = split "#", $pair;
	    my $vlan = "$in#" . ${$vlans{$out}}[0] . "#";
	    my $memberref = ${$vlans{$out}}[1];
	    if (scalar(@$memberref) > 0 && ref(${$memberref}[0])) {
	    	$vlan = $vlan.Port->toStrings(@$memberref);
	    } else {
	    	$vlan = join(' ', @$memberref);
	    }
	    push @results, $vlan;
	}
	print join(',', @results);
	exit(0);
    }
    #
    # These need to be declared here for the benefit of the format string
    # See perlform(1) for help with formats
    # Note that they are declared 'our' rather than 'my' due to a stupid
    # bug in perl 5.10
    #
    our ($vlan_id,$ddep,$pideid,$vname,$members);

    #
    # Check to see if they want device-specific VLAN numbers, which makes the
    # display more cramped, but is useful for debugging
    #
    if (!$opt{w}) { 
	print << "END";
VLAN     Project/Experiment VName     Members
--------------------------------------------------------------------------------
END
	format vlanlist =
@<<<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$vlan_id,$pideid,           $vname,   $members
~~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                                      $members
.
	$FORMAT_NAME = 'vlanlist';
    } else {
    	print << "END";
VLAN     Number   Project/Experiment VName     Members
----------------------------------------------------------------------------------
END
	format vlanlist2 =
@<<<<<<< @<<<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$vlan_id,$ddep, $pideid,           $vname,   $members
~~                                             ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                                             $members
.
	$FORMAT_NAME = 'vlanlist2';
    }
    my @sorted = ($opt{w} ?
                  map {$tags{$_}} sort {tbsort($a,$b)} keys %tags :
                  sort {tbsort($a,$b)} keys %vlans);

    foreach my $vid (@sorted) {
        $vlan_id = $vid;
	my $memberref;
        my $vlan;
	($ddep,$memberref) = @{$vlans{$vid}};

	if ($vlan_id =~ /^\d*$/) {
	    $vlan = VLan->Lookup($vlan_id);
	}
	else {
	    $vlan = VLan->Lookup($experiment, $vlan_id);
	}
        if (!defined($vlan)) {
	    print("No such VLAN $vlan_id in lans table\n");
            # Only print unknown VLANs if -l was given twice, or the 
            # -O option was given
	    next unless ($opt{l} > 1 || $opt{O});

            # If only printing orphaned VLANs, consider only ones that have IDs
            # that look like the ones we assign in the database
            if ($opt{O} && $vlan_id !~ /^\d+$/) {
                next;
            }

            # Only admins get to see this. Possibly a silly check.
	    if (!TBAdmin()) {
		&debug("Failed TBAdmin check\n");
		next;
	    }
	    $pideid = "";
            $vname  = $vlan_id;
        }
	else {
            # If only printing orphaned VLANs, skip ones for which we know the
            # pid and ied
            if ($opt{O}) {
                next;
            }
            my $vlanexp = $vlan->GetExperiment();
            if ($UID &&
		!$vlanexp->AccessCheck($this_user, TB_EXPT_READINFO)) {
                &debug("$this_user failed access check to $experiment\n");
                next;
            }
   	    # Setup $pideid for a more compact display
            $pideid = $vlan->pid() . "/" . $vlan->eid();
            $vname  = $vlan->vname();
	}

	#
	# Check to see if we were supposed to print out MAC addresses
	#
	if ($opt{M}) {
	    # Rather than node:port, print out node:MAC (if we know the MAC)
	    if (scalar(@$memberref) > 0 && ref(${$memberref}[0])) { 
	    	$members = join(" ", map
		    {
			$_->mac()? $_->node_id().":".$_->mac():$_->toString()
		    } @$memberref);
	    } else {		
	    	my @ptobjs = map {Port->LookupByStringForced($_)} @$memberref;
	    	 
	    	$members = join(" ", map
		{
		    defined($_)?($_->mac()? $_->node_id().":".$_->mac():$_->toString()):""		    
		} @ptobjs);
	    }
	} else {
	    if (scalar(@$memberref) > 0 && ref(${$memberref}[0])) { 
	    	$members = Port->toStrings(@$memberref); 
	    } else {
	    	$members = join(" ",@$memberref);
	    }
	}
	write;
    }

    return 0;
}

#
# This routine does a number of illegal things.  It is used
# to make sure the leader of a stack contains all vlans on all switches
# in the stack and is only useful for moving a stack back and forth
# between types "cisco" and "generic" (where $stack->{ALLVLANSONLEADER} must be
# set to 1.
#
sub doSynchLeader ($) {

    my $stacks = shift;
    my $errors = 0;
    if (!TBAdmin()) {
	die "Only admins are allowed to synchronize stacks\n";
    }

    foreach my $stack (@$stacks) {
	my $leader = $stack->{LEADER};
	my %vlans = $stack->findVlans();
	while (my ($id,$num) = each %vlans) {
	    my $vlan;
	    
	    if ($id =~ /^\d*$/) {
		$vlan = VLan->Lookup($id);
	    }
	    else {
		$vlan = VLan->Lookup($experiment, $id);
	    }
	    if (!defined($vlan)) {
		print "Skipping $id/$num cause it is not in the DB\n";
		$errors++;
		next;
	    }
	    
	    if (($num >= $leader->{MIN_VLAN}) &&
		($num <= $leader->{MAX_VLAN}) &&
		!($leader->vlanNumberExists($num))) {
		$errors += $leader->createVlan($id, $vlan->lanid(), $num);
	    }
	}
    }
    return $errors;
}

#
# Lists all ports on all stacks
#
sub doListPorts($) {

    my $stacks = shift;

    #
    # Get a listing from all stacks
    #
    my @portList = ();
    foreach my $stack (@$stacks) {
	push @portList, $stack->listPorts;
    }

    #
    # See perlform(1) for help with formats
    #
    our ($port,$enabled,$up,$speed,$duplex);
    print << "END";
Port      Enabled Up   Speed      Duplex
--------------------------------------------
END
# make port field much longer because we use the 'triple' format of port string
    format portlist =
@<<<<<<<<<<<<<<<< @<<<<<< @<<< @<<<<<<<<< @<<<<<<<<<
$port,$enabled,$up,$speed,$duplex
.
    $FORMAT_NAME = 'portlist';
    foreach my $line (sort {tbsort($$a[0],$$b[0])} @portList) {
	($port,$enabled,$up,$speed,$duplex) = @$line;
	#
	# Only let people see information about ports in their experiments
	#
	#$port =~ /^(.+):/;
	my $node = $port->node_id();
	$port = $port->toString();

	&debug("node is $node\n");
	if (!$node) {
	    if (!TBAdmin($UID)) {
		next;
	    }
	} elsif ($UID && !TBNodeAccessCheck($UID,TB_NODEACCESS_READINFO,$node)) {
	    next;
	}
	write;
    }

    return 0;
}

#
# Get information on a particular port - the idea is that this string can later
# be passed back to us to restore the status of the port.
# This is inefficient, because it gets information about all ports and only
# uses it for one (or a few). BUT, it doesn't require changes to the
# vendor-specific modules, so I think it's worth it for portability.
#
sub doPortStatus($@) {

    my $stacks = shift;
    my @port = @_;

    my $errors = 0;

    #
    # Get a listing from all stacks
    #
    my @portList = ();
    foreach my $stack (@$stacks) {
	push @portList, $stack->listPorts;
    }

    #
    # Find the port(s) we're looking for in the portlist
    #
    my %ports = ();
    foreach my $port (@ports) {
        $ports{$port->toString()} = undef;
    }
    foreach my $portrecord (@portList) {
	my ($port,$enabled,$up,$speed,$duplex) = @$portrecord;
        if (exists $ports{$port->toString()}) {
            $ports{$port->toString()} = "enabled=$enabled";
            $ports{$port->toString()} .= ";speed=$speed";
            if ($speed ne "autoDetect") {
                $ports{$port->toString()} .= ";duplex=$duplex";
            }
        }
    }

    #
    # Now find out what VLAN it's in
    #
    foreach my $stack (@$stacks) {
	my @vlanList = $stack->listVlans();
	foreach my $vlan (@vlanList) {
	    my ($id,$ddep,$memberref) = @$vlan;
            # Now we have to look through the memberref for our ports
            foreach my $port (@$memberref) {
                if ($ports{$port->toString()}) {
                    $ports{$port->toString()} .= ";vlan=$id";
                }
            }
	}
    }

    #
    # XXX - This is gonna be a mess if the port is a trunk port, or otherwise
    # somehow more complicated. For now, we just ignore this, I guess
    #

    #
    # Check to see if we missed any
    #
    foreach my $port (keys %ports) {
        if (!$ports{$port}) {
	    tberror({type => 'primary', severity => SEV_ERROR,
		     error => ['get_port_status_failed', $port]},
		    "Unable to get status information for $port!");
            $errors++;
        } else {
            print "port=$port;$ports{$port}\n";
        }
    }

    if ($errors) {
        return $errors;
    }

}

#
# Restore port status. Takes a single argument, which is an array that will be
# turned back into a param hash
#
sub doRestorePortStatus($@) {

    my $stacks = shift;
    my %params = @_; # Yes, this does work
    my $errors = 0;

    my $port = $params{port};
    if (!$port) {
        tbdie "No port passed to -B option";
    }
    
    if (!ref($port)) {
	    my $tport = convertPortFromString($port);
	    if ($tport) {
		    $port = $tport;
	    } else {
		    die "Port $port does not exist!\n";
	    }
    }

    if (@$stacks > 1) {
	die "Port restoration across multiple stacks is not yet supported\n" .
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
    }
    my ($stack) = @$stacks;

    #
    # See where the port is; might be in the default vlan in which case it is
    # not technically in a vlan.
    #
    my $source_vlan = VLan->FindVlanByPort(undef, $port);
    my $target_vlan;

    #
    # Put the port in the specified VLAN
    # If they didn't give us a VLAN, we assume that means they want it removed
    # from its vlan and put into the default vlan.
    #
    my $vlan_id = $params{vlan};
    if ($vlan_id) {
	$target_vlan = VLan->Lookup($vlan_id);
	if (!defined($target_vlan)) {
            tbwarn "No such vlan in the DB: $vlan_id\n";
	    return 1;
	}
    }
    else {
	$vlan_id = "default";
    }
    print "Putting port in VLAN ...\n"
	if (!$quiet);
    $errors += $stack->setPortVlan($vlan_id, $port);
    if ($errors) { return $errors; }

1713 1714 1715 1716
    #
    # Do not worry about mucking with the switch trunk paths.
    # This call exists to temporarily move ports back and forth.
    #
1717 1718 1719 1720 1721
    if (defined($source_vlan) && $source_vlan->KeepInSync()) {
	if ($source_vlan->DelPort($port)) {
	    print "Could not yank $port from $source_vlan\n";
	    $errors++;
	}
1722
	VLan->RecordVlanInsertion($source_vlan->id(), $stack->{STACKID});
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 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
    }
    if (defined($target_vlan) && $target_vlan->KeepInSync()) {
	if ($target_vlan->AddPort($port)) {
	    print "Could not add $port to $target_vlan\n";
	    $errors++;
	}
	VLan->RecordVlanInsertion($target_vlan->id(), $stack->{STACKID});
    }

    # Enable or disable the port
    # If they didn't tell us either way, we assume they wanted it disabled
    my $enabled = $params{enabled};
    # If they are putting the port into the default VLAN, force it to be
    # disabled, so that a user cannot use this method to break into that VLAN
    if ($vlan_id eq "default") { $enabled = "no"; }
    if ($enabled eq "yes") {
        $errors = $stack->portControl("enable",$port);
    } else {
        $errors = $stack->portControl("disable",$port);
    }

    #
    # Set the speed and duplex on the port if given
    #
    my $speed = $params{speed};
    if ($speed && $speed ne " ") {
        if ($speed eq "autoDetect") {
            $errors = $stack->portControl("auto",$port);
        } else {
            #
            # Check for a valid speed - convert Mbps to mbit if necessary
            #
            if ($speed =~ /(\d+)(Mbps|mbit)/) {
                $errors = $stack->portControl("${1}mbit",$port);
            } else {
                tbwarn "Bad speed given for ".$port->toString().": $speed";
                $errors++;
            }
        }
    }
    my $duplex = $params{duplex};
    if ($duplex && $duplex ne " ") {
        if ($duplex eq "half") {
            $errors = $stack->portControl("half",$port);
        } elsif ($duplex eq "full") {
            $errors = $stack->portControl("full",$port);
        } else {
            tbwarn "Bad duplex given for ".$port->toString().": $duplex";
            $errors++;
        }
    }
    return $errors;
}

#
# Get statistics for all ports on all stacks
#
sub doGetStats($) {

    my $stacks = shift;

    #
    # Get a listing from all stacks
    #
    my @statList = ();
    foreach my $stack (@$stacks) {
	push @statList, $stack->getStats();
    }

    our ($port, $inoctets, $inunicast, $innunicast, $indiscards, $inerr,
        $inunk, $outoctets, $outunicast, $outnunicast, $outdiscards,
	$outerr,$outq);
    #
    # See perlform(1) for help with formats
    #
    print << "END";
          In         InUnicast  InNUnicast In         In         Unknown    Out        OutUnicast OutNUcast  Out       Out         OutQueue
Port      Octets     Packets    Packets    Discards   Errors     Protocol   Octets     Packets    Packets    Discards  Errors      Length
---------------------------------------------------------------------------------------------------------------------------------------------
END
    format stats =
@<<<<<<<< @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> @>>>>>>>>> 
$port,    $inoctets, $inunicast,$innunicast,$indiscards,$inerr,  $inunk,    $outoctets,$outunicast,$outnunicast,$outdiscards,$outerr,$outq
.
    $FORMAT_NAME = 'stats';
    foreach my $line (sort {tbsort($a,$b)} @statList) {
	($port, $inoctets, $inunicast, $innunicast, $indiscards, $inerr,
	 $inunk, $outoctets, $outunicast, $outnunicast, $outdiscards,
	 $outerr, $outq) = @$line;
	 $port = $port->toString();
	write;
    }

    return 0;
}

#
# Creates all VLANs given. Looks up identifiers in the database to determine
# the membership.
#
sub doVlansFromTables($$@) {
    my $experiment = shift;
    my $stacks  = shift;
    my @vlanids = @_;
    my %vlans   = ();

    my $errors = 0;
    my $vlan_number;

    if (@$stacks > 1) {
	die "VLAN creation across multiple stacks is not yet supported\n" .
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
    }
    
    #
    # Hand over to outer boss.
    # 
    if ($ELABINELAB) {
	return RemoteDoVlansFromTables($experiment, @vlanids);
    }

    my ($stack) = @$stacks;

#    $debug = 1;
#    $stack->FlipDebug(1);   

    my @trunkedPorts = getExperimentTrunks($experiment->pid(),
					   $experiment->eid());
    my %trunkedPorts = map { $_->toString() => $_ } @trunkedPorts;

    #
    # Look for a lan that requires dual mode trunking. The ports in that
    # lan need to be trunked after the native lan is created, so that we
    # can call doTrunkEnable with dual mode instead of equalmode. This is
    # not a general solution to this, but I have not found a solution I am
    # really happy with. 
    #
    foreach my $id (@vlanids) {
	my $vlan = VLan->Lookup($id);
	if (!defined($vlan)) {
	    die("Could not locate vlan $id in the DB\n");
	}
	$vlans{"$id"} = $vlan;
    }
    foreach my $vlan (values(%vlans)) {
	my $vlanid = $vlan->id();
	my $trunk_mode;
	$vlan->GetAttribute("trunk_mode", \$trunk_mode);

	# This is set in libvtop.
	if (defined($trunk_mode) && $trunk_mode eq "dual") {
	    my @ports = getVlanPorts($vlanid);
	    
	    # Create this vlan now.
	    if (CreateOneVlan($experiment,$stack, $vlanid, @ports))  {
		die("Could not create dual trunked $vlan\n");
	    }
	    # Trunk these ports, removing from list.
	    foreach my $port (@ports) {
		if (doTrunkEnable($stacks,$port,0,$vlanid)) {
		    die("Could not put ".$port->toString()." ($vlan) into dual trunk mode\n");
		}
		delete($trunkedPorts{$port->toString()});
	    }
	    
	    #
	    # Set openflow
	    #
	    # A much more right place for the openflow settings is CreateOneVlan,
	    # however, it is called by sync vlan function and others, which don't destroy
	    # the existing vlan_arrtibutes rows.
	    #
	    # TODO: Move this part to CreateOneVlan and Make sure the existed 
	    #       vlan_attributes rows are deleted
	    #
	    my $ofenabled;
	    $vlan->GetAttribute("ofenabled", \$ofenabled);
	    if (defined($ofenabled) && $ofenabled == 1) {
	        $errors += doOpenflowEnable($stacks, $vlanid);
	    
	        my $ofcontroller;
	        $vlan->GetAttribute("ofcontroller", \$ofcontroller);
	        if (defined($ofcontroller) && $ofcontroller ne "") {
	            $errors += doSetOpenflowController($stacks, $vlanid, $ofcontroller);
	        }
	    
	        $errors += doEnableOpenflowListener($stacks, $vlanid);
	    
	        # doEnableOpenflowListener updates the lan_arrtibutes table, so vlan 
	        # should refresh itself. But here vlan will not be used any more, so
	        # maybe we can comment this refresh.
	        $vlan->Refresh();	    
	    }
	    
	    # Delete this vlan from the list that will be created below.
	    delete($vlans{"$vlanid"});
	}
    }
    # Do the rest of the trunked ports in equalmode.
    foreach my $port (keys(%trunkedPorts)) {
	$errors += doTrunkEnable($stacks,$trunkedPorts{$port},1);
    }

    #
    # Sanity check: make sure that this experiment does not use more VLANs than
    # we can put on the stack. Note that we don't try to check how many are
    # available (ie. total - used), because getting the 'used' value is not
    # trivial.
    #
    my $leader = getStackLeader($stack->{STACKID});
    if (!defined $leader) {
        tberror "Unable to get stack leader for $stack->{STACKID}";
        return 1;
    }
    my $switch_options = getDeviceOptions($leader);
    if (!defined $switch_options) {
        tberror "Unable to get stack leader for $stack->{STACKID}";
        return 1;
    }
    my $vlan_count = $switch_options->{'max_vlan'} -
                     $switch_options->{'min_vlan'};
    my $expt_vlan_count = scalar(keys(%vlans));
    if ($expt_vlan_count > $vlan_count) {
        tberror "Too many VLANs in experiment: $expt_vlan_count requested, " .
                "$vlan_count available";
        return 1;
    }

    foreach my $vlan (values(%vlans)) {
	my $vlanid = $vlan->id();
	my @ports  = getVlanPorts($vlanid);

	$errors += CreateOneVlan($experiment, $stack, $vlanid, @ports);
	
	#
	# Set openflow
	# 
	# A much more right place for the openflow settings is CreateOneVlan,
	# however, it is called by sync vlan function and others, which don't destroy
	# the existing vlan_arrtibutes rows.
	#
	# TODO: Move this part to CreateOneVlan and Make sure the existed 
	#       vlan_attributes rows are deleted
	#
	my $ofenabled;
	$vlan->GetAttribute("ofenabled", \$ofenabled);
	if (defined($ofenabled) && $ofenabled == 1) {
	    $errors += doOpenflowEnable($stacks, $vlanid);
	    
	    my $ofcontroller;
	    $vlan->GetAttribute("ofcontroller", \$ofcontroller);
	    if (defined($ofcontroller) && $ofcontroller ne "") {
	        $errors += doSetOpenflowController($stacks, $vlanid, $ofcontroller);
	    }
	    
	    $errors += doEnableOpenflowListener($stacks, $vlanid);
	    
	    # doEnableOpenflowListener updates the lan_arrtibutes table, so vlan 
	    # should refresh itself. But here vlan will not be used any more, so
	    # maybe we can comment this refresh.
	    $vlan->Refresh();	    
	}
    }
    return $errors;
}

#
# Create a single vlan.
#
sub CreateOneVlan($$$@)
{
    my $experiment = shift();
    my $stack  = shift();
    my $vlanid = shift();
    my @ports  = @_;
    my $errors = 0;

    if ($stack->vlanExists($vlanid)) {
	print "  VLAN $vlanid already exists\n"
	    if (!$quiet);
	if ($stack->setPortVlan($vlanid,@ports)) {
	    $errors++;
	}
    }
    else {
	my $vlan_number = $stack->createVlan($vlanid, $vlanid, \@ports);
	if (!$vlan_number) {
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['create_vlan_failed', $vlanid]},
		    "Failed to create VLAN with id $vlanid");
	    #
	    # Don't try to put ports in a VLAN if it couldn't be created
	    #
	    $errors++;
	}
    }
    return $errors
	if ($errors);

2022 2023 2024 2025 2026 2027
    #
    # Record an insertion to make sure the DB reflects the current state
    # of the vlan. 
    #
    VLan->RecordVlanInsertion($vlanid, $stack->{STACKID});

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
    #
    # Set the speed and duplex of each interface depending on the
    # value in the database
    #
    if (!$NOSTACKMIB) {
	foreach my $port (@ports) {
	    my ($speed,$duplex) = getInterfaceSettings($port);
	    #
	    # If either is not set, we do nothing. We could make
	    # a 0 mean 'auto'
	    #
	    # For now, we ignore it if the switch doesn't support the
	    # commands.
	    #
	    if ($speed) {
		my $cmd = $speed . "mbit";
		my $rv = $stack->portControl($cmd, $port);
		if ($rv > 0) {
		    $errors += $rv;
		}
	    }
	    if ($duplex) {
		my $rv = $stack->portControl($duplex, $port);
		if ($rv > 0) {
		    $errors += $rv;
		}
	    }
	}
    }
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
    #
    # Look for a layer 1 link; There is a logical wire that needs to be
    # activated once it is created. 
    #
    my $vlan = VLan->Lookup($vlanid);
    if ($vlan->type() eq "wire") {
	my $wireid;
	
	if ($vlan->GetAttribute("logicalwireid", \$wireid) == 0) {
	    my $wire = Interface::Wire->Lookup($wireid);
	    if (!defined($wire)) {
		print STDERR "Could not logical wire for $vlan ($wireid)\n";
		$errors++;
	    }
	    else {
		if ($wire->Activate() != 0) {
		    print STDERR "Could not activate $wire for $vlan\n";
		    $errors++;
		}
	    }
	}
    }
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
    return $errors;
}

#
# Remove all VLANs given from every switch in the stack. All ports in the
# VLANs are removed, irrespective of what the database says membership should
# be
#
sub doReset($@) {
    my $stacks = shift;
    my @vlans = @_;
2090
    my %wires = ();
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109

    #
    # Hand over to outer boss.
    # 
    if ($ELABINELAB) {
	return RemoteDoReset($experiment,
			     scalar(@optvlanids) == 0, $opt{C}, @vlans);
    }

    my $errors = 0;
    my @trunkedPorts = getExperimentTrunks($pid,$eid);
    foreach my $port (@trunkedPorts) {
	$errors += doTrunkDisable($stacks,$port);
    }
    # In case of error, do not clear the DB state.
    my %notdeleted = ();

    $debug = 1;
    
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
    #
    # Look for a layer 1 link; There is a logical wire that needs to be
    # deactivated once it is created, but must ensure that the logical
    # wire is not actually in use.
    #
    foreach my $vlan_id (@vlans) {
	my $vlan = VLan->Lookup($vlan_id);
	my $wireid;

	next
	    if (! $vlan->type() eq "wire");
	
	if ($vlan->GetAttribute("logicalwireid", \$wireid) == 0) {
	    my $wire = Interface::Wire->Lookup($wireid);
	    if (!defined($wire)) {
		print STDERR "Could not logical wire for $vlan ($wireid)\n";
		return -1;
	    }
	    # need the interfaces.
	    my ($interface1, $interface2) = $wire->Interfaces();
	    if (!defined($interface1)) {
		print STDERR "No interface for logical wire $wire\n";
		return -1;
	    }
	    # Find the vlan that uses this interface.
Leigh Stoller's avatar
Leigh Stoller committed
2135
	    my $vlanusing = VLan->FindVlanByInterface($experiment, $interface1);
2136 2137 2138 2139 2140 2141 2142 2143 2144
	    if (defined($vlanusing) && $vlanusing->CreatedOnSwitches()) {
		print STDERR "Logical wire $wire is in use by $vlanusing; ".
		    "not allowed to remove $vlan\n";
		return -1;
	    }
	    $wires{$vlan->lanid()} = $wire;
	}
    }

2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
    #
    # Just remove the VLAN from every stack on which it exists. We keep a
    # list and do them all at once for efficiency.
    #
    foreach my $stack (@$stacks) {
#	$stack->FlipDebug(1);

	my @existant_vlans = $stack->existantVlans(@vlans);
	if (!$stack->removeVlan(@existant_vlans)) {
	    #
	    # Find out what still exists so that we keep the DB state.
	    #
	    foreach my $vlan_id (@existant_vlans) {
		if ($stack->vlanExists($vlan_id)) {
		    print "  $vlan_id was not deleted.\n";
		    $notdeleted{$vlan_id} = 1;
		}
	    }
	    $errors++;
	}
    }
    foreach my $vlan_id (@vlans) {
	next
	    if (exists($notdeleted{$vlan_id}));
	
2170
	VLan::ClearReservedVlanTag($vlan_id)
2171 2172
	    if ($opt{C});
	VLan->RecordVLanDeletion($vlan_id);
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183

	# Deactivate the logical wire.
	if (exists($wires{$vlan_id})) {
	    my $wire = $wires{$vlan_id};
	    
	    print "Deactivating logical wire $wire\n";
	    if ($wire->DeActivate() != 0) {
		print STDERR "Could not deactivate $wire for vlan $vlan_id\n";
		$errors++;
	    }
	}
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
    }
    return $errors;
}

#
# Sync vlans from the DB for a single experiment. This is a swapmod helper
# to avoid churning the switches.
#
sub syncVlansFromTables($$) {
    my $experiment = shift;
    my $stacks     = shift;
    my %expvlans   = ();
    my %curvlans   = ();
    my %stale      = ();
    my $errors     = 0;
    my $vlan_number;

    if (@$stacks > 1) {
	die "VLAN creation across multiple stacks is not yet supported\n" .
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
    }
    my ($stack) = @$stacks;

    $debug = 1;
    $stack->FlipDebug(1);

    my @needTrunking = getExperimentTrunks($pid,$eid);
    my %needTrunking = map { $_->toString() => $_ } @needTrunking;

    debug("Trunk Ports: ".Port->toStrings(@needTrunking)."\n");

    #
    # Get list of vlans that should exist.
    #
    my @tmp;
    VLan->ExperimentVLans($experiment, \@tmp) == 0 or
	die("Could not get current vlans for $experiment\n");
    foreach my $vlan (@tmp) {
	$expvlans{$vlan->id()} = $vlan;
    }
    debug("Experiment vlans: " . join(" ", keys(%expvlans)) . "\n");;

    #
    # Get list of vlans that we think are on the switch (vlans table).
    #
    @tmp = ();
    VLan->StaleVlanList($experiment, \@tmp) == 0 or
	die("Could not get stale vlans for $experiment\n");
    foreach my $vlanid (@tmp) {
	$curvlans{$vlanid} = 1;
	
	# Not in the new set; must delete.
	$stale{$vlanid} = 1
	    if (!exists($expvlans{$vlanid}));
    }
    debug("Existing vlans: @tmp\n");
    debug("Stale vlans: " . join(" ", keys(%stale)) . "\n");

    #
    # Get a list of interfaces that are currently trunked.
    #
    my @currentTrunks = getExperimentCurrentTrunks($pid,$eid);
    my %currentTrunks = map { $_->toString() => $_ } @currentTrunks;

    #
    # Okay, kill off stale vlans.
    #
    if (keys(%stale)) {
	my @existant_vlans = $stack->existantVlans(keys(%stale));

	if (@existant_vlans) {
	    debug("Removing stale vlans @existant_vlans\n");

	    if (!$impotent) {
		foreach my $vlanid (@existant_vlans) {
		    my @curports   = getExperimentVlanPorts($vlanid);
		    my @trunkports = ();

		    foreach my $port (@curports) {
			if (exists($currentTrunks{$port->toString()})) {
			    push(@trunkports, $port);
			}
		    }
		    if (@trunkports) {
			$stack->removeSomePortsFromTrunk($vlanid, @trunkports)
			    or goto bad;
		    }
		    if (!$stack->removeVlan($vlanid)) {
			print STDERR "Could not remove vlan: $vlanid\n";
			goto bad;
		    }
		    VLan->RecordVLanDeletion($vlanid) == 0
			or goto bad;
2277
		    VLan::ClearReservedVlanTag($vlanid) == 0
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
			or goto bad;
		}
	    }
	}
    }

    #
    # Remove stale ports from existing vlans. 
    #
    foreach my $vlanid (keys(%expvlans)) {
	# This one will be built later.
	next
	    if (!exists($curvlans{$vlanid}));
	    
	my @expports   = getVlanPorts($vlanid);
	my @curports   = getExperimentVlanPorts($vlanid);
	my @staleports = ();
	my @staletrunks= ();

	#
	# As a simplification for the backend, keep trunked ports separate
	# from regular ports. Better then the backend figuring it out.
	#
	foreach my $port (@curports) {
	    if (! grep {$_->toString() eq $port->toString()} @expports) {
		if (exists($currentTrunks{$port->toString()})) {
		    push(@staletrunks, $port);
		}
		else {
		    push(@staleports, $port);
		}
	    }
	}
	next
	    if (! (@staleports || @staletrunks));
	    
2314 2315 2316 2317 2318 2319
	#
	# Clear the switch trunks since we are removing ports, which
	# changes that set. 
	#
	$stack->setVlanOnSwitchTrunks($vlanid, 0);
	
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
	if (@staleports) {
	    debug("Removing stale ports from vlan $vlanid: ".Port->toStrings(@staleports)."\n");

	    if (!$impotent) {
		$stack->removeSomePortsFromVlan($vlanid, @staleports)
		    or goto bad;
	    }
	}
	if (@staletrunks) {
	    debug("Removing stale trunked ports from vlan $vlanid: ".
	    Port->toStrings(@staletrunks)."\n");
	    
	    if (!$impotent) {
		$stack->removeSomePortsFromTrunk($vlanid, @staletrunks)
		    or goto bad;
	    }
	}
2337 2338 2339 2340 2341 2342
	#
	# We can optimize this slightly by looking to see if this
	# vlan is going to get new ports below, and waiting till then.
	#
	$stack->setVlanOnSwitchTrunks($vlanid, 1);
	VLan->RecordVlanInsertion($vlanid, $stack->{STACKID});
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
    }

    #
    # Now untrunk the ports that are no longer trunked.
    #
    foreach my $port (keys(%currentTrunks)) { # $port is string here
	if (!exists($needTrunking{$port})) {
	    debug("Disabling trunking on $port\n");
	    
	    next
		if ($impotent);
	
	    doTrunkDisable($stacks, $currentTrunks{$port}) == 0
		or goto bad;

	    delete($currentTrunks{$port});
	}
    }

    #
    # Look for special vlans that need dual trunking.
    #
    foreach my $vlanid (keys(%expvlans)) {
	my $vlan = $expvlans{$vlanid};
	my $trunk_mode;
	$vlan->GetAttribute("trunk_mode", \$trunk_mode);

	# This is set in libvtop.
	if (defined($trunk_mode) && $trunk_mode eq "dual") {
	    my @ports = getVlanPorts($vlanid);
	    my @saveports = @ports;

	    #
	    # If the vlan exists, still want to call CreateOneVlan(),
	    # but only if some ports are not yet in the vlan.
	    #
	    if (exists($curvlans{$vlanid})) {
		my @curports = getExperimentVlanPorts($vlanid);
		my @newports = ();

		foreach my $port (@ports) {
		    push(@newports, $port)
			if (! grep {$_->toString() eq $port->toString()} @curports);
		}
		@ports = @newports;
	    }
	    
	    # Create this vlan now. 
	    debug("Creating dual mode trunking vlan $vlanid: ".Port->toStrings(@ports)."\n")
		if (@ports);
		
	    if (!$impotent && @ports &&
		CreateOneVlan($experiment, $stack, $vlanid, @ports))  {
		print STDERR "Could not create dual trunked $vlan\n";
		goto bad;
	    }
	    # So it is not created below.
	    $curvlans{$vlanid} = 1;
	    
	    # Trunk ports.
	    foreach my $port (@saveports) {
		if (!exists($currentTrunks{$port->toString()})) {
		    debug("Enabling dual mode trunking on ".$port->toString().":$vlanid\n");
		    
		    if (!$impotent &&
			doTrunkEnable($stacks,$port,0,$vlanid)) {
			print STDERR
			    "Could not put ".$port->toString()."($vlanid) into ".
			    "dual trunk mode\n";
			goto bad;
		    }
		}
		# Mark is as being trunked.
		$currentTrunks{$port->toString()} = $port;
	    }
	}
    }

    #
    # And add trunking on any port that needs it.
    #
    foreach my $port (keys(%needTrunking)) {
	if (!exists($currentTrunks{$port})) {
	    debug("Enabling trunking on $port\n");
	    
	    next
		if ($impotent);
	
	    doTrunkEnable($stacks, $needTrunking{$port}, 1) == 0
		or goto bad;

	    # Mark is as being trunked.
	    $currentTrunks{$port} = $needTrunking{$port};
	}
    }

    #
    # Now add ports to existing vlans.
    #
    foreach my $vlanid (keys(%expvlans)) {
	# This one will be built later.
	next
	    if (!exists($curvlans{$vlanid}));
	    
	my @expports   = getVlanPorts($vlanid);
	my @curports   = getExperimentVlanPorts($vlanid);
	my @newports   = ();

	foreach my $port (@expports) {
	    push(@newports, $port)
		if (! grep {$_->toString() eq $port->toString()} @curports);
	}
	next
	    if (!@newports);
	    
	debug("Adding new ports to vlan $vlanid: ".Port->toStrings(@newports)."\n");

	next
	    if ($impotent);
	
2463 2464 2465 2466 2467 2468
	#
	# Clear the switch trunks since we are adding ports, which
	# changes that set. The trunks are added back in CreateOneVlan.
	#
	$stack->setVlanOnSwitchTrunks($vlanid, 0);
 	
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
	if (CreateOneVlan($experiment, $stack, $vlanid, @newports)) {
	    goto bad;
	}
    }

    #
    # Now create vlans that did not exist.
    #
    foreach my $vlanid (keys(%expvlans)) {
	next
	    if (exists($curvlans{$vlanid}));
	    
	my @ports  = getVlanPorts($vlanid);

	debug("Creating new vlan $vlanid: ".Port->toStrings(@ports)."\n");

	next
	    if ($impotent);
	
	if (CreateOneVlan($experiment, $stack, $vlanid, @ports)) {
	    goto bad;
	}
    }
    return 0;

 bad:
    return -1;
}

#
# Reserve vlan tags.
# 
sub doReserveVlanTags($$@) {
    my $experiment = shift;
    my $stacks  = shift;
    my @vlanids = @_;
    my %vlans   = ();
    my %vstacks = ();
    my $errors  = 0;
    my @stacknames = map { $_->{STACKID} } @$stacks;

    if ($ELABINELAB) {
	return RemoteDoReserveVlanTags($experiment, \%optvlantags, @vlanids);
    }
    
    #
    # First do sanity checks on the entire set of vlans
    #
    foreach my $id (@vlanids) {
	my $vlan = VLan->Lookup($id);
	if (!defined($vlan)) {
	    die("Could not locate vlan $id in the DB\n");
	}
	$vlans{"$id"} = $vlan;

	my @planned = getPlannedStacksForVlans($id);
	if (@planned > 1) {
	    print STDERR "$vlan crosses multiple stacks. Cannot reserve tag\n";
	    $errors++;
	    next;
	}
	elsif (@planned == 0) {
	    # Default to the provided stack. Correct thing to do?
	    @planned = @stacknames;
	}
	my $stack = $planned[0];
	
	if (! (grep {$_ eq $stack} @stacknames)) {
	    print STDERR "$vlan is in stack $stack, but not in given stacks!\n";
	    $errors++;
	    next;
	}
	$vstacks{"$id"} = $stack_ids{$stack};
    }
    return $errors
	if ($errors);

    #
    # Now do the reservations. Have to deal with roll back on error.
    #
    my @assigned = ();
    
    foreach my $vlan (values(%vlans)) {
	my $vlanid  = $vlan->id();
	my $stack   = $vstacks{"$vlanid"};
	my @tags    = ();

	#
	# Option to assign a specific tag. This needs to be better.
	#
	if (exists($optvlantags{$vlanid})) {
	    @tags = @{ $optvlantags{$vlanid} };
	}
	elsif ($vlan->GetReservedVlanTag()) {
	    # Wanted any tag, but lan has a tag.
	    next;
	}

      again:
	if (@tags) {
	    $next_vlan_tag = pop(@tags);
	}
	#
	# If we can assign a tag, remember we did so that we can
	# undo whatever we did, if there is an error. 
	#
	my $tag = $stack->newVlanNumber($vlanid, $vlanid);
	if ($tag) {
	    push(@assigned, [$vlan,$tag]);
2578
	    next;
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
	}
	elsif (!$opt{'blockmode'}) {
	    #
	    # In block mode (multiple tags) do not signal an error on failure.
	    # Caller will figure it out.
	    #
	    print STDERR "Could not pre-reserve tag for $vlan\n";
	    $errors++;
	    last;
	}
	goto again
	    if (@tags);
    }
    if ($errors) {
	foreach my $ref (@assigned) {
	    my ($vlan, $tag) = @{ $ref };
	    $vlan->ClearReservedVlanTag($tag);
	}
    }
    return $errors;
}

sub doUnReserveVlanTags($$@) {
    my $experiment = shift;
    my $stacks  = shift;
    my @vlanids = @_;
    my %vlans   = ();
    my %vstacks = ();
    my $errors  = 0;
    my @stacknames = map { $_->{STACKID} } @$stacks;

    if ($ELABINELAB) {
	return RemoteDoUnReserveVlanTags($experiment, \%optvlantags, @vlanids);
    }
    
    #
    # First do sanity checks on the entire set of vlans
    #
    foreach my $id (@vlanids) {
	my $vlan = VLan->Lookup($id);
	if (!defined($vlan)) {
	    die("Could not locate vlan $id in the DB\n");
	}
	$vlans{"$id"} = $vlan;

	my @planned = getPlannedStacksForVlans($id);
	if (@planned > 1) {
	    print STDERR "$vlan crosses multiple stacks. Cannot reserve tag\n";
	    $errors++;
	    next;
	}
	elsif (@planned == 0) {
	    # Default to the provided stack. Correct thing to do?
	    @planned = @stacknames;
	}
	my $stack = $planned[0];
	
	if (! (grep {$_ eq $stack} @stacknames)) {
	    print STDERR "$vlan is in stack $stack, but not in given stacks!\n";
	    $errors++;
	    next;
	}

	#
	# Not allowed to clear the reservation if the lan exists.
	#
	if ($stack_ids{$stack}->vlanExists($id)) {
	    print STDERR
		"$vlan exists on stack $stack; cannot clear reserved tag\n";
	    $errors++;
	    next;
	}
    }
    return $errors
	if ($errors);

    #
    # Now clear the reservations. 
    #
    foreach my $vlan (values(%vlans)) {
	my $vlanid = $vlan->id();

	if (exists($optvlantags{$vlanid})) {
	    foreach my $tag (@{ $optvlantags{$vlanid} }) {
		$vlan->ClearReservedVlanTag($tag);
	    }
	}
	else {
	    $vlan->ClearReservedVlanTag();
	}
    }
    return $errors;
}

#
# Sync the switches and the DB.
# 
sub doSyncVlansWithDB($) {
    my $stacks  = shift;
    my $errors  = 0;
    my %portmap = ();
    my %allports = ();

    if (@$stacks > 1) {
	die "VLAN synchronization across multiple stacks not supported\n" .
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
    }
    my ($stack) = @$stacks;
    my $stackid = ($ELABINELAB ? $stack : $stack->{STACKID});

    #
    # Grab a port mapping of all vlans.
    #
    my @vlanList = $stack->listVlans();
    foreach my $ref (@vlanList) {
	my ($vlan_id,undef,$memberref) = @$ref;
	$portmap{$vlan_id} = []
	    if (!exists($portmap{$vlan_id}));
	$allports{$vlan_id} = []
	    if (!exists($allports{$vlan_id}));

	foreach my $port (@$memberref) {
	    push(@{ $allports{$vlan_id} }, $port);
	    # Convert the ports to node:iface for the next call.
	    push (@{ $portmap{$vlan_id} }, $port);
	}
    }
    #
    # Now check every vlan.
    #
    my %vlans = $stack->findVlans();

    foreach my $vlan_id (keys(%vlans)) {
	my $tag = $vlans{$vlan_id};
	my $vlan;
	    
	if ($vlan_id =~ /^\d*$/) {
	    $vlan = VLan->Lookup($vlan_id);
	}
	else {
	    $vlan = VLan->Lookup($experiment, $vlan_id);
	}
	if (defined($vlan)) {
	    #
	    # Make sure things are consistent.
	    #
	    # This looks in the vlans table.
	    #
	    my $otag = $vlan->GetTag();
	    if (defined($otag) && $otag == $tag) {
		#
		# Make sure in the reserved vlantags table. 
		#
		if (!$vlan->HasVlanTagReserved($tag)) {
		    #
		    # Make consistent by entering into reserved tags.
		    #
		    print "$vlan is using unreserved vlan tag $otag\n";
		    if (!$impotent) {
			print