snmpit.proxynew.in 16.8 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2007 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15
# All rights reserved.
#
use English;
use Getopt::Std;

#
# Snmpit proxy for ElabInElab.
#
sub usage()
{
    print STDOUT "Usage: snmpit.proxy [-d] -p <pid> -e <eid> ".
16
	"setup|destroy|trunk|list arg [arg ...]\n";
17 18 19 20 21 22 23 24
 
    exit(-1);
}
my $optlist  = "dnp:e:";
my $debug    = 0;
my $impotent = 0;
my $pid;
my $eid;
25 26 27
my @inner_ids = ();
my @outer_ids = ();
my %mapping   = ();
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/site/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1; 

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use libdb;
use libtestbed;
48
use Experiment;
49 50 51 52

# Be careful not to exit on transient error
$libdb::DBQUERY_MAXTRIES = 60;

53 54 55
# Locals
my $exptidx;

56 57 58
# Protos
sub SetupVlans();
sub DestroyVlans();
59 60 61
sub Trunk();
sub List();
sub Map();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"p"})) {
    $pid = $options{"p"};
    
    #
    # Untaint the arguments.
    #
    if ($pid =~ /^([-\w\.]+)$/) {
	$pid = $1;
    }
    else {
	die("Tainted argument $pid!\n");
    }
}
if (defined($options{"e"})) {
    $eid = $options{"e"};

    if ($eid =~ /^([-\w\.]+)$/) {
	$eid = $1;
    }
    else {
	die("Tainted argument $eid!\n");
    }
}
usage()
    if (!@ARGV || !defined($pid) || !defined($eid));

my $op = shift(@ARGV);

#
# Sanity check. Must be an ElabInElab experiment and user must have
# permission (be the creator).
#
109 110
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
111 112 113
    die("*** $0:\n",
	"    Experiment $pid/$eid is not active!\n");
}
114
$exptidx = $experiment->idx();
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
if (!TBExptAccessCheck($UID, $pid, $eid, TB_EXPT_MODIFY)) {
    die("*** $0:\n".
	"    You do not have permission to swap or modify this experiment!\n");
}

#
# I'm going to serialize this for now. When the script exits, the lock
# will be released.
#
DBQueryFatal("select get_lock('snmpit.proxy', 999999)");

if ($op eq "setup") {
    exit(SetupVlans());
}
elsif ($op eq "destroy") {
    exit(DestroyVlans());
}
132 133 134 135 136 137
elsif ($op eq "trunk") {
    exit(Trunk());
}
elsif ($op eq "list") {
    exit(List());
}
138 139 140 141 142 143 144 145 146 147 148 149 150

#
# Setup vlans for an inner emulab. ARGV holds a set of strings that look
# like:
#	id,node:iface,speed,duplex,vtag
# which came in from the XMLRPC server. For each vlan id, gather up all
# if its member ports (node:iface), along with the speed and duplex for
# each port, which goes into the interfaces table so that the real snmpit
# can find the right values. 
# 
sub SetupVlans()
{
    my $vlantable = {};
151
    my %vmaptable = ();
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    my %vtagtable = ();
    my %nodes     = ();
    my @outer_ids = ();
    my $errors    = 0;
	
    while (@ARGV) {
	my $str = shift(@ARGV);

	if ($str =~ /^(\d+),([\w:]+),(\d*),(full|half),([-\w]+)$/) {
	    my $id     = $1;
	    my $port   = $2;
	    my $speed  = $3;
	    my $duplex = $4;
	    my $vtag   = $5;
	    my $node;
	    my $iface;

	    if (! exists($vlantable->{$id})) {
		$vlantable->{$id} = {};
		$vtagtable{$id}   = $vtag;
	    }
	    $vlantable->{$id}->{$port} = [$speed, $duplex];

	    # For doing access and sanity checks below.
	    if ($port =~ /^(.+):(.+)$/) {
		($node,$iface) = ($1, $2);
	    }
	    $nodes{$node} = []
		if (!exists($nodes{$node}));
	    push(@{ $nodes{$node} }, $iface);
	}
	else {
	    die("*** $0:\n",
		"    SetupVlans: Cannot parse '$str'!\n");
	}
    }

    #
    # First check permission on the nodes. snmpit is going to repeat this
    # operation, but we have to do it here cause we first mess with the
    # speed and duplex values in the interfaces table for each node, cause
    # snmpit uses those values when setting up the vlan.
    #
    if (!TBNodeAccessCheck($UID, TB_NODEACCESS_MODIFYVLANS, keys(%nodes))) {
	die("*** $0:\n",
	    "    You do not have permission to modify some of the nodes\n" .
	    "    that will be affected by the operation you requested\n");
    }

201
    # Stoller wrote:
202 203 204
    # Sanity check the inner id numbers. If they already exist in the
    # mapping table, then bail now. We could probably support this, but
    # I do not see a reason to yet.
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

    # Sklower explains:
    # for the federation boss, in order to calculate which
    # vlans go on which inter site trunks it's convenient to
    # push the vlan handling for master site's parent into
    # a pseudo-switch-module, but that will cause the parent
    # to be asked to add groups of interfaces in chunks.

#    my $query_result =
#	DBQueryFatal("select * from elabinelab_vlans ".
#		     "where pid='$pid' and eid='$eid' and ".
#		     # Join "id='foo'" with ORs
#		     "(" .
#		       join(' OR ', map("inner_id='$_'", keys(%$vlantable))) .
#		     ")");
#    if ($query_result->numrows) {
#	my @ids = keys(%$vlantable);
#	
#	die("*** $0:\n",
#	    "    One of the inner vlan ids (@ids) already exists!\n");
#    }
226 227 228 229 230 231 232 233

    #
    # Okay, sanity check the interfaces for each node. They have to be real
    # interfaces, marked as TBDB_IFACEROLE_EXPERIMENT(), nothing else. Also,
    # the IP must not be set; if the IP is set, its being used for the inner
    # control network, and we do not let those interfaces change.
    #
    foreach my $node (keys(%nodes)) {
234

235 236
	my @ifaces = @{ $nodes{$node} };

237 238 239 240 241 242 243 244 245
	# Sklower chimes in again
	# In Mike's canonical experiment about running two interfaces in
	# multiplexed mode the query that was here returned more than
	# one result, because the same interface was presented twice.
        
	# this check is going to become a lot more elaborate if we allow
	# an elabinelab to have firewalls within it ... let's *table* that
	# motion for now ...

246
	my $query_result =
247 248
	    DBQueryFatal("select iface,role,IP from interfaces ".
			 "where node_id='$node' and ".
249 250 251
			 # Join "iface='foo'" with ORs
			 "(" . join(' OR ', map("iface='$_'", @ifaces)) . ")");

252 253 254 255 256 257 258
	if ($query_result) {
	    while (my ($iface, $role, $IP) = $query_result->fetchrow()) {
		if (($role ne "expt") || ($IP ne "")) {
		    die("*** $0:\n",
			"Iface $iface for $node cannot be changed\n");
		}
	    }
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	}
    }

    #
    # Okay, set the speed and duplex for all the interfaces. 
    #
    foreach my $id (keys(%$vlantable)) {
	foreach my $port (keys(%{ $vlantable->{$id} })) {
	    my ($speed, $duplex) = @{ $vlantable->{$id}->{$port} };
	    my ($node,$iface)    = ($port =~ /^(.+):(.+)$/);

	    if ($debug) {
		print STDERR "$id $node:$iface $speed $duplex\n";
	    }
	    if (! $impotent) {
		DBQueryFatal("update interfaces set ".
			     "   current_speed=$speed,duplex='$duplex'".
			     "where node_id='$node' and iface='$iface'");
	    }
	}
    }

    #
    # Okay, create an actual members list to insert into the DB vlans table.
    # We need to remember the association between the inner id and the outer
    # id, so after we insert the vlans entry, get the ID that was assigned and
    # remember it in the elabinelab_vlans table for later when the inner elab
    # requests deletion (see DestroyVlans() below).
    #
    # Note that on failure we keep going, which mirrors how snmpit operates.
    # Not sure if this is the right approach though.
    # 
    foreach my $id (keys(%$vlantable)) {
	my $vtag    = $vtagtable{$id};
	my @members = keys(%{ $vlantable->{$id} });
	my $mstring = "@members";
295
	my $outer_id;
296 297 298 299 300 301 302

	if ($debug) {
	    print STDERR "$pid $eid $id $mstring\n";
	}
	next
	    if ($impotent);

303
	# Insert (or modify) outer vlans entry.
304
	my $query_result =
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
	    DBQueryFatal("select outer_id from elabinelab_vlans ".
			 "where pid='$pid' and eid='$eid' and inner_id='$id'");
	if ($query_result->numrows == 1) {
	    ($outer_id) = $query_result->fetchrow();
	    $query_result =
		DBQueryFatal("select members from vlans where id='$outer_id'");
	    if ($query_result->numrows == 1) {
		my ($oldstring) = $query_result->fetchrow();
		my @mlist = split " ",$oldstring;
		my %mhash = ();
		foreach my $mem (@mlist) {
		    $mhash{$mem} = 1;
		}
		foreach my $mem (@members) {
		    $mhash{$mem} = 1;
		}
		@mlist = keys(%mhash);
		$mstring = "@mlist";
	    }
	    my $query_result =
		DBQueryWarn("update vlans set members='$mstring' where " .
			     "id='$outer_id'");
	    if (!$query_result) {
		print STDERR "*** $0:\n".
			     "    Could not update vlan table entry for $id\n";
		$errors++;
		next;
	    }
	} else {
	    my $query_result =
		DBQueryWarn("insert into vlans ".
			    "  (exptidx,id,pid,eid,virtual,members) ".
			    "values ($exptidx, 0, '$pid', '$eid', '$vtag', ".
			    "        '$mstring')");
	    if (!$query_result || !$query_result->numrows) {
		print STDERR "*** $0:\n".
			     "    Could not insert vlan table entry for $id\n";
		$errors++;
		next;
	    }
	    $outer_id = $query_result->insertid;
346

347 348
	    # Insert mapping between inner and outer vlan entries.
	    $query_result = DBQueryWarn("insert into elabinelab_vlans ".
349 350
			 "       (exptidx,pid,eid,inner_id,outer_id) ".
			 "values ($exptidx, '$pid', '$eid', $id, $outer_id)");
351 352 353 354 355 356 357 358 359 360 361 362
	    if (!$query_result || !$query_result->numrows) {
		#
		# Failed, must remove vlans entry too. We keep going though
		# 
		print STDERR "*** $0:\n".
			     "    Could not insert elabinelab_vlans table entry ".
			     "for $id/$outer_id\n";

		DBQueryFatal("delete from vlans where id='$outer_id'");
		$errors++;
		next;
	    }
363
	}
364 365 366 367 368
	if ($debug) {
	    print STDERR "Mapping inner id $id to outer id $outer_id\n";
	    print STDERR "  $mstring\n";
	}
	$vmaptable{$id} = $outer_id;
369 370 371 372 373 374 375 376 377 378
	# Okay, save outer_id up for passing to snmpit below.
	push(@outer_ids, $outer_id);
    }
    # Now call snmpit to create the actual vlans.
    if ($debug) {
	print STDERR "Running 'snmpit -t $pid $eid @outer_ids'\n";
    }
    return $errors
	if ($impotent);
    
379
    system("$TB/bin/snmpit -t $pid $eid @outer_ids > /dev/null");
380 381 382 383 384 385 386 387 388 389 390 391
    if ($?) {
	#
	# Yuck failed. We leave things as is, and wait for experiment
	# teardown to destroy any vlans that managed to get set up.
	# Obviously, we must leave the vlans in the DB or else we will not
	# be able to clean up later. 
	# This mirrors what happens when snmpit fails during a normal setup.
	#
	print STDERR "*** $0:\n".
	             "    snmpit -t failed!\n";
	$errors = $? >> 8;
    }
392 393 394 395 396 397 398 399 400 401 402 403 404
    my @results = ();
    foreach $id (keys %vmaptable) {
	my $mapid = $vmaptable{$id};
	$query_result = DBQuery("select tag from vlans where id='$mapid'");
	if (!$query_result || $query_result->numrows != 1) {
	    print STDERR "couldn't retrive vlan 802.1Q number for $mapid \n";
	     $errors++;
	} else {
	    my ($tagnum) = $query_result->fetchrow();
	    push (@results, "$id#$tagnum");
	}
    }
    print join(",", @results);
405 406 407
    return $errors;
}
#
408 409 410
# This is common to list and destroy
#
sub Map()
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
{
    my $query_result =
	DBQueryFatal("select inner_id,outer_id from elabinelab_vlans ".
		     "where pid='$pid' and eid='$eid'");

    while (my ($inner_id,$outer_id) = $query_result->fetchrow()) {
	$mapping{$inner_id} = $outer_id;
    }
    #
    # Sanity check; make sure the set of vlans we got on the command line
    # (from the inner elab via the RPC server) are really vlans we have
    # already setup. Anything that does not match, skip with a warning, but
    # go ahead and tear down ones that match.
    #
    while (@ARGV) {
	my $id = shift(@ARGV);

428
	if ($id eq "") { next ; }
429 430 431 432 433 434 435 436 437 438 439 440 441 442
	if (! ($id =~ /^\d+$/)) {
	    print STDERR "*** $0:\n".
		         "    Illegal characters in id: $id\n";
	    next;
	}

	if (!exists($mapping{$id})) {
	    print STDERR "*** $0:\n".
		         "    No such elabinelab_vlans table entry: $id\n";
	    next;
	}
	push(@inner_ids, $id);
	push(@outer_ids, $mapping{$id});
    }
443 444 445 446 447 448 449 450 451 452 453 454
    return 0;
}

#
# Destroy a set of vlans. We get a list of inner vlan ID numbers for the
# inner elab vlans table. We have to map those to outer vlan table id
# numbers, and then remove those from the DB and from the switches.
# 
sub DestroyVlans()
{

    Map();
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
    # If no vlans, do nothing! snmpit will end up removing all the vlans!
    return 0
	if (! @outer_ids);
    return 0
	if ($impotent);

    #
    # Okay, ask snmpit to tear down these vlans. 
    #
    if ($debug) {
	print STDERR "Running 'snmpit -r $pid $eid @outer_ids'\n";
    }
    system("$TB/bin/snmpit -r $pid $eid @outer_ids");
    if ($?) {
	#
	# Yuck failed. We leave things as is, and wait for the inner elab
	# to request experiment teardown again. This mirrors what happens
	# on a normal swapout; snmpit -r can be retried until all of the
	# vlans are finally gone; At that point the DB state can be removed.
	#
	print STDERR "*** $0:\n".
	             "    snmpit -r failed!\n";
	return $? >> 8;
    }

    #
    # Okay, remove the outer vlan table entries first. 
    #
    if ($debug) {
	print STDERR "Removing @outer_ids from vlans table\n";
    }
    DBQueryFatal("delete from vlans ".
		 "where pid='$pid' and eid='$eid' and ".
		 # Join "id='foo'" with ORs
		 "(" . join(' OR ', map("id='$_'", @outer_ids)) . ")");

    #
    # Since the above worked, we can remove the mappings too.
    # 
    if ($debug) {
	print STDERR "Removing @inner_ids from elabinelab_vlans table\n";
    }
    DBQueryFatal("delete from elabinelab_vlans ".
		 "where pid='$pid' and eid='$eid' and ".
		 # Join "id='foo'" with ORs
		 "(" . join(' OR ', map("inner_id='$_'", @inner_ids)) . ")");

    return 0;
}
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 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 607 608
#
# List a set of vlans. We get a list of inner vlan ID numbers for the
# inner elab vlans table. We have to map those to outer vlan table id
# numbers, and then list.
# 
sub List()
{
    my @pairs;

    Map();
    if (!@inner_ids) { @inner_ids = keys %mapping; }
    if (!@inner_ids) { return 0; }

    foreach my $in (@inner_ids) {
	my $out = $mapping{$in};
	push @pairs, "$out#$in";
    }
    my $command = "$TB/bin/snmpit -L " . join(",", @pairs);
    system($command);
    if ($?) {
	# Yuck failed.
	print STDERR "*** $0:\n".  "    snmpit -L failed!\n";
	return $? >> 8;
    }
    return 0;
}

#
# Either put a(n experimental) port into standard, or dual-mode trunking
# or reset to its normal state (snmpit -E , -T or - U).
#
sub Trunk()
{
    my $mode = shift(@ARGV);
    my $port = shift(@ARGV);

    $port =~ /^(.+):(.+)/;
    my ($node, $card) = ($1,$2);
    my $query =
	"select iface from interfaces where node_id='$node' and card='$card'";
    my $query_result = DBQueryFatal($query);
    if ($query_result->numrows != 1) {
	print STDERR "can't determine iface from $port in $pid/$eid\n";
	return 1;
    }
    my ($iface) = ($query_result->fetchrow())[0];

    $query_result =
	DBQueryFatal("select node_id from reserved where node_id='$node' ".
		     "and pid='$pid' and eid='$eid'");
    if ($query_result->numrows != 1) {
	print STDERR "$node not allocated to $pid / $eid\n";
	return 1;
    }
    Map();
    if ($mode eq "-U") {
	$query_result = DBQueryFatal("select iface from vinterfaces where " .
			 "node_id='$node' and type='vlan' and iface='$iface'");
	if ($query_result->numrows == 0) {
	    print STDERR "$port not trunked in database\n";
	    return 1;
	}
	#
	# Okay, ask snmpit to Untrunk
	#
	if ($debug) {
	    print STDERR "Running 'snmpit -U $port'\n";
	}
	system("$TB/bin/snmpit -U $port > /dev/null");
	if ($?) {
	    # Yuck failed.
	    print STDERR "*** $0:\n".  "    snmpit -U failed!\n";
	    return $? >> 8;
	}
	#
	# and clean up the database
	#
	$query_result = DBQueryFatal("delete from vinterfaces where " .
			 "node_id='$node' and type='vlan' and iface='$iface'");
	return 0;
    }
    if (($mode eq "-E") || ($mode eq "-T")) {
	# First, update the status of the port in the database
	# The code here is wrong and needs futher work.
	# apparently there is a vinterfaces entry for each vlan
	# however in order to figure out which one you have to
	# do a join through both the vlans and virt_lans tables.
	# There's no convenient way, given the management
	# interface, to come up with a unique IP address that's
	# appropriate to stuff.  It seems likely that the structure
	# of the database will be revised, in this area, but
	# for now, we'll just play Joe Isuzu.
	$query_result = DBQueryFatal("select iface from vinterfaces where " .
			  "node_id='$node' and iface='$iface'");
	if ($query_result->numrows != 0) {
	    DBQueryFatal("update vinterfaces set type='vlan' where " .
	      "node_id='$node' and iface='$iface'");
	} else {
	    DBQueryFatal(
	    "replace into vinterfaces (node_id,iface,type) " .
	    "values ('$node','$iface','vlan')");
	}
	#
	# Okay, ask snmpit to trunk these vlans. 
	#
609
	my $command = "$TB/bin/snmpit -S Experiment $mode $port @outer_ids > /dev/null";
610 611 612 613 614 615 616 617 618 619 620 621
	if ($debug) { print STDERR "Running $command\n"; }
	system($command);
	if ($?) {
	    # Yuck failed.
	    print STDERR "*** $0:\n".  "    snmpit $mode failed!\n";
	    return $? >> 8;
	}
	return 0;
    }
    print STDERR "*** unknown mode for trunk request: $mode \n";
    return 1;
}