snmpit.in 74.3 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2
#
3
# EMULAB-LGPL
4
# Copyright (c) 2000-2010 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
6
7
# All rights reserved.
#

8
9
10
11
12
13
14
15
16
#
# snmpit - A tool for setting up VLANs on SNMP-controllable switches
#

#
# Configure variables
#

use lib '@prefix@/lib';
17
my $TESTMODE   = @TESTMODE@;
18
my $ELABINELAB = @ELABINELAB@;
19
my $NOSTACKMIB = @NOSTACKMIB@;
20
my $TB = '@prefix@';
21

22
use libdb;
23
use User;
24
use Experiment;
25
use snmpit_lib;
26
use snmpit_remote;
Kevin Atkinson's avatar
   
Kevin Atkinson committed
27
use libtblog;
28
29

use English;
30
use Getopt::Long;
31
use strict;
32

33
34
35
36
37
38
39
# Protos
sub parseStatusString($);
sub debug($);
sub doListVlans($);
sub doListPorts($);
sub doPortStatus($@);
sub doGetStats($);
40
sub doVlansFromTables($$@);
41
sub syncVlansFromTables($$);
42
43
44
45
46
47
sub doReset($@);
sub doMakeVlan($$@);
sub doDeleteVlan($@);
sub doVlanNumber($$);
sub doPortControl($$@);
sub doRecreateVlans($);
48
sub doTrunkEnable($$$@);
49
50
sub doTrunkDisable($$);
sub doRestorePortStatus($@);
51
sub doSynchLeader($);
52
sub CreateOneVlan($$@);
53
54
sub doOpenflowEnable($$);
sub doOpenflowDisable($$);
55
56
57
sub doSetOpenflowController($$$);
sub doSetOpenflowListener($$$);
sub doEnableOpenflowListener($$);
58

59
60
61
#
# Defaults
#
62
my $debug = 0;
63
my $quiet = 0;
64
65
my $minOpenflowListenerPort = 5000;
my $maxOpenflowListenerPort = 65535;
66
67
68
69
70
71
72
73
74
75

######################################################################
# 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";
76
Usage: $0 [-h] [-v level] [-q] [-n] [-i device] [-S stack]
77
	  [-l] [-s] [-g] [-O]
78
	  [-m name pid eid [ports]]
79
80
	  [-T port name]
	  [-U port]
81
	  [-o name pid eid]
82
          [-N name]
83
84
          [-r pid eid]
	  [-t pid eid]
85
	  [-d ports] [-e ports] [-a ports]
86
	  [-p <10|100|1000> ports] [-u <half|full> ports]
87
	  [-c]
88
89
90
          [--of-disable name pid eid]
          [--of-enable name pid eid]
          [--of-controller name pid eid tcp:ip:port]
91
          [--of-listener name pid eid]
92
93
General:
  -h          Display this help message
94
  -v <level>  Verbose mode
95
  -q          Quiet mode
Robert Ricci's avatar
Robert Ricci committed
96
  -n          Test mode - don't actually make any changes
97
98
  -i <device> Operate on <device>, overriding default device list. Can be
                  given multiple times
99
100
  -S <stack>  Operate on the given stack, instead of the default of the
                  experimental network
101
102

VLAN Control:
103
104
  -t <pid> <eid>    Create all VLANs for an experiment
  -r <pid> <eid>    Remove all VLANs for an experiment
105
                        (you can provide an optional list of vlan ids)
106
107
  -l                List all VLANs associated with experiments.
                        A second -l will list ALL vlans.
108
  -w                Used with -l, includes device-specific VLAN number
109
  -M                Used with -l, print MAC addresses instead of port numbers
110
  -O                Used with -l, list only orphaned VLANs
111
  -L <out#in[,o2#i2,...]> stylized -l for snmpit.proxy of specific vlans
112
113
114
115
  -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
Robert Ricci's avatar
Robert Ricci committed
116
117
118
119
120
121
  -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
122
123
124
  -o <name> <pid> <eid>
                    Delete the VLAN with name <name>, which is associated with
                        the given experiment
125
  -N <name>         Print out the VLAN number for the named VLAN
126
127
  -c                Delete ALL VLANs, and recreate from the database. ** USE
                        WITH EXTREME CAUTION **
128
129
  -F                Create all vlans in the given stack on the leader for
		    use in leader->{ALLVLANSONLEADER} (Internal use only)
130
  --of-enable <name> <pid> <eid> 
131
132
                    Enable Openflow on VLAN with the name <name> that is 
		        associated with the given experiment 
133
  --of-disable <name> <pid> <eid>
134
135
                    Disable Openflow on VLAN with the name <name> that is 
		        associated with the given experiment
136
  --of-controller <name> <pid> <eid> tcp:ip:port
137
138
139
                    Set controller for Openflow-enabled VLAN with the 
		        name <name> that is associated with the given 
			experiment
140
  --of-listener <name> <pid> <eid> 
141
142
143
144
                    Enable listener for Openflow-enabled VLAN with the 
		        name <name> that is associated with the given 
			experiment, snmpit will print out the listener 
			connection string
145
146

Port Control:
147
148
149
150
151
152
153
  -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
154
155
  -T <port> <names>      Enable trunking on the given <port>, and allow VLANs
                             with the given <names> across it
156
  -E <port> <names>      Like -T, but "Equal" mode; PVID is also tagged
157
  -U <port>              Turn off trunking for the given <port>
158
159
  -b <ports>             Print out port status for a set of ports
  -B <statstring>        Pass in a stat string from -b to restore status
160
161
  -D <pid> <eid>         Disable all control net ports for an experiment
  -R <pid> <eid>         (Re)enable all control net ports for an experiment
162
163
164
165

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.
166
167
168
END

    return 1;
169
170
}

171
my %opt = ();
172
Getopt::Long::Configure("no_ignore_case");
173
174
GetOptions(\%opt,
    'a','c','d','e','b','B=s@','g','h','i=s@','l+','m=s@','M','n',
175
    'N=s@','o=s@','p=s','q','r','s', 'S=s@','t','E=s','T=s','u=s','U','v=s','w',
176
    'y=s','x=s','z=s','F','L=s','O', 'D', 'R', 'f', 'X', 'vlan_tag=i', 
177
    'of-disable=s', 'of-enable=s', 'of-controller=s', 'of-listener=s');
178
# Unused: f,j
179
180
181
182

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

184
185
186
187
188
if ($opt{v}) {
    $debug = $opt{v};
    print "Debug level is $debug\n";
}

189
190
if ($opt{q}) {
    $quiet = 1;
191
    if ($opt{m} || $opt{o} || $opt{t} || $opt{r} || $opt{X} || $opt{T} ||
Weibin Sun's avatar
Weibin Sun committed
192
	  $opt{E} || $opt{U} || $opt{u} || $opt{d} || $opt{p} || $opt{e} ||
193
194
	  $opt{'of-enable'} || $opt{'of-disable'} || $opt{'of-controller'} || 
	  $opt{'of-listener'}) {
195
196
	my $nulldev;
        open($nulldev, ">>/dev/null");
197
198
	select $nulldev; # supresses print foo(); without explicit fileglob
    }
199
200
}

Weibin Sun's avatar
Weibin Sun committed
201
#if ($opt{F}) { push @commands, ["synchleader"]; }
202
203
# Values that may have been passed on the command line
#
204
205
my $pid;
my $eid;
206
my $experiment;
207
my @ports;
208
my @optvlanids = ();
209
my $equaltrunking = 0;
210
my $this_user;
211
my $ofconnstr; # Openflow connection string, for controller 
212
our $next_vlan_tag; # XXX see doMakeVlan for explanation
213
214
215
216
217
218
219
220
221
222
223

#
# 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");
    }
}
224
225
226
227
228

#
# Some operations have mandatory agruments - for others, make sure that
# the user didn't give any extraneous arguments
#
229
if ($opt{m} || $opt{o}) {
230
231
232
    if (@ARGV < 2 ||
	($opt{m} && ($ARGV[0] =~ /:/ || $ARGV[1] =~ /:/)) ||
	($opt{o} && ($ARGV[0] =~ /^\d+$/ || $ARGV[1] =~ /^\d+$/))) {
233
234
235
236
237
238
239
240
241
	if (! $opt{f}) {
	    tberror "pid/eid reqired!";
	    exit(usage());
	}
    }
    else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
    }
}
242
if ($opt{t} || $opt{r} || $opt{D} || $opt{R} || $opt{X}) {
243
244
245
    #
    # Options that take 'pid eid'
    #
246
    if (@ARGV < 2) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
247
	tberror "pid/eid reqired!";
248
	exit &usage;
249
    } else {
250
	($pid, $eid) = (shift @ARGV, shift @ARGV);
251
    }
252
253
254
    if (@ARGV) {
	@optvlanids = @ARGV;
    }
255
} elsif ($opt{d} || $opt{e} || $opt{a} || $opt{p} || $opt{u} || $opt{m}
256
         || $opt{U} || $opt{b}) {
257
258
259
260
    #
    # Options that take a list of ports
    #
    @ports = @ARGV;
261
} elsif ($opt{T} || $opt{E}) {
262
263
264
265
    #
    # Options that take both a port and a list of VLANs - we require at least
    # one VLAN to be given
    #
266
267
    if ($opt{E}) { $opt{T} = $opt{E}; $equaltrunking = 1;}
    elsif (!@ARGV) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
268
	tberror "At least one VLAN required";
269
270
271
272
273
274
275
276
	exit &usage;
    }
    @optvlanids = @ARGV;

    #
    # Set the @ports array so that we'll do proper permission checking on it
    #
    @ports = ($opt{T});
277
} elsif ($opt{'of-controller'}) {
Weibin Sun's avatar
Weibin Sun committed
278
    #
279
    # Options that take the pid eid and connection string
Weibin Sun's avatar
Weibin Sun committed
280
    #
281
282
283
284
285
286
    if (@ARGV < 2) {
	tberror "pid/eid reqired!";
	exit &usage;
    } else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
    }
Weibin Sun's avatar
Weibin Sun committed
287
    if (@ARGV < 0) {
288
	tberror "Controller connection string reqired!";
Weibin Sun's avatar
Weibin Sun committed
289
290
291
292
	exit &usage;
    } else {
	$ofconnstr = shift @ARGV;
    }
293
} elsif ($opt{'of-enable'} || $opt{'of-disable'} || $opt{'of-listener'}) {
Weibin Sun's avatar
Weibin Sun committed
294
    #
295
    # Options that need pid eid
Weibin Sun's avatar
Weibin Sun committed
296
    #
297
298
    if (@ARGV < 1) {
	tberror "pid/eid reqired!";
Weibin Sun's avatar
Weibin Sun committed
299
	exit &usage;
300
301
    } else {
	($pid, $eid) = (shift @ARGV, shift @ARGV);
302
    }    
303
304
305
306
307
} else {
    #
    # Everything else
    #
    if (@ARGV) {
308
309
310
	tberror({type => 'primary', severity => SEV_ERROR,
		 error => ['too_many_arguments']},
		"Too many arguments!");
311
	exit &usage;
312
    }
313
314
315
316
317
318
319
}

#
# 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.
#
320
321
322
323
324
325
my @commands;

#
# Simple commands
#
if ($opt{l}) { push @commands, ["listvlans"]; }
326
if ($opt{L}) { push @commands, ["listvlans"]; }
327
328
329
330
if ($opt{s}) { push @commands, ["listports"]; }
if ($opt{g}) { push @commands, ["getstats"]; }
if ($opt{t}) { push @commands, ["tables"]; }
if ($opt{r}) { push @commands, ["reset"]; }
331
if ($opt{X}) { push @commands, ["synctables"]; }
332
if ($opt{c}) { push @commands, ["recreate"]; }
333
if ($opt{U}) { push @commands, ["trunkdisable"]; }
334
if ($opt{b}) { push @commands, ["portstatus"]; }
335
if ($opt{F}) { push @commands, ["synchleader"]; }
336
337

#
338
# Commands that can appear once, and take an argument
339
340
341
342
#
if ($opt{d}) { push @commands, ["portcontrol","disable"]; }
if ($opt{e}) { push @commands, ["portcontrol","enable"]; }
if ($opt{a}) { push @commands, ["portcontrol","auto"]; }
343
344
if ($opt{D}) { push @commands, ["expcnetcontrol", "disable"]; }
if ($opt{R}) { push @commands, ["expcnetcontrol", "enable"]; }
345
if ($opt{T}) { push @commands, ["trunkenable", $opt{T}]; }
Weibin Sun's avatar
Weibin Sun committed
346
347
348
349
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'}]; }
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365

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

366
367
368
369
370
371
if ($opt{N}) {
    foreach my $name (@{$opt{N}}) {
	push @commands, ["vlannumber",$name];
    }
}

372
373
374
375
376
377
378
379
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}) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
380
            tbdie "No port given in status string";
381
382
        }
        if ($args{port}) {
383
            push @ports, convertPortsFromIfaces($args{port});
384
385
386
387
        }
    }
}

388
389
390
391
#
# Commands that require 'translation' of their arguments
#
if ($opt{p}) {
392
393
394
    #
    # We'll put the argument in the form needed by the portControl function
    #
395
396
397
    if ($opt{p} =~ /^1000/) {
	push @commands, ["portcontrol","1000mbit"];
    } elsif ($opt{p} =~ /^100/) {
398
	push @commands, ["portcontrol","100mbit"];
399
    } elsif ($opt{p} =~ /^10/) {
400
	push @commands, ["portcontrol","10mbit"];
401
    } else {
402
	tbreport(SEV_ERROR, 'bad_data', 'port_speed', $opt{p});
403
	die "Bad port speed: $opt{p}. Valid values are 10, 100, and 1000\n";
404
    }
405
406
}
if ($opt{u}) {
407
408
409
410
    #
    # We'll put the argument in the form needed by the portControl function
    #
    if ($opt{u} =~ /half/) {
411
	push @commands, ["portcontrol","half"];
412
    } elsif ($opt{u} =~ /full/) {
413
	push @commands, ["portcontrol","full"];
414
415
    } else {
	die "Bad port duplex: $opt{u}. Valid values are full and half\n";
Mac Newbold's avatar
Mac Newbold committed
416
    }
417
418
419
}

if (!@commands) {
420
    tbreport(SEV_ERROR, 'no_operation');
421
422
    die "No operation given\n";
}
Mac Newbold's avatar
Mac Newbold committed
423

Robert Ricci's avatar
Robert Ricci committed
424
425
426
427
#
# Options that affect other commands
#

428
429
430
431
#
# User-supplied switch lists
#
my @supplied_switches = ();
432
433
my @supplied_stacks = ();
my $supplied_switches = 0; # Whether -i or -S was given
434
if ($opt{i}) {
435
    $supplied_switches = 1;
436
437
438
439
    push @supplied_switches, @{$opt{i}};
}
if ($opt{S}) {
    foreach my $stack (@{$opt{S}}) {
440
441
442
443
444
445
446
447
448
449
450
451
452
453
	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;
	    } else {
		tbdie({type => 'primary', severity => SEV_ERROR,
		       error => ['invalid_switch_stack', $stack]},
		      "No such switch stack: $stack");
	    }
454
455
456
457
	}
    }
}

Robert Ricci's avatar
Robert Ricci committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#
# 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}) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
475
	    tberror "-x and -z must be given when -y is $opt{y}!";
Robert Ricci's avatar
Robert Ricci committed
476
477
478
479
480
481
482
483
484
485
	    exit &usage;
	}
	#
	# Fix up ports given in the module/port format, like we do below for
	# ports from @ARGV
	#
	if ($opt{z} =~ /^\d+\/\d+?$/) {
	    if ($opt{i} && @{$opt{i}} == 1) {
		$opt{z} = $opt{i}->[0] . "." . $opt{z};
	    } else {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
486
487
		tbdie "The module/port format is only legal if exactly one -i " .
		    "argument has been given";
Robert Ricci's avatar
Robert Ricci committed
488
489
490
491
492
	    }
	}
	push @pvlanArgs,$opt{x},$opt{z};
    }
}
493
494
495
496
497
498
499
500
501
502
503
504
505

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

#
# If this is an operation on an experiment, make sure that they have permission
# to modify that experiment
#
if ($pid && $eid) {
Robert Ricci's avatar
Robert Ricci committed
506
507
508
    #
    # First, make sure the experiment exists
    #
509
510
    $experiment = Experiment->Lookup($pid,$eid);
    if (!defined($experiment)) {
Robert Ricci's avatar
Robert Ricci committed
511
512
	die "There is no experiment $eid in project $pid\n";
    }
513
514
    if (defined($this_user) &&
	!$experiment->AccessCheck($this_user, TB_EXPT_MODIFY)) {
515
	die "You do not have permission to modify experiment $pid/$eid\n";
516
    }
517
518
519
520
521
522
}

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

524
525
526
527
528
# Convert ports into the correct format
if (@ports) {
    @ports = convertPortsFromIfaces(@ports);
}

529
if (@ports) {
Robert Ricci's avatar
Robert Ricci committed
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
    #
    # Allow ports to be given in one of two forms: node:port, or switch.port.
    # Only admins can do the latter, of course...
    #
    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 {
549
	    tbreport(SEV_ERROR, 'bad_data', 'port', $port);
Robert Ricci's avatar
Robert Ricci committed
550
551
552
553
	    die "Bad format for port $port\n"
	}
    }

554
    if ($UID && !TBNodeAccessCheck($UID,TB_NODEACCESS_MODIFYVLANS,@nodes)) {
555
	tbreport(SEV_ERROR, 'insufficient_permissions');
556
557
	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";
558
    }
Robert Ricci's avatar
Robert Ricci committed
559
560
561
562

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

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

570
#
571
572
# snmpit_lib fills out some hashes for speed of lookup later. Initialize
# them now
573
#
574
575
snmpit_lib::init($debug);

Robert Ricci's avatar
Robert Ricci committed
576
my $exitval = 0;
577
COMMAND: foreach my $command (@commands) {
578
579
580
581
582
583
584
585
586
587
588

    #
    # 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
589
590
591
    # 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
592
593
594
595
    #
    my @devicenames;
    my @vlans;
    SWITCH: for ($operation) {
596
	(/listvlans/ || /getstats/ || /vlannumber/ || /synchleader/) && do {
597
	    @devicenames = $supplied_switches?
598
			   @supplied_switches : getTestSwitches();
599
	    last;
600
	};
601
	(/listports/) && do {
602
	    @devicenames = $supplied_switches? @supplied_switches :
603
	    (@ports? getDeviceNames(@ports) : getTestSwitches());
604
605
	    last;
	};
606
607
608
609
610
611
612
613
614
615
616
617
	( /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;
	};
618
619
620
621
622
623
624
625
626
627
        (/remove/) && do {
            # Three levels of possible sources for device names (in order):
            #   passed in on command line
            #   stack name recorded in database
            #   if others fail, default to experimental switches
	    my ($vlan_name) = @args;
            my ($vlanobj, $stack);
            if ($supplied_switches) {
                debug("Remove: using supplied switches\n");
                @devicenames = @supplied_switches;
628
629
            } elsif (defined($experiment) &&
                     defined($vlanobj = VLan->Lookup($experiment,$vlan_name)) &&
630
                     defined($stack = $vlanobj->GetStack())) {
631
632
633
634
635
636
                debug("Remove: found stack $stack in database\n");
                @devicenames = getSwitchesInStack($stack);
            } else {
                debug("Remove: using test switches\n");
                @devicenames = getTestSwitches();
            }
637
            last;
638
        };
639
640
641
642
643
644
        (/^tables$/) && 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);
645
            if (!@vlans) {
646
647
                print "snmpit: $pid/$eid has no VLANs to create, skipping\n"
		    if (!$quiet);
648
649
                next COMMAND;
            }
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
            if ($supplied_switches) {
                debug("Tables: using supplied switches\n");
                @devicenames = @supplied_switches;
            } else {
                @devicenames =
                    getSwitchesInStacks(getPlannedStacksForVlans(@vlans));
                debug("Tables: list from database: " . join(",",@devicenames) .
                    "\n");
            }
            if (scalar(@devicenames == 0)) {
                debug("Tables: falling back to test swtiches\n");
                @devicenames = getTestSwitches();
            }
            last;
        };
665
666
	(/reset/) && do {
	    #
667
668
            # We operate on all stacks that we have recorded as having VLANs
            # that belong to this experiment.
669
	    #
670
	    @vlans = getExperimentVlans($pid,$eid,@optvlanids);
671
            if (!@vlans) {
672
673
                print "snmpit: $pid/$eid has no VLANs, skipping\n"
		    if (!$quiet);
674
675
                next COMMAND;
            }
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
            @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;
            } else {
                @devicenames =
                    getSwitchesInStacks(getActualStacksForVlans(@vlans));
                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
            if ($supplied_switches) {
                debug("Sync: using supplied switches\n");
                @devicenames = @supplied_switches;
            } else {
                # Get both the VLANs that do exist and the VLANs that should
                # exist
                my @newvlans = getExperimentVlans($pid,$eid,@optvlanids);
                @devicenames =
                    getSwitchesInStacks(getPlannedStacksForVlans(@newvlans));
                debug("Sync: New devices are " . join(",",@devicenames) .
                    "\n");

                my @oldvlans;
                VLan->StaleVlanList($experiment,\@oldvlans);
                my @oldports;
                foreach my $oldvlan (@oldvlans) {
                    push @oldports, getExperimentVlanPorts($oldvlan);
                }
                push @devicenames,
                    getSwitchesInStacks(getStacksForSwitches(getDeviceNames(@oldports)));
                debug("Sync: With old devices, list is " .
                    join(",",@devicenames) .  "\n");

                @devicenames = uniq(@devicenames);
            }

            # 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();
            }
735
736
	    last;
	};
737
	(/portcontrol/ || /trunkdisable/ || /portstatus/) && do {
738
	    @devicenames = $supplied_switches?
739
	    		   @supplied_switches : getDeviceNames(@ports);
740
741
	    last;
	};
742
743
744
745
	(/expcnetcontrol/) && do {
	    @ports = getExperimentControlPorts($pid, $eid);
	    @devicenames = getDeviceNames(@ports);
	};
746
747
748
749
750
	(/recreate/) && do {
	    #
	    # Safety check - cannot be used with -i . We have to operate on
	    # all experimental switches
	    #
751
	    if ($supplied_switches) {
752
		die "-c and -i or -S cannot be used together\n";
753
754
755
756
	    }
	    @devicenames = getTestSwitches();
	    last;
	};
757
	(/trunkenable/) && do {
758
	    @devicenames = $supplied_switches?
759
	    		   @supplied_switches : getDeviceNames(@ports);
760
761
	    @vlans = @optvlanids;
	    last;
762
763
764
765
766
767
768
	};
        (/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}) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
769
                tbdie "No port given in status string";
770
            }
771
            @ports = convertPortsFromIfaces($args{port});
772
773
774
775
776
777
778
779
780
            if ($args{vlan}) {
                @vlans = ($args{vlan});
            }
            @devicenames = $supplied_switches?
                           @supplied_switches : getDeviceNames(@ports);

            @args = %args;
            last;
        };
Weibin Sun's avatar
Weibin Sun committed
781
782
	(/ofenable/ || /ofdisable/ || /ofcontroller/ || /oflistener/) && do {
	    @vlans = @args;
783
784

	    # Same to 'remove', we find stacks by VLAN 
785
	    my ($vlanobj, $stack);
786
787
788
789
            if ($supplied_switches) {
                debug("Openflow operations: using supplied switches\n");
                @devicenames = @supplied_switches;
            } elsif (defined($experiment) &&
790
                     defined($vlanobj = VLan->Lookup($experiment,$vlans[0])) &&
791
792
793
794
795
796
797
                     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();
            }
Weibin Sun's avatar
Weibin Sun committed
798
799
	    last;
	};
800
    }
801

802
803
    debug("Device names: " . join(",",@devicenames) . "\n");
    debug("Ports: " . join(",",@ports) . "\n");
804
    if (@vlans) { debug("VLANs: " . join(",",@vlans) . "\n") };
805
806

    my %stacks = ();
807
    if (! $ELABINELAB) {
808
809
810
	#
	# First, look at the device names we've got and map them to stacks 
	#
811
	foreach my $devicename (@devicenames) {
812
	    my $stack = getSwitchPrimaryStack($devicename);
813
814
815
	    if (defined($stack)) {
		push @{$stacks{$stack}}, $devicename;
	    }
816
	}
817
818
819
820
821
822
823
824
	#
	# Next, add in stacks that were specified as a whole
	#
	foreach my $stack (@supplied_stacks) {
	    # We checked for non-existent stacks above
	    my @switches = getSwitchesInStack($stack);
	    push @{$stacks{$stack}}, @switches;
	}
825
    }
826
827

    #
828
    # Now, make the object for each stack that we discovered
829
    #
830
    my @stacks;
831
    my %stack_ids;
832
    foreach my $stack_id (keys %stacks) {
833
	my ($stack_type, $supports_private, $single_domain, $community)
834
		= getStackType($stack_id);
Robert Ricci's avatar
Robert Ricci committed
835
836
837
838
839
840
841
	#
	# 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";
	}
842

843
844
845
	my $stack;
	debug("Stack $stack_id has type $stack_type\n");
	SWITCH: for ($stack_type) {
846
	    (/cisco/ || /catalyst/) && do {
847
		require snmpit_cisco_stack;
848
849
		$stack = new snmpit_cisco_stack($stack_id,$debug,$single_domain,
 						@{$stacks{$stack_id}});
850
851
852
853
		last;
	    }; # /cisco/
	    /intel/ && do {
		require snmpit_intel_stack;
854
		$stack = new snmpit_intel_stack($stack_id,$debug,
855
						@{$stacks{$stack_id}});
856
857
		last;
	    };
858
859
	    /generic/ && do {
		require snmpit_stack;
860
		$stack = new snmpit_stack($stack_id,$debug,
861
					  @{$stacks{$stack_id}});
862
863
		last;
	    }; # /generic/
864
865
866
867
868
869
870
871
872
873
874
875

	    # '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;
876
877
878
879
880
881
882
883
884
	    $stack_ids{$stack_id} = $stack;
	}
    }


    #
    # If we were given ports, make sure that the stack(s) that got created
    # cover all of them
    #
885
    if (@ports && !$ELABINELAB) {
886
887
888
	my %devicemap = mapPortsToDevices(@ports);
	my @devices = keys %devicemap;
	foreach my $device (@devices) {
889
890
891
892
893
894
895
896
	    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) {
897
898
899
900
		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!");
901
	    }
902
	}
903
    }
904
905
906
907
908
909
    if ($ELABINELAB) {
	#
	# Okay, now that we skipped all that stack stuff ...
	#
	@stacks = @supplied_stacks;
    }
910

911
######################################################################
912
# Step 4 - Actually perfrom the operation
913
914
#
# Finally, we just call the helper function for the operation that
915
# is to be performed.
916
######################################################################
Robert Ricci's avatar
Robert Ricci committed
917
918
919
920
    if ($opt{n}) {
	print "Test mode, skipping operation\n";
	next;
    }
921

922
923
924
925
926
    SWITCH: for ($operation) {
	/listvlans/ && do {
	    $exitval += doListVlans(\@stacks);
	    last;
	}; # /listvlans/ && do 
927
928
929
930
	/synchleader/ && do {
	    $exitval += doSynchLeader(\@stacks);
	    last;
	}; # /listvlans/ && do 
931
932
933
934
935
936
937
938
	/listports/ && do {
	    $exitval += doListPorts(\@stacks);
	    last;
	}; # /listports/ && do
	/getstats/ && do {
	    $exitval += doGetStats(\@stacks);
	    last;
	}; # /ports/ && do
939
	/^tables$/ && do {
940
	    $exitval += doVlansFromTables($experiment,\@stacks,@vlans);
941
942
	    last;
	}; # /tables/ && do
943
944
945
946
	/synctables/ && do {
	    $exitval += syncVlansFromTables($experiment,\@stacks);
	    last;
	}; # /tables/ && do
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
	/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 {
962
	    my ($portcommand) = @args;
963
	    $exitval += doPortControl(\@stacks,$portcommand,@ports);
964
965
	    last;
	};
966
967
968
969
970
	/expcnetcontrol/ && do {
	    my ($portcommand) = @args;
	    $exitval += doPortControl(\@stacks,$portcommand,@ports);
	    last;
	};
971
972
973
	/recreate/ && do {
	    $exitval += doRecreateVlans(\@stacks);
	    last;
974
	};
975
	/trunkenable/ && do {
976
977
	    $exitval += doTrunkEnable(\@stacks,$ports[0],
				      $equaltrunking,@vlans);
978
979
980
	    last;
	}; # /trunkenable/ && do
	/trunkdisable/ && do {
981
	    $exitval += doTrunkDisable(\@stacks,$ports[0]);
982
	    last;
983
984
985
986
987
	}; # /trunkdisable/ && do
	/portstatus/ && do {
	    $exitval += doPortStatus(\@stacks,@ports);
	    last;
	}; # /portstatus/ && do
988
989
990
991
992
	/vlannumber/ && do {
	    my ($vlan_name) = @args;
	    $exitval += doVlanNumber(\@stacks,$vlan_name);
	    last;
	}; # /portstatus/ && do
993
994
995
996
	/restorestatus/ && do {
	    $exitval += doRestorePortStatus(\@stacks,@args);
	    last;
	}; # /portstatus/ && do
Weibin Sun's avatar
Weibin Sun committed
997
998
999
1000
1001
1002
1003
1004
1005
	(/ofenable/) && do {
	    $exitval += doOpenflowEnable(\@stacks,$vlans[0]);
	    last;
	}; # /ofenable/ && do
	(/ofdisable/) && do {
	    $exitval += doOpenflowDisable(\@stacks,$vlans[0]);
	    last;
	}; # /ofdisable/ && do
	(/ofcontroller/) && do {
1006
	    $exitval += doSetOpenflowController(\@stacks,$vlans[0],$ofconnstr);
Weibin Sun's avatar
Weibin Sun committed
1007
1008
1009
	    last;
	}; # /ofcontroller/ && do
	(/oflistener/) && do {
1010
	    $exitval += doEnableOpenflowListener(\@stacks,$vlans[0]);
Weibin Sun's avatar
Weibin Sun committed
1011
1012
	    last;
	}; # /oflistener/ && do
1013
    }
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
}

exit $exitval;

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

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

1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
#
# 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) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
1042
            tbdie "Bad port status string: $string";
1043
1044
1045
1046
1047
1048
1049
1050
        } else {
            $pairs{$key} = $value;
        }
    }

    return %pairs;
}

1051
1052
1053
#
# Lists all vlans on all stacks
#
1054
1055
1056
sub doListVlans ($) {

    my $stacks = shift;
1057
    my %vlans;
1058
    my @vlanList;
1059
1060
1061
1062
1063

    #
    # We need to 'coallate' the results from each stack by putting together
    # the results from each stack, based on the VLAN identifier
    #
Robert Ricci's avatar
Robert Ricci committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
    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;
            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;
                push @{${$vlans{$id}}[1]}, @$memberref;
            }
        }
1085
1086
    }

1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
    #
    # less code to do this for snmpit.proxy than for it to popen snmpit
    # parse the output, and glue it back together.
    #
    if ($opt{L}) {
	my @results;
	foreach my $pair (split ',', $opt{L}) {
	    my ($out,$in) = split "#", $pair;
	    my $vlan = "$in#" . ${$vlans{$out}}[0] . "#" .
				    join(' ', @{${$vlans{$out}}[1]});
	    push @results, $vlan;
	}
	print join(',', @results);
	exit(0);
    }
1102
1103
1104
1105
    #
    # These need to be declared here for the benefit of the format string
    # See perlform(1) for help with formats
    #
1106
1107
1108
1109
1110
1111
1112
    my ($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";
1113
VLAN     Project/Experiment VName     Members
1114
1115
--------------------------------------------------------------------------------
END
1116
	format vlanlist =
1117
1118
@<<<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$vlan_id,$pideid,           $vname,   $members
1119
1120
1121
~~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                                      $members
.
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
	$FORMAT_NAME = 'vlanlist';
    } else {
    	print << "END";
VLAN     Number Project/Experiment VName     Members
--------------------------------------------------------------------------------
END
	format vlanlist2 =
@<<<<<<< @<<<<< @<<<<<<<<<<<<<<<<< @<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$vlan_id,$ddep, $pideid,           $vname,   $members
~~                                           ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                                             $members
.
	$FORMAT_NAME = 'vlanlist2';
}
1136

Kirk Webb's avatar
   
Kirk Webb committed
1137
1138
    foreach my $vid (sort {tbsort($a,$b)} keys %vlans) {
        $vlan_id = $vid;
1139
	my $memberref;
Kirk Webb's avatar
   
Kirk Webb committed
1140
	($ddep,$memberref) = @{$vlans{$vid}};
1141
        
1142
        my $vlan = VLan->Lookup($vlan_id);
1143
        if (!defined($vlan)) {
1144
	    &debug("No such VLAN $vlan_id in lans table\n");