new_snmpit.in 93.6 KB
Newer Older
Weibin Sun's avatar
Weibin Sun committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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
#

use lib '@prefix@/lib';
my $TESTMODE   = @TESTMODE@;
my $ELABINELAB = @ELABINELAB@;
my $NOSTACKMIB = @NOSTACKMIB@;
my $MAINSITE   = @TBMAINSITE@;
my $TB = '@prefix@';

use libdb;
use User;
use Experiment;
26
use new_snmpit_lib;
Weibin Sun's avatar
Weibin Sun committed
27
28
29
30
use snmpit_remote;
use libtblog;
use EmulabFeatures;
use Port;
31
use Lan;
Weibin Sun's avatar
Weibin Sun committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45

use English;
use Getopt::Long;
use strict;

# Protos
sub parseStatusString($);
sub debug($);
sub doListVlans($);
sub doListPorts($);
sub doPortStatus($@);
sub doGetStats($);
sub doVlansFromTables($$@);
sub syncVlansFromTables($$);
46
sub doSyncVlansWithDB($);
Weibin Sun's avatar
Weibin Sun committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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;
71
my $impotent = 0;
Weibin Sun's avatar
Weibin Sun committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
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
  --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',
189
190
    'o=s@{1,1}', 'redirect-err', 'blockmode', 'syncvlans', 'impotent',
    'shadow');
Weibin Sun's avatar
Weibin Sun committed
191
192
193
194
195
196
197
198
199
200
201
202
203

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

204
205
206
207
if ($opt{'impotent'}) {
    $impotent = 1;
}

Weibin Sun's avatar
Weibin Sun committed
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
if ($opt{v}) {
    $debug = $opt{v};
    print "Debug level is $debug\n";
}

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

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


#
# Move this initialization ahead from its previous location so that
# the ports converters can be used when parsing command line args.
#
# snmpit_lib fills out some hashes for speed of lookup later. Initialize
# them now
#
249
new_snmpit_lib::init($debug);
Weibin Sun's avatar
Weibin Sun committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277

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());
	}
278
279
280
	$pid = VLAN_PID();
	$eid = VLAN_EID();
	print "Using internal experiment $pid/$eid for operations\n";
Weibin Sun's avatar
Weibin Sun committed
281
282
283
284
285
    }
    else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
    }
}
286
287
288
289
290
if ($opt{'syncvlans'} || $opt{l} || $opt{F}) {
    $pid = VLAN_PID();
    $eid = VLAN_EID();
    print "Using internal experiment $pid/$eid for operations\n";
}
Weibin Sun's avatar
Weibin Sun committed
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
if ($opt{t} || $opt{r} || $opt{D} || $opt{R} || $opt{X} ||
    $opt{A} || ($opt{C} && !$opt{o})) {
    #
    # Options that take 'pid eid'
    #
    if (!defined($pid)) {
	if (@ARGV < 2) {
	    tberror "pid/eid reqired!";
	    exit &usage;
	} else {
	    ($pid, $eid) = (shift @ARGV, shift @ARGV);
	}
    }
    if (@ARGV) {
	if ($opt{A} || ($opt{C} && !($opt{r} || $opt{o}))) {
	    # Allow a comma separated list of tags per lan.
	    foreach my $arg (@ARGV) {
		if ($arg =~ /^[-\w]*,\d*/) {
		    my @tmp = split(',', $arg);
		    my $id  = shift(@tmp);
		    push(@optvlanids, $id);
		    $optvlantags{$id} = \@tmp;
		}
		else {
		    push(@optvlanids, $arg);
		}
	    }
	}
	else {
	    @optvlanids = @ARGV;
	}
    }
} elsif ($opt{d} || $opt{e} || $opt{a} || $opt{p} || $opt{u} || $opt{m}
         || $opt{U} || $opt{b}) {
    #
    # Options that take a list of ports
    #
    @ports = @ARGV;
} elsif ($opt{T} || $opt{E}) {
    #
    # Options that take both a port and a list of VLANs - we require at least
    # one VLAN to be given
    #
    if ($opt{E}) { $opt{T} = $opt{E}; $equaltrunking = 1;}
    elsif (!@ARGV) {
	tberror "At least one VLAN required";
	exit &usage;
    }
    @optvlanids = @ARGV;

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

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

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

#
# Simple commands
#
if ($opt{l}) { push @commands, ["listvlans"]; }
if ($opt{L}) { push @commands, ["listvlans"]; }
if ($opt{s}) { push @commands, ["listports"]; }
if ($opt{g}) { push @commands, ["getstats"]; }
if ($opt{t}) { push @commands, ["tables"]; }
if ($opt{r}) { push @commands, ["reset"]; }
if ($opt{X}) { push @commands, ["synctables"]; }
if ($opt{c}) { push @commands, ["recreate"]; }
if ($opt{U}) { push @commands, ["trunkdisable"]; }
if ($opt{b}) { push @commands, ["portstatus"]; }
if ($opt{F}) { push @commands, ["synchleader"]; }
if ($opt{A}) { push @commands, ["reservetags"]; }
410
if ($opt{'syncvlans'}) { push @commands, ["syncvlans"]; }
Weibin Sun's avatar
Weibin Sun committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
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
503
504
505
506
507
508
509

# 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}) {
            push @ports, convertPortsFromStrings($args{port}, $optdev);
            # @@@@ !!!! #push @ports, convertPortsFromIfaces($args{port});
        }
    }
}

#
# 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";
    }
510
511
    # XXX Do not make this check when -f is used; called in user context.
    if (defined($this_user) && !$opt{f} && 
Weibin Sun's avatar
Weibin Sun committed
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
	!$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
#
my @supplied_switches = ();
my @supplied_stacks   = ();
my $supplied_switches = 0; # Whether -i or -S was given
if ($opt{i}) {
    $supplied_switches = 1;
    push @supplied_switches, @{$opt{i}};
}
if ($opt{S}) {
    foreach my $stack (@{$opt{S}}) {
	if ($ELABINELAB) {
	    # We are going to pass the stack argument through in the rpc call.
	    push(@supplied_stacks, $stack);
	}
	else {
	    $supplied_switches = 1;
	    my @switches = getSwitchesInStack($stack);
	    if (@switches) {
		push @supplied_stacks, $stack;
		push @supplied_switches, @switches;
	    } else {
		tbdie({type => 'primary', severity => SEV_ERROR,
		       error => ['invalid_switch_stack', $stack]},
		      "No such switch stack: $stack");
	    }
	}
    }
}
@supplied_switches = uniq(@supplied_switches);
@supplied_stacks   = uniq(@supplied_stacks);

#
# Arguments for making private VLANs
#
# Build up a list of extra arguments to be passed to createVlan()
my @pvlanArgs = ();
if ($opt{y}) {
    #
    # Make sure the private VLAN type they gave is valid, and make sure they
    # gave the other required arugments for certain types
    #
    if ($opt{y} ne "primary" && $opt{y} ne "isolated" &&
	$opt{y} ne "community") {
	die "Unknown private VLAN type $opt{y}\n";
    }
    @pvlanArgs = $opt{y};
    if ($opt{y} ne "primary") {
	if (!$opt{x} || !$opt{z}) {
	    tberror "-x and -z must be given when -y is $opt{y}!";
	    exit &usage;
	}
	#
	# Fix up ports given in the module/port format, like we do below for
	# ports from @ARGV
	#
	my ($c, $p) = Port->ParseCardPortString($opt{z});
	if (defined($c) && defined($p)) {
	    if (defined($optdev)) {
		$opt{z} = Port->Triple2Iface(Port->Tokens2TripleString($optdev, $c, $p));
607
608
609
		if (!defined($opt{z})) {
		    tbdie "Port $c:$p not found";
		}
Weibin Sun's avatar
Weibin Sun committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
	    } else {
		tbdie "The module/port format is only legal if exactly one -i " .
		    "argument has been given";
	    }
	}
	# if ($opt{z} =~ /^\d+\/\d+?$/) { #@@@@ whole block refactored
	    # if ($opt{i} && @{$opt{i}} == 1) {
		# $opt{z} = $opt{i}->[0] . "." . $opt{z};
	    # } else {
		# tbdie "The module/port format is only legal if exactly one -i " .
		    # "argument has been given";
	    # }
	# }
	push @pvlanArgs,$opt{x},$opt{z};
    }
}

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

#
# If their operation involves a set of ports, make sure that the caller has
# access to the nodes that the ports are on
#
# Convert ports into the correct format
639
if (@ports) {	
Weibin Sun's avatar
Weibin Sun committed
640
641
642
643
644
645
646
647
648
649
650
651
652
653
    @ports = convertPortsFromStrings(@ports, $optdev);
    # @@@@ #@ports = convertPortsFromIfaces(@ports);
    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...
    #

    # @@@@ large change
654
655
656
    my @pcports = grep {!$_->is_switch_side()} @ports;
    my @nodes = map {$_->node_id()} @pcports;
    my @switchports = grep {$_->is_switch_side()} @ports;
Weibin Sun's avatar
Weibin Sun committed
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698

    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) {
699
700
	(/listvlans/ || /getstats/ || /vlannumber/ || /synchleader/ ||
	 /syncvlans/) && do {
Weibin Sun's avatar
Weibin Sun committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
	    @devicenames = $supplied_switches?
			   @supplied_switches : getTestSwitches();
	    last;
	};
	(/listports/) && do {
	    @devicenames = $supplied_switches? @supplied_switches :
	    (@ports? getDeviceNames(@ports) : getTestSwitches());
	    last;
	};
	( /make/ ) && do {
            if ($supplied_switches) {
                @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
725
            #   vlan from the db
Weibin Sun's avatar
Weibin Sun committed
726
727
728
729
730
            #   if others fail, default to experimental switches
	    my ($vlan_name) = @args;
            if ($supplied_switches) {
                debug("Remove: using supplied switches\n");
                @devicenames = @supplied_switches;
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
            }
	    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");
Weibin Sun's avatar
Weibin Sun committed
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
                @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;
            }
            if ($supplied_switches) {
                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 {
774
                @devicenames = mapVlansToSwitches(@vlans);
Weibin Sun's avatar
Weibin Sun committed
775
                debug("Tables: list from database: " . join(",",@devicenames) .
776
		      "\n");
Weibin Sun's avatar
Weibin Sun committed
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
            }
            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;
            }
            if ($supplied_switches) {
                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 {
820
                @devicenames = mapVlansToSwitches(@vlans);
Weibin Sun's avatar
Weibin Sun committed
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
                debug("Reset: list from database: " . join(",",@devicenames) .
                    "\n");
            }

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

            if ($supplied_switches) {
841
842
843
844
845
		die("-X and -i cannot be used together\n");
            }
	    else {
                @devicenames = uniq(mapVlansToSwitches(@newvlans),
				    mapStaleVlansToSwitches(@oldvlans));
Weibin Sun's avatar
Weibin Sun committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
                debug("Sync: list from database: " . join(",",@devicenames) .
		      "\n");
            }
            # 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 {
	    @devicenames = $supplied_switches?
	    		   @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
	    #
	    if ($supplied_switches) {
		die "-c and -i or -S cannot be used together\n";
	    }
	    @devicenames = getTestSwitches();
	    last;
	};
	(/trunkenable/) && do {
	    @devicenames = $supplied_switches?
	    		   @supplied_switches : getDeviceNames(@ports);
	    @vlans = @optvlanids;
	    last;
	};
        (/restorestatus/) && do {
            # We start by parsing out the options string, then we'll reset
            # @args
            my ($statusarg) = @args;
            my %args = parseStatusString($statusarg);
            if (!$args{port}) {
                tbdie "No port given in status string";
            }
            @ports = Port->converPortsFromStrings($args{port}); #@@@@  @ports = convertPortsFromIfaces($args{port});
            if ($args{vlan}) {
                @vlans = ($args{vlan});
            }
895
896
	    @devicenames = $supplied_switches?
		           @supplied_switches : getDeviceNames(@ports);
Weibin Sun's avatar
Weibin Sun committed
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
            @args = %args;
            last;
        };
	(/ofenable/ || /ofdisable/ || /ofcontroller/ || /oflistener/) && do {
	    @vlans = @args;

	    # Same to 'remove', we find stacks by VLAN 
	    my ($vlanobj, $stack);
            if ($supplied_switches) {
                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;
	};
    }

    debug("Device names: " . join(",",@devicenames) . "\n");
922
    debug("Ports: " . join(",", map($_->toIfaceString(), @ports)) . "\n"); 
Weibin Sun's avatar
Weibin Sun committed
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
    if (@vlans) { debug("VLANs: " . join(",",@vlans) . "\n") };

    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 {
970
971
		require new_snmpit_stack;
		$stack = new new_snmpit_stack($stack_id,$debug,
Weibin Sun's avatar
Weibin Sun committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
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
					  @{$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 
1042
1043
1044
1045
	/syncvlans/ && do {
	    $exitval += doSyncVlansWithDB(\@stacks);
	    last;
	}; # /listvlans/ && do 
Weibin Sun's avatar
Weibin Sun committed
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
	/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
#
1177
sub doListVlans ($) {
Weibin Sun's avatar
Weibin Sun committed
1178
1179
1180

    my $stacks = shift;
    my %vlans;
1181
    my %tags;
Weibin Sun's avatar
Weibin Sun committed
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
    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;
1198
	    $tags{$ddep} = $id;
Weibin Sun's avatar
Weibin Sun committed
1199
1200
1201
1202
1203
1204
1205
1206
            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;
1207
		$tags{$ddep} = $id;
Weibin Sun's avatar
Weibin Sun committed
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
                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;
1221
1222
	    my $vlan = "$in#" . ${$vlans{$out}}[0] . "#";
	    my $memberref = ${$vlans{$out}}[1];
Weibin Sun's avatar
Weibin Sun committed
1223
	    if (scalar(@$memberref) > 0 && ref(${$memberref}[0])) {
1224
1225
1226
1227
	    	$vlan = $vlan.Port->toStrings(@$memberref);
	    } else {
	    	$vlan = join(' ', @$memberref);
	    }
Weibin Sun's avatar
Weibin Sun committed
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
	    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";
1259
1260
VLAN     Number   Project/Experiment VName     Members
----------------------------------------------------------------------------------
Weibin Sun's avatar
Weibin Sun committed
1261
1262
END
	format vlanlist2 =
1263
@<<<<<<< @<<<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Weibin Sun's avatar
Weibin Sun committed
1264
$vlan_id,$ddep, $pideid,           $vname,   $members
1265
~~                                             ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Weibin Sun's avatar
Weibin Sun committed
1266
1267
1268
                                             $members
.
	$FORMAT_NAME = 'vlanlist2';
1269
1270
1271
1272
    }
    my @sorted = ($opt{w} ?
                  map {$tags{$_}} sort {tbsort($a,$b)} keys %tags :
                  sort {tbsort($a,$b)} keys %vlans);
Weibin Sun's avatar
Weibin Sun committed
1273

1274
    foreach my $vid (@sorted) {
Weibin Sun's avatar
Weibin Sun committed
1275
1276
        $vlan_id = $vid;
	my $memberref;
1277
        my $vlan;
Weibin Sun's avatar
Weibin Sun committed
1278
	($ddep,$memberref) = @{$vlans{$vid}};
1279
1280
1281
1282
1283
1284
1285

	if ($vlan_id =~ /^\d*$/) {
	    $vlan = VLan->Lookup($vlan_id);
	}
	else {
	    $vlan = VLan->Lookup($experiment, $vlan_id);
	}
Weibin Sun's avatar
Weibin Sun committed
1286
        if (!defined($vlan)) {
1287
	    print("No such VLAN $vlan_id in lans table\n");
Weibin Sun's avatar
Weibin Sun committed
1288
1289
1290
1291
1292
1293
            # 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
1294
            if ($opt{O} && $vlan_id !~ /^\d+$/) {
Weibin Sun's avatar
Weibin Sun committed
1295
1296
                next;
            }
1297
1298

            # Only admins get to see this. Possibly a silly check.
Weibin Sun's avatar
Weibin Sun committed
1299
1300
1301
1302
	    if (!TBAdmin()) {
		&debug("Failed TBAdmin check\n");
		next;
	    }
1303
1304
1305
1306
	    $pideid = "";
            $vname  = $vlan_id;
        }
	else {
Weibin Sun's avatar
Weibin Sun committed
1307
1308
1309
1310
1311
            # If only printing orphaned VLANs, skip ones for which we know the
            # pid and ied
            if ($opt{O}) {
                next;
            }
1312
            my $vlanexp = $vlan->GetExperiment();
Weibin Sun's avatar
Weibin Sun committed
1313
            if ($UID &&
1314
		!$vlanexp->AccessCheck($this_user, TB_EXPT_READINFO)) {
Weibin Sun's avatar
Weibin Sun committed
1315
1316
1317
                &debug("$this_user failed access check to $experiment\n");
                next;
            }
1318
1319
1320
1321
   	    # Setup $pideid for a more compact display
            $pideid = $vlan->pid() . "/" . $vlan->eid();
            $vname  = $vlan->vname();
	}
Weibin Sun's avatar
Weibin Sun committed
1322
1323
1324
1325
1326
1327

	#
	# 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)
Weibin Sun's avatar
Weibin Sun committed
1328
	    if (scalar(@$memberref) > 0 && ref(${$memberref}[0])) { 
1329
1330
	    	$members = join(" ", map
		    {
Weibin Sun's avatar
Weibin Sun committed
1331
			$_->mac()? $_->node_id().":".$_->mac():$_->toString()
1332
1333
1334
1335
1336
1337
1338
1339
1340
		    } @$memberref);
	    } else {		
	    	my @ptobjs = map {Port->LookupByStringForced($_)} @$memberref;
	    	 
	    	$members = join(" ", map
		{
		    defined($_)?($_->mac()? $_->node_id().":".$_->mac():$_->toString()):""		    
		} @ptobjs);
	    }
Weibin Sun's avatar
Weibin Sun committed
1341
	} else {
Weibin Sun's avatar
Weibin Sun committed
1342
	    if (scalar(@$memberref) > 0 && ref(${$memberref}[0])) { 
1343
1344
1345
1346
	    	$members = Port->toStrings(@$memberref); 
	    } else {
	    	$members = join(" ",@$memberref);
	    }
Weibin Sun's avatar
Weibin Sun committed
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
	}
	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) {
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
	    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;
	    }
	    
Weibin Sun's avatar
Weibin Sun committed
1387
1388
1389
	    if (($num >= $leader->{MIN_VLAN}) &&
		($num <= $leader->{MAX_VLAN}) &&
		!($leader->vlanNumberExists($num))) {
1390
		$errors += $leader->createVlan($id, $vlan->lanid(), $num);
Weibin Sun's avatar
Weibin Sun committed
1391
1392
1393
1394
1395
1396
1397
1398
1399
	    }
	}
    }
    return $errors;
}

#
# Lists all ports on all stacks
#
1400
sub doListPorts($) {
Weibin Sun's avatar
Weibin Sun committed
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

    my $stacks = shift;

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

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

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

    return 0;
}

#
# Get information on a particular port - the idea is that this string can later
# be passed back to us to restore the status of the port.
# This is inefficient, because it gets information about all ports and only
# uses it for one (or a few). BUT, it doesn't require changes to the
# vendor-specific modules, so I think it's worth it for portability.
#
1456
sub doPortStatus($@) {
Weibin Sun's avatar
Weibin Sun committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533

    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
#
1534
sub doRestorePortStatus($@) {
Weibin Sun's avatar
Weibin Sun committed
1535
1536
1537

    my $stacks = shift;
    my %params = @_; # Yes, this does work
1538
    my $errors = 0;
Weibin Sun's avatar
Weibin Sun committed
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555

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

    if (@$stacks > 1) {
1556
	die "Port restoration across multiple stacks is not yet supported\n" .
Weibin Sun's avatar
Weibin Sun committed
1557
1558
1559
1560
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
    }
    my ($stack) = @$stacks;

1561
1562
1563
1564
1565
1566
    #
    # 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;
Weibin Sun's avatar
Weibin Sun committed
1567

1568
    #
Weibin Sun's avatar
Weibin Sun committed
1569
1570
    # Put the port in the specified VLAN
    # If they didn't give us a VLAN, we assume that means they want it removed
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
    # 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);
Weibin Sun's avatar
Weibin Sun committed
1587
1588
    if ($errors) { return $errors; }

1589
1590
1591
1592
1593
    if (defined($source_vlan) && $source_vlan->KeepInSync()) {
	if ($source_vlan->DelPort($port)) {
	    print "Could not yank $port from $source_vlan\n";
	    $errors++;
	}
1594
1595
	my @tmp = ($port->toIfaceString());
	VLan->RecordVLanModification($source_vlan->id(), undef, \@tmp);
1596
1597
1598
1599
1600
1601
1602
1603
1604
    }
    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});
    }

Weibin Sun's avatar
Weibin Sun committed
1605
1606
1607
1608
1609
    # 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
1610
    if ($vlan_id eq "default") { $enabled = "no"; }
Weibin Sun's avatar
Weibin Sun committed
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
    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
#
1653
sub doGetStats($) {
Weibin Sun's avatar
Weibin Sun committed
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

    my $stacks = shift;

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

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

    return 0;
}

#
# Creates all VLANs given. Looks up identifiers in the database to determine
# the membership.
#
1696
sub doVlansFromTables($$@) {
Weibin Sun's avatar
Weibin Sun committed
1697
1698
1699
1700
1701
1702
1703
1704
1705
    my $experiment = shift;
    my $stacks  = shift;
    my @vlanids = @_;
    my %vlans   = ();

    my $errors = 0;
    my $vlan_number;

    if (@$stacks > 1) {
1706
1707
	die "VLAN creation across multiple stacks is not yet supported\n" .
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
Weibin Sun's avatar
Weibin Sun committed
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
    }
    
    #
    # Hand over to outer boss.
    # 
    if ($ELABINELAB) {
	return RemoteDoVlansFromTables($experiment, @vlanids);
    }

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

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

	# This is set in libvtop.
	if (defined($trunk_mode) && $trunk_mode eq "dual") {
	    my @ports = getVlanPorts($vlanid);
	    
	    # Create this vlan now.
	    if (CreateOneVlan($experiment,$stack, $vlanid, @ports))  {
		die("Could not create dual trunked $vlan\n");
	    }
	    # Trunk these ports, removing from list.
	    foreach my $port (@ports) {
		if (doTrunkEnable($stacks,$port,0,$vlanid)) {
1752
		    die("Could not put ".$port->toString()." ($vlan) into dual trunk mode\n");
Weibin Sun's avatar
Weibin Sun committed
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
		}
		delete($trunkedPorts{$port->toString()});
	    }
	    
	    #
	    # Set openflow
	    #
	    # A much more right place for the openflow settings is CreateOneVlan,
	    # however, it is called by sync vlan function and others, which don't destroy
	    # the existing vlan_arrtibutes rows.
	    #
	    # TODO: Move this part to CreateOneVlan and Make sure the existed 
	    #       vlan_attributes rows are deleted
	    #
	    my $ofenabled;
	    $vlan->GetAttribute("ofenabled", \$ofenabled);
	    if (defined($ofenabled) && $ofenabled == 1) {
	        $errors += doOpenflowEnable($stacks, $vlanid);
	    
	        my $ofcontroller;
	        $vlan->GetAttribute("ofcontroller", \$ofcontroller);
	        if (defined($ofcontroller) && $ofcontroller ne "") {
	            $errors += doSetOpenflowController($stacks, $vlanid, $ofcontroller);
	        }
	    
	        $errors += doEnableOpenflowListener($stacks, $vlanid);
	    
	        # doEnableOpenflowListener updates the lan_arrtibutes table, so vlan 
	        # should refresh itself. But here vlan will not be used any more, so
	        # maybe we can comment this refresh.
	        $vlan->Refresh();	    
	    }
	    
	    # Delete this vlan from the list that will be created below.
	    delete($vlans{"$vlanid"});
	}
    }
    # Do the rest of the trunked ports in equalmode.
    foreach my $port (keys(%trunkedPorts)) {
	$errors += doTrunkEnable($stacks,$trunkedPorts{$port},1);
    }

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

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

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

#
# Create a single vlan.
#
1861
sub CreateOneVlan($$$@)
Weibin Sun's avatar
Weibin Sun committed
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
{
    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.
Weibin Sun's avatar
Weibin Sun committed
1877
	    my @conports = map {$_->toIfaceString()} @ports; 
Weibin Sun's avatar
Weibin Sun committed
1878
1879
1880
1881
	    VLan->RecordVLanModification($vlanid, \@conports, undef);
	}
    }
    else {
1882
	my $vlan_number = $stack->createVlan($vlanid, $vlanid, \@ports);
Weibin Sun's avatar
Weibin Sun committed
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
	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 {
1893
	    VLan->RecordVlanInsertion($vlanid, $stack->{STACKID});
Weibin Sun's avatar
Weibin Sun committed
1894
1895
1896
1897
1898
1899
1900
1901
1902
	}
    }
    return $errors
	if ($errors);

    #
    # Set the speed and duplex of each interface depending on the
    # value in the database
    #
1903
    if (!$NOSTACKMIB) {
Weibin Sun's avatar
Weibin Sun committed
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
	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;
		}
	    }
	}
    }
    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
#
1936
sub doReset($@) {
Weibin Sun's avatar
Weibin Sun committed
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
    my $stacks = shift;
    my @vlans = @_;

    #
    # 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);
    }
1953
1954
    # In case of error, do not clear the DB state.
    my %notdeleted = ();
Weibin Sun's avatar
Weibin Sun committed
1955
1956
1957
1958
1959
1960
1961
1962

    #
    # 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) {
	my @existant_vlans = $stack->existantVlans(@vlans);
	if (!$stack->removeVlan(@existant_vlans)) {
1963
1964
1965
1966
1967
1968
1969
1970
1971
	    #
	    # 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;
		}
	    }
Weibin Sun's avatar
Weibin Sun committed
1972
1973
	    $errors++;
	}
1974
1975
1976
1977
1978
1979
1980
1981
    }
    foreach my $vlan_id (@vlans) {
	next
	    if (exists($notdeleted{$vlan_id}));
	
	clearReservedVlanTag($vlan_id)
	    if ($opt{C});
	VLan->RecordVLanDeletion($vlan_id);
Weibin Sun's avatar
Weibin Sun committed
1982
1983
1984
1985
1986
1987
1988
1989
    }
    return $errors;
}

#
# Sync vlans from the DB for a single experiment. This is a swapmod helper
# to avoid churning the switches.
#
1990
sub syncVlansFromTables($$) {
Weibin Sun's avatar
Weibin Sun committed
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
    my $experiment = shift;
    my $stacks     = shift;
    my %expvlans   = ();
    my %curvlans   = ();
    my %stale      = ();
    my $errors     = 0;
    my $vlan_number;

    $debug = 1;

    if (@$stacks > 1) {
2002
	die "VLAN creation across multiple stacks is not yet supported\n" .
Weibin Sun's avatar
Weibin Sun committed
2003
2004
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
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
	    "Stacks are " . join(", ",map {$_->{STACKID}} @$stacks) . "\n";
    }
    my ($stack) = @$stacks;
    my @needTrunking = getExperimentTrunks($pid,$eid);
    my %needTrunking = map { $_->toString() => $_ } @needTrunking;

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

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

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

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

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

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

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

		    foreach my $port (@curports) {
			if (exists($currentTrunks{$port->toString()})) {
			    push(@trunkports, $port);
			}
		    }
		    if (@trunkports) {
			$stack->removeSomePortsFromTrunk($vlanid, @trunkports)
			    or goto bad;

			# Convert the ports to node:iface for the next call.
			@trunkports = map {$_->toIfaceString()} @trunkports; 
			VLan->RecordVLanModification($vlanid,
						     undef, \@trunkports)
			    == 0 or goto bad;
		    }
		    if (!$stack->removeVlan($vlanid)) {
			print STDERR "Could not remove vlan: $vlanid\n";
			goto bad;
		    }
		    VLan->RecordVLanDeletion($vlanid) == 0
			or goto bad;
2079
2080
		    VLan->ClearReservedVlanTag($vlanid) == 0
			or goto bad;
Weibin Sun's avatar
Weibin Sun committed
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
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
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
		}
	    }
	}
    }

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

	#
	# As a simplification for the backend, keep trunked ports separate
	# from regular ports. Better then the backend figuring it out.
	#
	foreach my $port (@curports) {
	    if (! grep {$_->toString() eq $port->toString()} @expports) {
		if (exists($currentTrunks{$port->toString()})) {
		    push(@staletrunks, $port);
		}
		else {
		    push(@staleports, $port);
		}
	    }
	}
	next
	    if (! (@staleports || @staletrunks));
	    
	if (@staleports) {
	    debug("Removing stale ports from vlan $vlanid: ".Port->toStrings(@staleports)."\n");

	    if (!$impotent) {
		$stack->removeSomePortsFromVlan($vlanid, @staleports)
		    or goto bad;

		# Convert the ports to node:iface for the next call.
		@staleports = map {$_->toIfaceString()} @staleports; 
		VLan->RecordVLanModification($vlanid, undef, \@staleports) == 0
		    or goto bad;
	    }