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

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

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

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

Leigh B Stoller's avatar
Leigh B Stoller committed
32
33
# Optional alternate version of libraries.
#use lib '@prefix@/lib/snmpit_test';
34
35
36
use snmpit_lib;
use snmpit_remote;

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

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

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

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

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

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

    return 1;
}

my @SAVEARGV = @ARGV;
my %opt = ();
Getopt::Long::Configure("no_ignore_case");
GetOptions(\%opt,
    'a','c','d','e','b','B=s@','g','h','i=s@','l+','m=s@','M','n', 'A', 'C',
    'N=s@','p=s','q','r','s', 'S=s@','t','E=s','T=s','u=s','U','v=s','w',
    'y=s','x=s','z=s','F','L=s','O', 'D', 'R', 'f', 'X', 'Z', 'vlan_tag=i', 
    'of-disable=s', 'of-enable=s', 'of-controller=s', 'of-listener=s',
    'o=s@{1,1}', 'redirect-err', 'blockmode', 'syncvlans', 'impotent',
193
    'shadow', 'skip-supplied');
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273

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

if ($opt{'impotent'}) {
    $impotent = 1;
}

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

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

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

#
# 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);
    }
}
274
if ($opt{'syncvlans'} || $opt{l} || $opt{F}) {
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    $pid = VLAN_PID();
    $eid = VLAN_EID();
    print "Using internal experiment $pid/$eid for operations\n";
}
if ($opt{t} || $opt{r} || $opt{D} || $opt{R} || $opt{X} ||
    $opt{A} || ($opt{C} && !$opt{o})) {
    #
    # Options that take 'pid eid'
    #
    if (!defined($pid)) {
	if (@ARGV < 2) {
	    tberror "pid/eid reqired!";
	    exit &usage;
	} else {
	    ($pid, $eid) = (shift @ARGV, shift @ARGV);
	}
    }
    if (@ARGV) {
	if ($opt{A} || ($opt{C} && !($opt{r} || $opt{o}))) {
	    # Allow a comma separated list of tags per lan.
	    foreach my $arg (@ARGV) {
		if ($arg =~ /^[-\w]*,\d*/) {
		    my @tmp = split(',', $arg);
		    my $id  = shift(@tmp);
		    push(@optvlanids, $id);
		    $optvlantags{$id} = \@tmp;
		}
		else {
		    push(@optvlanids, $arg);
		}
	    }
	}
	else {
	    @optvlanids = @ARGV;
	}
    }
} elsif ($opt{d} || $opt{e} || $opt{a} || $opt{p} || $opt{u} || $opt{m}
         || $opt{U} || $opt{b}) {
    #
    # Options that take a list of ports
    #
    @ports = @ARGV;
} elsif ($opt{T} || $opt{E}) {
    #
    # Options that take both a port and a list of VLANs - we require at least
    # one VLAN to be given
    #
    if ($opt{E}) { $opt{T} = $opt{E}; $equaltrunking = 1;}
    elsif (!@ARGV) {
	tberror "At least one VLAN required";
	exit &usage;
    }
    @optvlanids = @ARGV;

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

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

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

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

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

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

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

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

if ($opt{B}) {
    foreach my $statstring (@{$opt{B}}) {
	push @commands, ["restorestatus",$statstring];
        # Set up the @ports variable so that we get permissions checking. Note,
        # though, that we re-parse the strings again later, this is just for
        # permissions
        my %args = parseStatusString($statstring);
        if (!$args{port}) {
            tbdie "No port given in status string";
        }
        if ($args{port}) {
444
            push @ports, convertPortsFromIfaces($args{port});
445
446
447
448
449
450
451
452
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
        }
    }
}

#
# 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";
    }
492
493
    # XXX Do not make this check when -f is used; called in user context.
    if (defined($this_user) && !$opt{f} && 
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
	!$experiment->AccessCheck($this_user, TB_EXPT_MODIFY)) {
	die "You do not have permission to modify experiment $pid/$eid\n";
    }
}
#
# See if we use the alternate version of snmpit from Rob.
#
if ($MAINSITE && $TB eq "/usr/testbed" && !$opt{Z}) {
    my $group = (defined($experiment) ? $experiment->GetGroup() : undef);
    $EmulabFeatures::verbose = 0;
    my $newsnmpit =
        (EmulabFeatures->FeatureEnabled("RobSnmpit",
					$this_user, $group, $experiment));
    if ($newsnmpit) {
	# Rob, change this path:
	my $newpath = "$TB/bin/snmpit";
	print STDERR "Invoking alternate snmpit from $newpath\n";
	
        unshift(@SAVEARGV, "-Z");
	exec $newpath, @SAVEARGV;
	die("*** $0:\n".
	    "    Could not exec $newpath: $!");
    }
}

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

#
# Options that affect other commands
#

#
# User-supplied switch lists
#
531
532
533
534
535
536
537

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

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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
my @supplied_switches = ();
my @supplied_stacks   = ();
my $supplied_switches = 0; # Whether -i or -S was given
if ($opt{i}) {
    $supplied_switches = 1;
    push @supplied_switches, @{$opt{i}};
}
if ($opt{S}) {
    foreach my $stack (@{$opt{S}}) {
	if ($ELABINELAB) {
	    # We are going to pass the stack argument through in the rpc call.
	    push(@supplied_stacks, $stack);
	}
	else {
	    $supplied_switches = 1;
	    my @switches = getSwitchesInStack($stack);
	    if (@switches) {
		push @supplied_stacks, $stack;
		push @supplied_switches, @switches;
	    } else {
		tbdie({type => 'primary', severity => SEV_ERROR,
		       error => ['invalid_switch_stack', $stack]},
		      "No such switch stack: $stack");
	    }
	}
    }
}
@supplied_switches = uniq(@supplied_switches);
@supplied_stacks   = uniq(@supplied_stacks);

#
# Arguments for making private VLANs
#
# Build up a list of extra arguments to be passed to createVlan()
my @pvlanArgs = ();
if ($opt{y}) {
    #
    # Make sure the private VLAN type they gave is valid, and make sure they
    # gave the other required arugments for certain types
    #
    if ($opt{y} ne "primary" && $opt{y} ne "isolated" &&
	$opt{y} ne "community") {
	die "Unknown private VLAN type $opt{y}\n";
    }
    @pvlanArgs = $opt{y};
    if ($opt{y} ne "primary") {
	if (!$opt{x} || !$opt{z}) {
	    tberror "-x and -z must be given when -y is $opt{y}!";
	    exit &usage;
	}
	#
	# Fix up ports given in the module/port format, like we do below for
	# ports from @ARGV
	#
592
593
594
	if ($opt{z} =~ /^\d+\/\d+?$/) {
	    if ($opt{i} && @{$opt{i}} == 1) {
		$opt{z} = $opt{i}->[0] . "." . $opt{z};
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
	    } else {
		tbdie "The module/port format is only legal if exactly one -i " .
		    "argument has been given";
	    }
	}
	push @pvlanArgs,$opt{x},$opt{z};
    }
}

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

#
# If their operation involves a set of ports, make sure that the caller has
# access to the nodes that the ports are on
#
615

616
# Convert ports into the correct format
617
618
if (@ports) {
    @ports = convertPortsFromIfaces(@ports);
619
620
621
622
623
624
625
}

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...
    #
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
    my (@nodes, @switchports);
    foreach my $port (@ports) {
	if ($port =~ /^([^:]+):\d+$/) {
	    push @nodes, $1;
	} elsif ($port =~ /^([^.]+)\.\d+(\/\d+)?$/) {
	    push @switchports, $port;
	} elsif ($port =~ /^\d+\/\d+?$/) {
	    if ($opt{i} && @{$opt{i}} == 1) {
		$port = $opt{i}->[0] . "." . $port;
		push @switchports, $port;
	    } else {
		die "The module/port format is only legal if exactly one -i " .
		    "argument has been given\n";
	    }
	} else {
	    tbreport(SEV_ERROR, 'bad_data', 'port', $port);
	    die "Bad format for port $port\n"
	}
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
    }

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

662
663
664
665
666
667
#
# snmpit_lib fills out some hashes for speed of lookup later. Initialize
# them now
#
snmpit_lib::init($debug);

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
my $exitval = 0;
COMMAND: foreach my $command (@commands) {

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

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

    #
    # Discover the set of devices we need to talk to. This differs depending
    # on the operation which we're performing. We also get a list of all ports
    # and vlan IDs involved in this operation, if appropriate. We use this
    # opportunity to bail out of the command if it appears we have no work
    # to do
    #
    my @devicenames;
    my @vlans;
    SWITCH: for ($operation) {
	(/listvlans/ || /getstats/ || /vlannumber/ || /synchleader/ ||
	 /syncvlans/) && do {
690
	    @devicenames = ($supplied_switches && !$skip_supplied)?
691
692
693
694
			   @supplied_switches : getTestSwitches();
	    last;
	};
	(/listports/) && do {
695
696
697
	    @devicenames = ($supplied_switches && !$skip_supplied)? 
		           @supplied_switches :
			   (@ports? getDeviceNames(@ports) : getTestSwitches());
698
699
700
	    last;
	};
	( /make/ ) && do {
701
            if ($supplied_switches && !$skip_supplied) {
702
703
704
705
706
707
708
709
710
711
712
713
714
                @devicenames = @supplied_switches;
            } elsif (@ports) {
                # Have to operate on whole stacks so that trunks work
                @devicenames =
                    getSwitchesInStacks(getStacksForSwitches(getDeviceNames(@ports)));
            } else {
                @devicenames = getTestSwitches();
            }
	    last;
	};
        (/remove/) && do {
            # Three levels of possible sources for device names (in order):
            #   passed in on command line
715
            #   vlan from the db
716
717
            #   if others fail, default to experimental switches
	    my ($vlan_name) = @args;
718
            if ($supplied_switches && !$skip_supplied) {
719
720
                debug("Remove: using supplied switches\n");
                @devicenames = @supplied_switches;
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
            }
	    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");
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
                @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;
            }
753
            if ($supplied_switches && !$skip_supplied) {
754
755
756
757
758
759
760
761
762
763
764
765
766
767
                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");
            }
768
769
770
771
772
773
774
775
776
777
778
            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;
		}
            }
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
806
807
808
809
            if (scalar(@devicenames == 0)) {
                debug("Tables: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
            last;
        };
	(/reset/) && do {
	    #
            # We operate on all stacks that we have recorded as having VLANs
            # that belong to this experiment.
	    #
	    @vlans = getExperimentVlans($pid,$eid,@optvlanids);
            if (!@vlans) {
                print "snmpit: $pid/$eid has no VLANs, skipping\n"
		    if (!$quiet);
                next COMMAND;
            }
	    if ($ELABINELAB) {
		#
		# Do not worry about the local state. Always go to outer
		# boss to make sure that the vlans are removed.
		#
		@devicenames = getTestSwitches();
		last;
	    }
            @vlans = filterPlannedVlans(@vlans);
            if (!@vlans) {
                print "snmpit: $pid/$eid has VLANs, but none have been " .
                    "created on switches\n  ... skipping\n";
                next COMMAND;
            }
810
            if ($supplied_switches && !$skip_supplied) {
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
                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");
            }

826
827
828
829
830
831
832
833
834
835
836
837
            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;
		}
            }

838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
            # Fallthrough - if we haven't found any switches yet, operate
            # on the whole experimetnal net
            if (scalar(@devicenames) == 0) {
                debug("Reset: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
	    last;
	};
	(/synctables/) && do {
            # We operate on all stacks on which we think VLANs do, or should,
            # exist.
	    my @newvlans = getExperimentVlans($pid,$eid,@optvlanids);
	    my @oldvlans;
	    VLan->StaleVlanList($experiment,\@oldvlans);

853
            if ($supplied_switches && !$skip_supplied) {
854
855
856
857
858
		die("-X and -i cannot be used together\n");
            }
	    else {
                @devicenames = uniq(mapVlansToSwitches(@newvlans),
				    mapStaleVlansToSwitches(@oldvlans));
859
860
861
                debug("Sync: list from database: " . join(",",@devicenames) .
		      "\n");
            }
862
863
864
865
866
867
868
869
870
871
872
873
874

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

875
876
877
878
879
880
881
882
883
            # 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 {
884
	    @devicenames = ($supplied_switches && !$skip_supplied)?
885
886
887
888
889
890
891
892
893
894
895
896
	    		   @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
	    #
897
	    if ($supplied_switches && !$skip_supplied) {
898
899
900
901
902
903
		die "-c and -i or -S cannot be used together\n";
	    }
	    @devicenames = getTestSwitches();
	    last;
	};
	(/trunkenable/) && do {
904
	    @devicenames = ($supplied_switches && !$skip_supplied)?
905
906
907
908
909
910
911
912
913
914
915
916
	    		   @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";
            }
917
            @ports = convertPortsFromIfaces($args{port});
918
919
920
            if ($args{vlan}) {
                @vlans = ($args{vlan});
            }
921
	    @devicenames = ($supplied_switches && !$skip_supplied)?
Leigh B Stoller's avatar
Leigh B Stoller committed
922
		           @supplied_switches : getDeviceNames(@ports);
923
924
925
926
927
928
929
930
            @args = %args;
            last;
        };
	(/ofenable/ || /ofdisable/ || /ofcontroller/ || /oflistener/) && do {
	    @vlans = @args;

	    # Same to 'remove', we find stacks by VLAN 
	    my ($vlanobj, $stack);
931
            if ($supplied_switches && !$skip_supplied) {
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
                debug("Openflow operations: using supplied switches\n");
                @devicenames = @supplied_switches;
            } elsif (defined($experiment) &&
                     defined($vlanobj = VLan->Lookup($experiment,$vlans[0])) &&
                     defined($stack = $vlanobj->GetStack())) {
                debug("Openflow operations: found stack $stack in database\n");
                @devicenames = getSwitchesInStack($stack);
            } else {
                debug("Openflow operations: using test switches\n");
                @devicenames = getTestSwitches();
            }
	    last;
	};
    }

947
948
949
950
951
952
953
    #
    # No matter what operation we're doing, we're safe to filter the 
    # devicenames list now!
    #
    @devicenames = filterList(\@devicenames,\@supplied_switches)
        if ($skip_supplied);

954
    debug("Device names: " . join(",",@devicenames) . "\n");
955
    debug("Ports: " . join(",",@ports) . "\n");
956

Leigh B Stoller's avatar
Leigh B Stoller committed
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    #
    # Order the vlans using the dependency information in the link field.
    #
    if (@vlans) {
	my %vlans    = map { $_ => VLan->Lookup($_) } @vlans;
	my @newvlans = ();
	my %newvlans = ();
	#
	# 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. 
	#
	while (@vlans) {
	    my @tmp = ();
	    foreach my $vlanid (@vlans) {
		my $vlan = $vlans{$vlanid};

974
975
976
		if (!$vlan->link() ||
		    exists($newvlans{$vlan->link()}) ||
		    !exists($vlans{$vlan->link()})) {
Leigh B Stoller's avatar
Leigh B Stoller committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
		    push(@newvlans, $vlanid);
		    $newvlans{$vlanid} = $vlanid;
		}
		else {
		    push(@tmp, $vlanid);
		}
	    }
	    @vlans = @tmp
	}
	@vlans = reverse(@newvlans);
	debug("VLANs: " . join(",",@vlans) . "\n");

	print "VLANs: " . join(",",@vlans) . "\n";
    }
    
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
    my %stacks = ();
    if (! $ELABINELAB) {
	#
	# Map all the devices to stacks.
	#
	foreach my $devicename (@devicenames) {
	    my $stack = getSwitchPrimaryStack($devicename);
	    if (defined($stack)) {
		push @{$stacks{$stack}}, $devicename;
	    }
	}
    }

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

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

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

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


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

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

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

exit $exitval;

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

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

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

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

    return %pairs;
}

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

    my $stacks = shift;
    my %vlans;
Leigh B Stoller's avatar
Leigh B Stoller committed
1248
    my %tags;
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
    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;
Leigh B Stoller's avatar
Leigh B Stoller committed
1265
	    $tags{$ddep} = $id;
1266
1267
1268
1269
1270
1271
1272
1273
            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;
Leigh B Stoller's avatar
Leigh B Stoller committed
1274
		$tags{$ddep} = $id;
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
                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;
1288
1289
	    my $vlan = "$in#" . ${$vlans{$out}}[0] . "#" .
				    join(' ', @{${$vlans{$out}}[1]});
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
	    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 =
1313
@<<<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1314
$vlan_id,$pideid,           $vname,   $members
1315
~~                                              ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1316
1317
1318
1319
1320
                                      $members
.
	$FORMAT_NAME = 'vlanlist';
    } else {
    	print << "END";
1321
1322
VLAN     Number Project/Experiment VName     Members
--------------------------------------------------------------------------------
1323
1324
END
	format vlanlist2 =
1325
@<<<<<<< @<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1326
$vlan_id,$ddep, $pideid,           $vname,   $members
1327
~~                                                     ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1328
1329
1330
                                             $members
.
	$FORMAT_NAME = 'vlanlist2';
Leigh B Stoller's avatar
Leigh B Stoller committed
1331
1332
1333
1334
    }
    my @sorted = ($opt{w} ?
                  map {$tags{$_}} sort {tbsort($a,$b)} keys %tags :
                  sort {tbsort($a,$b)} keys %vlans);
1335

Leigh B Stoller's avatar
Leigh B Stoller committed
1336
    foreach my $vid (@sorted) {
1337
1338
        $vlan_id = $vid;
	my $memberref;
Leigh B Stoller's avatar
Leigh B Stoller committed
1339
        my $vlan;
1340
	($ddep,$memberref) = @{$vlans{$vid}};
Leigh B Stoller's avatar
Leigh B Stoller committed
1341
1342
1343
1344
1345
1346
1347

	if ($vlan_id =~ /^\d*$/) {
	    $vlan = VLan->Lookup($vlan_id);
	}
	else {
	    $vlan = VLan->Lookup($experiment, $vlan_id);
	}
1348
        if (!defined($vlan)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1349
	    print("No such VLAN $vlan_id in lans table\n");
1350
1351
1352
1353
1354
1355
            # 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
Leigh B Stoller's avatar
Leigh B Stoller committed
1356
            if ($opt{O} && $vlan_id !~ /^\d+$/) {
1357
1358
                next;
            }
Leigh B Stoller's avatar
Leigh B Stoller committed
1359
1360

            # Only admins get to see this. Possibly a silly check.
1361
1362
1363
1364
	    if (!TBAdmin()) {
		&debug("Failed TBAdmin check\n");
		next;
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1365
1366
1367
1368
	    $pideid = "";
            $vname  = $vlan_id;
        }
	else {
1369
1370
1371
1372
1373
            # If only printing orphaned VLANs, skip ones for which we know the
            # pid and ied
            if ($opt{O}) {
                next;
            }
Leigh B Stoller's avatar
Leigh B Stoller committed
1374
            my $vlanexp = $vlan->GetExperiment();
1375
            if ($UID &&
Leigh B Stoller's avatar
Leigh B Stoller committed
1376
		!$vlanexp->AccessCheck($this_user, TB_EXPT_READINFO)) {
1377
1378
1379
                &debug("$this_user failed access check to $experiment\n");
                next;
            }
Leigh B Stoller's avatar
Leigh B Stoller committed
1380
1381
1382
1383
   	    # Setup $pideid for a more compact display
            $pideid = $vlan->pid() . "/" . $vlan->eid();
            $vname  = $vlan->vname();
	}
1384
1385
1386
1387
1388
1389

	#
	# 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)
1390
	    $members = join(" ", map
1391
		{
1392
1393
		    macport($_)? (split /:/)[0] . ":" . macport($_) : $_
		} @$memberref);
1394
	} else {
1395
	    $members = join(" ",@$memberref);
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
	}
	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) {
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
	    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;
	    }
	    
1436
1437
1438
	    if (($num >= $leader->{MIN_VLAN}) &&
		($num <= $leader->{MAX_VLAN}) &&
		!($leader->vlanNumberExists($num))) {
1439
		$errors += $leader->createVlan($id, $vlan->lanid(), $num);
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
	    }
	}
    }
    return $errors;
}

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

    my $stacks = shift;

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

    #
    # See perlform(1) for help with formats
    #
    our ($port,$enabled,$up,$speed,$duplex);
    print << "END";
Port      Enabled Up   Speed      Duplex
--------------------------------------------
END
    format portlist =
1470
1471
@<<<<<<<< @<<<<<< @<<< @<<<<<<<<< @<<<<<<<<<
$port,    $enabled,$up,$speed,$duplex
1472
1473
1474
1475
1476
1477
1478
.
    $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
	#
1479
1480
	$port =~ /^(.+):/;
	my $node = $1;
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522

	&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) {
1523
        $ports{$port} = undef;
1524
1525
1526
    }
    foreach my $portrecord (@portList) {
	my ($port,$enabled,$up,$speed,$duplex) = @$portrecord;
1527
1528
1529
        if (exists $ports{$port}) {
            $ports{$port} = "enabled=$enabled";
            $ports{$port} .= ";speed=$speed";
1530
            if ($speed ne "autoDetect") {
1531
                $ports{$port} .= ";duplex=$duplex";
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
            }
        }
    }

    #
    # 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) {
1545
1546
                if ($ports{$port}) {
                    $ports{$port} .= ";vlan=$id";
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
                }
            }
	}
    }

    #
    # 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
Leigh B Stoller's avatar
Leigh B Stoller committed
1585
    my $errors = 0;
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597

    my $port = $params{port};
    if (!$port) {
        tbdie "No port passed to -B option";
    }

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

Leigh B Stoller's avatar
Leigh B Stoller committed
1598
1599
1600
1601
1602
1603
    #
    # 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;
1604

Leigh B Stoller's avatar
Leigh B Stoller committed
1605
    #
1606
1607
    # Put the port in the specified VLAN
    # If they didn't give us a VLAN, we assume that means they want it removed
Leigh B Stoller's avatar
Leigh B Stoller committed
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
    # 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);
1624
1625
    if ($errors) { return $errors; }

Leigh B Stoller's avatar
Leigh B Stoller committed
1626
1627
1628
1629
1630
    if (defined($source_vlan) && $source_vlan->KeepInSync()) {
	if ($source_vlan->DelPort($port)) {
	    print "Could not yank $port from $source_vlan\n";
	    $errors++;
	}
1631
	my @tmp = ($port);
1632
	VLan->RecordVLanModification($source_vlan->id(), undef, \@tmp);
Leigh B Stoller's avatar
Leigh B Stoller committed
1633
1634
1635
1636
1637
1638
1639
1640
1641
    }
    if (defined($target_vlan) && $target_vlan->KeepInSync()) {
	if ($target_vlan->AddPort($port)) {
	    print "Could not add $port to $target_vlan\n";
	    $errors++;
	}
	VLan->RecordVlanInsertion($target_vlan->id(), $stack->{STACKID});
    }

1642
1643
1644
1645
1646
    # 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
Leigh B Stoller's avatar
Leigh B Stoller committed
1647
    if ($vlan_id eq "default") { $enabled = "no"; }
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
    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 {
1668
                tbwarn "Bad speed given for $port: $speed";
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
                $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 {
1680
            tbwarn "Bad duplex given for $port: $duplex";
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
            $errors++;
        }
    }
    return $errors;
}

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

    my $stacks = shift;

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

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

#    $debug = 1;
1756
1757
#    $stack->FlipDebug(1);
    
1758
1759
    my @trunkedPorts = getExperimentTrunks($experiment->pid(),
					   $experiment->eid());
1760
    my %trunkedPorts = map { $_ => $_ } @trunkedPorts;
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791

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

	# This is set in libvtop.
	if (defined($trunk_mode) && $trunk_mode eq "dual") {
	    my @ports = getVlanPorts($vlanid);
	    
	    # Create this vlan now.
	    if (CreateOneVlan($experiment,$stack, $vlanid, @ports))  {
		die("Could not create dual trunked $vlan\n");
	    }
	    # Trunk these ports, removing from list.
	    foreach my $port (@ports) {
		if (doTrunkEnable($stacks,$port,0,$vlanid)) {
1792
		    die("Could not put $port ($vlan) into dual trunk mode\n");
1793
		}
1794
		delete($trunkedPorts{$port});
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
	    }
	    
	    #
	    # Set openflow
	    #
	    # A much more right place for the openflow settings is CreateOneVlan,
	    # however, it is called by sync vlan function and others, which don't destroy
	    # the existing vlan_arrtibutes rows.
	    #
	    # TODO: Move this part to CreateOneVlan and Make sure the existed 
	    #       vlan_attributes rows are deleted
	    #
	    my $ofenabled;
	    $vlan->GetAttribute("ofenabled", \$ofenabled);
	    if (defined($ofenabled) && $ofenabled == 1) {
	        $errors += doOpenflowEnable($stacks, $vlanid);
	    
	        my $ofcontroller;
	        $vlan->GetAttribute("ofcontroller", \$ofcontroller);
	        if (defined($ofcontroller) && $ofcontroller ne "") {
	            $errors += doSetOpenflowController($stacks, $vlanid, $ofcontroller);
	        }
	    
	        $errors += doEnableOpenflowListener($stacks, $vlanid);
	    
	        # doEnableOpenflowListener updates the lan_arrtibutes table, so vlan 
	        # should refresh itself. But here vlan will not be used any more, so
	        # maybe we can comment this refresh.
	        $vlan->Refresh();	    
	    }
	    
	    # Delete this vlan from the list that will be created below.
	    delete($vlans{"$vlanid"});
	}
    }
    # Do the rest of the trunked ports in equalmode.
    foreach my $port (keys(%trunkedPorts)) {
1832
	$errors += doTrunkEnable($stacks,$port,1);
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
    }

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

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

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

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

    if ($stack->vlanExists($vlanid)) {
	print "  VLAN $vlanid already exists\n"
	    if (!$quiet);
	if ($stack->setPortVlan($vlanid,@ports)) {
	    $errors++;
	}
	else {
	    # Convert the ports to node:iface for the next call.
1917
1918
	    my @conports = map { portiface($_) } @ports;

1919
1920
1921
1922
	    VLan->RecordVLanModification($vlanid, \@conports, undef);
	}
    }
    else {
1923
	my $vlan_number = $stack->createVlan($vlanid, $vlanid, \@ports);
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
	if (!$vlan_number) {
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['create_vlan_failed', $vlanid]},
		    "Failed to create VLAN with id $vlanid");
	    #
	    # Don't try to put ports in a VLAN if it couldn't be created
	    #
	    $errors++;
	}
	else {
Leigh B Stoller's avatar
Leigh B Stoller committed
1934
	    VLan->RecordVlanInsertion($vlanid, $stack->{STACKID});
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
	}
    }
    return $errors
	if ($errors);

    #
    # 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;
		}
	    }
	}
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
    #
    # Look for a layer 1 link; There is a logical wire that needs to be
    # activated once it is created. 
    #
    my $vlan = VLan->Lookup($vlanid);
    if ($vlan->type() eq "wire") {
	my $wireid;
	
	if ($vlan->GetAttribute("logicalwireid", \$wireid) == 0) {
	    my $wire = Interface::Wire->Lookup($wireid);
	    if (!defined($wire)) {
		print STDERR "Could not logical wire for $vlan ($wireid)\n";
		$errors++;
	    }
	    else {
		if ($wire->Activate() != 0) {
		    print STDERR "Could not activate $wire for $vlan\n";
		    $errors++;
		}
	    }
	}
    }
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
    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 = @_;
Leigh B Stoller's avatar
Leigh B Stoller committed
2002
    my %wires = ();
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019

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

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

2020
    $debug = 1;
2021

Leigh B Stoller's avatar
Leigh B Stoller committed
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
    #
    # Look for a layer 1 link; There is a logical wire that needs to be
    # deactivated once it is created, but must ensure that the logical
    # wire is not actually in use.
    #
    foreach my $vlan_id (@vlans) {
	my $vlan = VLan->Lookup($vlan_id);
	my $wireid;

	next
	    if (! $vlan->type() eq "wire");
	
	if ($vlan->GetAttribute("logicalwireid", \$wireid) == 0) {
	    my $wire = Interface::Wire->Lookup($wireid);
	    if (!defined($wire)) {
		print STDERR "Could not logical wire for $vlan ($wireid)\n";
		return -1;
	    }
	    # need the interfaces.
	    my ($interface1, $interface2) = $wire->Interfaces();
	    if (!defined($interface1)) {
		print STDERR "No interface for logical wire $wire\n";
		return -1;
	    }
	    # Find the vlan that uses this interface.
Leigh B Stoller's avatar
Leigh B Stoller committed
2047
	    my $vlanusing = VLan->FindVlanByInterface($experiment, $interface1);
Leigh B Stoller's avatar
Leigh B Stoller committed
2048
2049
2050
2051
2052
2053
2054
2055
2056
	    if (defined($vlanusing) && $vlanusing->CreatedOnSwitches()) {
		print STDERR "Logical wire $wire is in use by $vlanusing; ".
		    "not allowed to remove $vlan\n";
		return -1;
	    }
	    $wires{$vlan->lanid()} = $wire;
	}
    }

2057
2058
2059
2060
2061
    #
    # Just remove the VLAN from every stack on which it exists. We keep a
    # list and do them all at once for efficiency.
    #
    foreach my $stack (@$stacks) {
2062
#	$stack->FlipDebug(1);
2063
	
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
	my @existant_vlans = $stack->existantVlans(@vlans);
	if (!$stack->removeVlan(@existant_vlans)) {
	    #
	    # Find out what still exists so that we keep the DB state.
	    #
	    foreach my $vlan_id (@existant_vlans) {
		if ($stack->vlanExists($vlan_id)) {
		    print "  $vlan_id was not deleted.\n";
		    $notdeleted{$vlan_id} = 1;
		}
	    }
	    $errors++;
	}
    }
    foreach my $vlan_id (@vlans) {
	next
	    if (exists($notdeleted{$vlan_id}));
	
	clearReservedVlanTag($vlan_id)
	    if ($opt{C});
	VLan->RecordVLanDeletion($vlan_id);
Leigh B Stoller's avatar
Leigh B Stoller committed
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095

	# Deactivate the logical wire.
	if (exists($wires{$vlan_id})) {
	    my $wire = $wires{$vlan_id};
	    
	    print "Deactivating logical wire $wire\n";
	    if ($wire->DeActivate() != 0) {
		print STDERR "Could not deactivate $wire for vlan $vlan_id\n";
		$errors++;
	    }
	}
Leigh B Stoller's avatar