snmpit.in 116 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2019 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
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 Stoller's avatar
Leigh 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
	    my @oldvlans = ();
909
	    @vlans = getExperimentVlans($pid,$eid,@optvlanids);
910 911 912 913
	    
	    if (!@optvlanids) {
		VLan->StaleVlanList($experiment,\@oldvlans);
	    }
914

915 916 917
	    #
	    # No old or new vlans, then skip all of this. 
	    #
918
	    if (! (@vlans || @oldvlans)) {
919 920 921 922 923
                print "snmpit: $pid/$eid has no old or new VLANs ... ".
		    "skipping\n";
                next COMMAND;
	    }

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

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

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

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

1034
    debug("Device names: " . join(",",@devicenames) . "\n");
1035 1036 1037 1038 1039
    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
1040 1041
    if (@vlans && ($opt{m} || $opt{t})) {
	my %vlans    = ();
1042 1043
 	my @newvlans = ();
 	my %newvlans = ();
Leigh Stoller's avatar
Leigh Stoller committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

	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;
	}
1061 1062 1063 1064 1065
 	#
 	# 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
1066 1067 1068 1069 1070 1071 1072 1073
	while (@vlans) {
	    my @tmp = ();
	    foreach my $vlanid (@vlans) {
		my $vlan = $vlans{$vlanid};

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

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

	#
	# 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";
1599 1600
Port              Enabled Up   Speed      Duplex
------------------------------------------------
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
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; }

1770 1771 1772 1773
    #
    # Do not worry about mucking with the switch trunk paths.
    # This call exists to temporarily move ports back and forth.
    #
1774 1775 1776 1777 1778
    if (defined($source_vlan) && $source_vlan->KeepInSync()) {
	if ($source_vlan->DelPort($port)) {
	    print "Could not yank $port from $source_vlan\n";
	    $errors++;
	}
1779 1780 1781 1782
	if (VLan->RecordVlanInsertion($source_vlan->id(), $stack->{STACKID})){
	    print "Could not record vlan insertion for $source_vlan\n";
	    $errors++;
	}
1783 1784 1785 1786 1787 1788
    }
    if (defined($target_vlan) && $target_vlan->KeepInSync()) {
	if ($target_vlan->AddPort($port)) {
	    print "Could not add $port to $target_vlan\n";
	    $errors++;
	}
1789 1790 1791 1792
	if (VLan->RecordVlanInsertion($target_vlan->id(), $stack->{STACKID})){
	    print "Could not record vlan insertion for $target_vlan\n";
	    $errors++;
	}
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
    }

    # 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";
1862 1863 1864
                                 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
-------------------------------------------------------------------------------------------------------------------------------------------------
1865 1866
END
    format stats =
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
$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);   

1912
    my %trunkedPorts = getExperimentTrunks($experiment->pid(),
1913
					   $experiment->eid(), @vlanids);
1914 1915 1916 1917 1918 1919 1920 1921

    #
    # 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. 
    #
1922 1923
    my %dualTrunkPorts = ();
    
1924 1925 1926 1927 1928 1929 1930
    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;
    }
1931
    
1932 1933 1934 1935
    foreach my $vlan (values(%vlans)) {
	my $vlanid = $vlan->id();
	my $trunk_mode;
	$vlan->GetAttribute("trunk_mode", \$trunk_mode);
1936 1937
	my $trunk_vlanid;
	$vlan->GetAttribute("trunk_vlan", \$trunk_vlanid);
1938 1939 1940 1941

	# This is set in libvtop.
	if (defined($trunk_mode) && $trunk_mode eq "dual") {
	    my @ports = getVlanPorts($vlanid);
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

	    #
	    # If a specific vlan listed, it must already exist.
	    #
	    if (defined($trunk_vlanid)) {
		my $trunk_vlan = VLan->Lookup($trunk_vlanid);
		if (!defined($trunk_vlan)) {
		    die("Trunk vlanid $trunk_vlanid does not exist\n");
		}
		if (!$trunk_vlan->CreatedOnSwitches()) {
		    die("Trunk vlanid $trunk_vlan is not instantiated\n");
		}
1954 1955 1956 1957 1958
		#
		# To maintain backwards compatibility with how snmpit used
		# to operate, "internal" vlans are sometimes named on the switch
		# by the symbolic name instead of the lanid.
		#
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
		if ($trunk_vlan->IsInternal() &&
		    !$stack->vlanExists($trunk_vlanid)) {
		    $trunk_vlanid = $trunk_vlan->vname();
		}
		    
		#
		# For each port that has not yet been put into trunk
		# mode, do that using the trunk_vlanid as the native.
		#
		foreach my $port (@ports) {
		    if (!IsPortTagged($port) &&
			doTrunkEnable($stacks,$port,0,$trunk_vlanid)) {
			die("Could not put $port ($trunk_vlan) into ".
			    "dual trunk mode\n");
		    }
		    delete($trunkedPorts{$port->toString()});
		}
		# Now we can create the actual vlan.
		if (CreateOneVlan($experiment,$stack, $vlanid, @ports))  {
		    die("Could not create dual trunked $vlan\n");
		}
	    }
	    else {
		# 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 port $port ($vlan) into ".
			    "dual trunk mode\n");
		    }
		    delete($trunkedPorts{$port->toString()});
1993 1994
		}
	    }
1995

1996 1997 1998 1999
	    # Delete this vlan from the list that will be created below.
	    delete($vlans{"$vlanid"});
	}
    }
2000
    #
2001
    # Do the rest of the trunked ports in equalmode.
2002 2003 2004
    #
    foreach my $port (values(%trunkedPorts)) {
	$errors += doTrunkEnable($stacks,$port,1);
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
    }

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

2036
	$errors += CreateOneVlan($experiment, $stack, $vlanid, @ports);	
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    }
    return $errors;
}

#
# Create a single vlan.
#
sub CreateOneVlan($$$@)
{
    my $experiment = shift();
    my $stack  = shift();
    my $vlanid = shift();
    my @ports  = @_;
2050
    my %otherargs = ();
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
    my $errors = 0;

    if ($stack->vlanExists($vlanid)) {
	print "  VLAN $vlanid already exists\n"
	    if (!$quiet);
	if ($stack->setPortVlan($vlanid,@ports)) {
	    $errors++;
	}
    }
    else {
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
	#
	# Check and see if OF was requested.  If so, check to make sure
	# all switches in scope support it.  Fail early if not.
	#
	my $vlan = VLan->Lookup($vlanid);
	if (!defined($vlan)) {
	    die("Could not locate vlan $vlanid in the DB\n");
	}
	my $ofenabled;
	$vlan->GetAttribute("ofenabled", \$ofenabled);
	$ofenabled = (defined($ofenabled) && $ofenabled == 1) ? 1 : 0;
	if ($ofenabled) {
	    if (!$stack->isOpenflowSupported(@ports)) {
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['create_vlan_failed', $vlanid]},
			"OpenFlow requested for VLAN $vlanid, but ".
			"is not supported on all switches in scope.\n");
		return 1;
	    }
2080
	    $otherargs{"ofenabled"} = 1;
2081 2082 2083
	    # XXX: Some internal calls to snmpit_stack::createVlan()
	    # still need to get special vlan arguments this way.
	    $stack->{VLAN_SPECIALARGS}->{$vlanid}->{"ofenabled"} = 1;
2084 2085
	}

2086 2087
	my $vlan_number = $stack->createVlan($vlanid, $vlanid, 
					     \@ports, \%otherargs);
2088 2089 2090 2091 2092
	if (!$vlan_number) {
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['create_vlan_failed', $vlanid]},
		    "Failed to create VLAN with id $vlanid");
	    #
2093 2094 2095
	    # Don't try to put ports in a VLAN if it couldn't be created.
	    # Lets make sure the vlan is not partially created, lest we
	    # have a vlan on the switch but not in the DB.
2096
	    #
2097 2098 2099
	    if (!$stack->removeVlan($vlanid)) {
		print STDERR "*** Could not remove failed vlan: $vlanid\n";
	    }
2100
	    $errors++;
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
	} else {
	    #
	    # Set up and enable openflow, if requested.
	    #
	    if ($ofenabled) {
	        my $ofcontroller;
	        $vlan->GetAttribute("ofcontroller", \$ofcontroller);
	        if (defined($ofcontroller) && $ofcontroller ne "") {
	            $errors += doSetOpenflowController([$stack], $vlanid,
						       $ofcontroller);
	        }
	        $errors += doEnableOpenflowListener([$stack], $vlanid);
	        $errors += doOpenflowEnable([$stack], $vlanid);

	        # doEnableOpenflowListener updates the lan_attributes table,
	        # so vlan should refresh itself.
	        $vlan->Refresh();
	    }
2119 2120 2121 2122 2123
	}
    }
    return $errors
	if ($errors);

2124 2125 2126 2127
    #
    # Record an insertion to make sure the DB reflects the current state
    # of the vlan. 
    #
2128 2129 2130 2131
    if (VLan->RecordVlanInsertion($vlanid, $stack->{STACKID})) {
	print STDERR "Could not record vlan insertion for $vlanid\n";
	$errors++;
    }
2132

2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
    #
    # 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;
		}
	    }
	}
    }
2162 2163 2164 2165 2166 2167 2168 2169 2170
    #
    # 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) {
2171
	    my $wire = Interface::LogicalWire->LookupByWireID($wireid);
2172
	    if (!defined($wire)) {
2173
		print STDERR "Could not get logical wire for $vlan ($wireid)\n";
2174 2175 2176
		$errors++;
	    }
	    else {
2177
		if ($wire->Activate($vlan) != 0) {
2178 2179 2180 2181 2182 2183
		    print STDERR "Could not activate $wire for $vlan\n";
		    $errors++;
		}
	    }
	}
    }
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
    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 = @_;
2195
    my %wires = ();
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205

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

    my $errors = 0;
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
    my %trunkedPorts = getExperimentTrunks($pid, $eid, @vlans);
    my @controlports = ();
    foreach my $port (values(%trunkedPorts)) {
	#
	# If operating on the control interface, the trunk disable
	# will remove the port from the control vlan. Move it back.
	#
	if (doTrunkDisable($stacks,$port) == 0) {
	    push(@controlports, $port)
		if ($port->role() eq TBDB_IFACEROLE_CONTROL());
	}
	else {
	    $errors++;
	}
    }
    return -1
	if ($errors);