snmpit.in 116 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2016 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 35
#

#
# 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@;
36
my $GENIRACK   = @PROTOGENI_GENIRACK@;
37 38
my $TB = '@prefix@';

39
use lib '@prefix@/lib';
40 41 42 43 44 45 46 47
use libdb;
use User;
use Experiment;
use libtblog;
use EmulabFeatures;
use Lan;
use English;
use Getopt::Long;
48
use emutil;
49
use strict;
50
use List::Util qw(shuffle);
51

52
# Optional alternate version of libraries.
53
use lib '@prefix@/lib/snmpit';
54 55 56
use snmpit_lib;
use snmpit_remote;

57 58
# Protos
sub parseStatusString($);
59
sub filterList($$);
60 61 62 63 64 65
sub debug($);
sub doListVlans($);
sub doListPorts($);
sub doPortStatus($@);
sub doGetStats($);
sub doVlansFromTables($$@);
66
sub syncVlansFromTables($$@);
67
sub doSyncVlansWithDB($);
68
sub doPruneStaleVlans($);
69 70 71 72 73 74 75 76 77 78 79 80 81
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($$);
82
sub doSetOpenflowController($$$;$);
83 84 85 86
sub doSetOpenflowListener($$$);
sub doEnableOpenflowListener($$);
sub doReserveVlanTags($$@);
sub doUnReserveVlanTags($$@);
87
sub doSetVlanOnTrunks($$@);
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

#
# 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]
120 121
          [--of-disable name pid eid]
          [--of-enable name pid eid]
122
          [--of-controller name pid eid tcp:ip:port [fail-secure]]
123
          [--of-listener name pid eid]
124 125 126 127 128 129 130 131 132
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
133 134
  --skip-supplied If the -S option was given, start with the default stacks, 
                      but skip any switches in the stacks listed in -S.
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
  --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)
165 166
  --of-enable <name> <pid> <eid> 
                    Enable Openflow on VLAN with the name that is 
167
		        associated with the given experiment 
168 169
  --of-disable <name> <pid> <eid>
                    Disable Openflow on VLAN with the name that is 
170
		        associated with the given experiment
171
  --of-controller <name> <pid> <eid> tcp:ip:port
172
                    Set controller for Openflow-enabled VLAN with the 
173 174
		        name that is associated with the given experiment
  --of-listener <name> <pid> <eid> 
175
                    Enable listener for Openflow-enabled VLAN with the 
176
		        name that is associated with the given 
177 178 179 180 181 182 183 184 185 186 187 188 189 190
			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
Leigh B Stoller's avatar
Leigh B Stoller committed
191
  -U <ports>             Turn off trunking for the given <ports>
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  -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',
214
    'shadow', 'skip-supplied', 'whol-magic', 'backtraceonwarning',
215
    'prunestalevlans','setvlanontrunks','resetvlanontrunks','clearvlanontrunks');
216 217 218 219 220 221 222 223 224 225 226 227

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");
}
228 229 230
if ($opt{'backtraceonwarning'}) {
    BackTraceOnWarning(1);
}
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
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 
264
my $ofconnopt; # Openflow option string, for controller 
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
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});
373 374 375 376 377 378 379 380
} elsif ($opt{'setvlanontrunks'} || $opt{'resetvlanontrunks'} ||
         $opt{'clearvlanontrunks'}) {
    if (!@ARGV) {
	tberror "At least one VLAN required";
	exit &usage;
    }
    @optvlanids = @ARGV;

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
} 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;
    }
397 398
    $ofconnopt = shift @ARGV
        if (@ARGV);
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
} 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"]; }
449
if ($opt{'prunestalevlans'}) { push @commands, ["prunestalevlans"]; }
450 451 452
if ($opt{'setvlanontrunks'}) { push @commands, ["setvlanontrunks"]; }
if ($opt{'resetvlanontrunks'}) { push @commands, ["resetvlanontrunks"]; }
if ($opt{'clearvlanontrunks'}) { push @commands, ["clearvlanontrunks"]; }
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 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

# 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}) {
503
            push @ports, convertPortsFromStrings($optdev, $args{port});
504 505
        }
    }
506
    @optports = @ports;
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 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
}

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

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

#
# Options that affect other commands
#

#
# User-supplied switch lists
#
571 572 573 574 575 576 577

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

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
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()
612
my %pvlanArgs = ();
613 614 615 616 617 618 619 620 621
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";
    }
622
    $pvlanArgs{"pvtype"} = $opt{y};
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    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";
	    }
	}
644 645
	$pvlanArgs{"pvprimary"} = $opt{x};
	$pvlanArgs{"pvport"} = $opt{z};
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    }
}

######################################################################
# 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) {	
662
    @ports = convertPortsFromStrings($optdev, @ports);
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
    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/ ||
720
	 /syncvlans/ || /prunestalevlans/) && do {
721
	    @devicenames = ($supplied_switches && !$skip_supplied)?
722 723 724 725
			   @supplied_switches : getTestSwitches();
	    last;
	};
	(/listports/) && do {
726 727 728
	    @devicenames = ($supplied_switches && !$skip_supplied)? 
		           @supplied_switches :
			   (@ports? getDeviceNames(@ports) : getTestSwitches());
729 730 731
	    last;
	};
	( /make/ ) && do {
732 733
	    my ($vlan_name) = @args;

734
            if ($supplied_switches && !$skip_supplied) {
735 736
                @devicenames = @supplied_switches;
            } elsif (@ports) {
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
		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));
753

754 755 756 757 758
		}
		else {
		    # All devices needed includes trunks to transit.
		    @devicenames = mapPortsToSwitches(@ports);
		}
Leigh B Stoller's avatar
Leigh B Stoller committed
759
		debug("make: switch list: " . join(",",@devicenames) . "\n");
760 761 762 763 764 765 766 767 768 769 770
            } 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;
771
            if ($supplied_switches && !$skip_supplied) {
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
                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;
            }
806
            if ($supplied_switches && !$skip_supplied) {
807 808 809 810 811 812 813 814 815 816 817 818 819 820
                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");
            }
821 822 823 824 825 826 827 828 829 830 831
            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;
		}
            }
832 833 834 835 836 837
            if (scalar(@devicenames == 0)) {
                debug("Tables: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
            last;
        };
838 839 840 841 842 843
	(/resetvlanontrunks/ || /setvlanontrunks/ || /clearvlanontrunks/) && do {
	    @devicenames = ($supplied_switches && !$skip_supplied)?
			   @supplied_switches : getTestSwitches();
	    @vlans = @optvlanids;
	    last;
	};
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
	(/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;
            }
869
            if ($supplied_switches && !$skip_supplied) {
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
                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");
            }

885 886 887 888 889 890 891 892 893 894 895 896
            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;
		}
            }

897 898 899 900 901 902 903 904 905 906 907
            # 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.
908
	    @vlans = getExperimentVlans($pid,$eid,@optvlanids);
909 910 911
	    my @oldvlans;
	    VLan->StaleVlanList($experiment,\@oldvlans);

Leigh B Stoller's avatar
Leigh B Stoller committed
912 913 914
	    #
	    # No old or new vlans, then skip all of this. 
	    #
915
	    if (! (@vlans || @oldvlans)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
916 917 918 919 920
                print "snmpit: $pid/$eid has no old or new VLANs ... ".
		    "skipping\n";
                next COMMAND;
	    }

921
            if ($supplied_switches && !$skip_supplied) {
922 923 924
		die("-X and -i cannot be used together\n");
            }
	    else {
925
                @devicenames = uniq(mapVlansToSwitches(@vlans),
926 927 928 929
				    mapStaleVlansToSwitches(@oldvlans));
                debug("Sync: list from database: " . join(",",@devicenames) .
		      "\n");
            }
930 931 932 933 934 935 936 937 938 939 940 941 942

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

943 944 945 946 947 948 949 950 951
            # 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 {
952
	    @devicenames = ($supplied_switches && !$skip_supplied)?
953 954 955 956 957 958 959 960 961 962 963 964
	    		   @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
	    #
965
	    if ($supplied_switches && !$skip_supplied) {
966 967 968 969 970 971
		die "-c and -i or -S cannot be used together\n";
	    }
	    @devicenames = getTestSwitches();
	    last;
	};
	(/trunkenable/) && do {
972
	    @devicenames = ($supplied_switches && !$skip_supplied)?
973 974 975 976 977 978 979 980 981 982 983 984
	    		   @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";
            }
985
            @ports = convertPortsFromStrings($optdev, $args{port}); 
986 987 988
            if ($args{vlan}) {
                @vlans = ($args{vlan});
            }
989
	    @devicenames = ($supplied_switches && !$skip_supplied)?
990 991 992 993 994
		           @supplied_switches : getDeviceNames(@ports);
            @args = %args;
            last;
        };
	(/ofenable/ || /ofdisable/ || /ofcontroller/ || /oflistener/) && do {
995
	    my ($vlan_name) = @args;
996
	    my ($vlanobj, $stack);
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	    if ($vlan_name =~ /^\d*$/) {
		$vlanobj = VLan->Lookup($vlan_name);
	    }
	    else {
		$vlanobj = VLan->Lookup($experiment, $vlan_name);
	    }
	    if (!defined($vlanobj)) {
		print STDERR "No such vlan '$vlan_name' in $experiment\n";
		next COMMAND;
	    }
	    @vlans = ($vlanobj->id());
	    
1009
            if ($supplied_switches && !$skip_supplied) {
1010 1011
                debug("Openflow operations: using supplied switches\n");
                @devicenames = @supplied_switches;
1012 1013
            }
	    elsif (defined($stack = $vlanobj->GetStack())) {
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
                debug("Openflow operations: found stack $stack in database\n");
                @devicenames = getSwitchesInStack($stack);
            } else {
                debug("Openflow operations: using test switches\n");
                @devicenames = getTestSwitches();
            }
	    last;
	};
    }

1024 1025 1026 1027 1028 1029 1030
    #
    # No matter what operation we're doing, we're safe to filter the 
    # devicenames list now!
    #
    @devicenames = filterList(\@devicenames,\@supplied_switches)
        if ($skip_supplied);

1031
    debug("Device names: " . join(",",@devicenames) . "\n");
1032 1033 1034 1035 1036
    debug("Ports: " . join(",", map($_->toIfaceString(), @ports)) . "\n");

    #
    # Order the vlans using the dependency information in the link field.
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
1037 1038
    if (@vlans && ($opt{m} || $opt{t})) {
	my %vlans    = ();
1039 1040
 	my @newvlans = ();
 	my %newvlans = ();
Leigh B Stoller's avatar
Leigh B Stoller committed
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

	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;
	}
1058 1059 1060 1061 1062
 	#
 	# 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 B Stoller's avatar
Leigh B Stoller committed
1063 1064 1065 1066 1067 1068 1069 1070
	while (@vlans) {
	    my @tmp = ();
	    foreach my $vlanid (@vlans) {
		my $vlan = $vlans{$vlanid};

		if (!$vlan->link() ||
		    exists($newvlans{$vlan->link()}) ||
		    !exists($vlans{$vlan->link()})) {
1071
		    push(@newvlans, $vlanid);
Leigh B Stoller's avatar
Leigh B Stoller committed
1072
		    $newvlans{$vlanid} = $vlanid;
1073
		}
Leigh B Stoller's avatar
Leigh B Stoller committed
1074 1075
		else {
		    push(@tmp, $vlanid);
1076
		}
Leigh B Stoller's avatar
Leigh B Stoller committed
1077 1078 1079
	    }
	    @vlans = @tmp;
	}
1080 1081 1082
 	@vlans = reverse(@newvlans);
 	debug("VLANs: " . join(",",@vlans) . "\n");
    }
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

    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 
1205 1206 1207 1208
	/prunestalevlans/ && do {
	    $exitval += doPruneStaleVlans(\@stacks);
	    last;
	}; # /listvlans/ && do 
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	/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 {
1230
	    $exitval += syncVlansFromTables($experiment,\@stacks,@vlans);
1231 1232
	    last;
	}; # /tables/ && do
1233 1234 1235 1236 1237
	(/setvlanontrunks/ || /resetvlanontrunks/ || /clearvlanontrunks/) && do {
	    $exitval +=
		doSetVlanOnTrunks(\@stacks, $operation, @vlans);
	    last;
	}; # /trunkenable/ && do
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
	/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 {
1297 1298
	    $exitval += doSetOpenflowController(\@stacks,$vlans[0],
						$ofconnstr, $ofconnopt);
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
	    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 {
Leigh B Stoller's avatar
Leigh B Stoller committed
1453 1454 1455 1456
	    #
	    # Watch for oddly named vlans on switches we do not fully
	    # control (say, scidmz in Utah).
	    #
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
	    $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
Leigh B Stoller's avatar
Leigh B Stoller committed
1481
            # pid and eid
1482 1483 1484 1485
            if ($opt{O}) {
                next;
            }
            my $vlanexp = $vlan->GetExperiment();
Leigh B Stoller's avatar
Leigh B Stoller committed
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
	    if (!defined($vlanexp)) {
		$pideid = "UNKNOWN";
		$vname  = "UNKNOWN";
	    }
            else {
                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();
	    }
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