snmpit.proxyv3.in 34 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2019 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#
use strict;
use English;
use Getopt::Std;
use RPC::XML::Parser;
use Data::Dumper;

#
# Snmpit proxy for ElabInElab.
#
sub usage()
{
    print STDOUT "Usage: snmpit.proxy ".
	"[-d] [-o outfile] -p <pid> -e <eid> <xmldoc>\n";
    exit(-1);
}
my $optlist  = "dnp:e:o:";
Leigh Stoller's avatar
Leigh Stoller committed
40
my $debug    = 0;
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
my $dlevel   = 1;
my $impotent = 0;
my $exitval  = 0;
my $output;
my $outfile;
my $pid;
my $eid;
my @inner_ids   = ();
my @outer_ids   = ();
my %outer_vlans = ();
my %mapping     = ();

#
# 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 libaudit;
use libtestbed;
use User;
use Experiment;
use Lan;
use Interface;
use Node;

# Locals
my $exptidx;

# Protos
sub SetupVlans($);
sub MakeVlan($);
sub DestroyVlans($);
sub PortControl($);
sub Trunk($);
sub List($);
sub MapVlans(@);
sub ReserveVlanTags($);
sub UnReserveVlanTags($);
sub fatal($);

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
my %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");
    }
}
if (defined($options{"o"})) {
    $outfile = $options{"o"};

    if (! ($outfile =~ /^\/var\/tmp\//)) {
	fatal("$outfile does not resolve to an appropriate directory!");
    }
}
usage()
    if (@ARGV != 1 || !defined($pid) || !defined($eid));

#
# Need a version of system that ensures that all output goes to STDERR
# since anything that goes to STDOUT will confuse the caller (xmlrpc).
# This is sad; the results should not go back as STDOUT text.
#
sub mysystem($)
{
    my ($command) = @_;
    
    open(PIPE,"$command 2>&1 |") or return -1;
    while (<PIPE>) {
	print STDERR $_;
    }
    close(PIPE);
    return $?;
}

#
# Log audit since it is hard to debug this one.
#
LogStart(0, undef, LIBAUDIT_LOGTBOPS()|LIBAUDIT_NODELETE());

my $xmldoc = $ARGV[0];
# Note different taint check (allow /).
if ($xmldoc =~ /^([-\w\.\/]+)$/) {
    $xmldoc = $1;
}
else {
    fatal("Tainted argument $xmldoc");
}
# Cause we are invoked from the xmlrpc server with this name format.
if (! ($xmldoc =~ /^\/var\/tmp\/php[-\w]+/)) {
    fatal("$xmldoc does not resolve to an appropriate directory!");
}
if (! -e $xmldoc) {
    fatal("$xmldoc does not exist!");
}
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}

#
# Sanity check. Must be an ElabInElab experiment and user must have
# permission (be the creator).
#
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    fatal("Experiment $pid/$eid is not active!");
}
$exptidx = $experiment->idx();
if (!$experiment->AccessCheck($this_user, TB_EXPT_MODIFY)) {
    fatal("You do not have permission to swap or modify this experiment!");
}

#
# Open the file and pass the stream to the parser. 
#
open(XMLDOC, $xmldoc) or
    fatal("$xmldoc could not be opened for reading!");

my $parser   = RPC::XML::Parser->new();
my $goo      = $parser->parse(*XMLDOC);
if (! ref($goo)) {
    fatal("$xmldoc could not be parsed!");
}
207
my $opargs  = (@{$goo->args()}[0])->value();
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
if (! (exists($opargs->{'op'}) && exists($opargs->{'args'}))) {
    fatal("missing arguments in xmlgoo");
}
my $op    = $opargs->{'op'};
my $args  = $opargs->{'args'};

# Add stuff for log message if sent.
AddAuditInfo("message", $op . "\n\n" . Dumper($args));

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

SWITCH: for ($op) {
    /setup/ && do {
	($exitval, $output) = SetupVlans($args);
	last;
    };
    /makevlan/ && do {
	($exitval, $output) = MakeVlan($args);
	last;
    };
    /destroy/ && do {
	($exitval, $output) = DestroyVlans($args);
	last;
    };
    /trunk/ && do {
	($exitval, $output) = Trunk($args);
	last;
    };
    /list/ && do {
	($exitval, $output) = List($args);
	last;
    };
    /portcontrol/ && do {
	($exitval, $output) = PortControl($args);
	last;
    };
    /^reserve$/ && do {
	($exitval, $output) = ReserveVlanTags($args);
	last;
    };
    /^unreserve$/ && do {
	($exitval, $output) = UnReserveVlanTags($args);
	last;
    };
    # default case
    fatal("Unknown operation $op");
}

260 261 262
# XXX "switch" statement clears $op
$op    = $opargs->{'op'};

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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 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 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 609 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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 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 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 735 736 737 738 739 740 741 742 743 744 745 746 747 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 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
# Update with output for log message if sent.
AddAuditInfo("message",
	     "$op:\n\n" . Dumper($args) . "\n\n" .
	     (defined($output) ? "$output" : "") . "\n");

#
# Terminate the log capture so that we can print the response to STDOUT
# for the RPC server. 
#
if ($exitval || $debug) {
    # Force error exit so email is sent.
    LogEnd($exitval + $debug);
}
else {
    LogAbort();
}
if (defined($output)) {
    if (defined($outfile)) {
	open(OUTF, ">>$outfile") or
	    fatal("$outfile could not be opened for writing!");
	print OUTF $output;
	close(OUTF);
    }
    else {
	print $output;
    }
}
exit($exitval);

#
# Setup vlans for an inner emulab. 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.
#
# Note that this function assumes the experiment stack. See MakeVlan()
# below for the more basic function to create a single vlan on a stack.
# 
sub SetupVlans($)
{
    my ($argtable) = @_;
    
    my $vlantable = {};
    my %vmaptable = ();
    my $attrtable = {};
    my %nodes     = ();
    my @outer_ids = ();
    my $errors    = 0;

    foreach my $id (keys(%{ $argtable })) {
	my $vtag    = $argtable->{$id}->{'virtual'};
	my $class   = $argtable->{$id}->{'stack'};
	my $members = $argtable->{$id}->{'members'};
	my $trunk_mode = $argtable->{$id}->{'trunk_mode'}
	    if (exists($argtable->{$id}->{'trunk_mode'}));

	if (! ($id =~ /^[\d]+$/)) {
	    fatal("SetupVlans: Illegal id '$id'");
	}
	if (! ($vtag =~ /^[\-\w]+$/)) {
	    fatal("SetupVlans: Illegal vname '$vtag'");
	}
	if (!defined($class)) {
	    $class = "Experimental";
	}
	elsif ($class ne "Control" && $class ne "Experimental") {
	    fatal("SetupVlans: Illegal class '$class'");
	}

	foreach my $port (keys(%{ $members })) {
	    my $speed  = $members->{$port}->{'speed'};
	    my $duplex = $members->{$port}->{'duplex'};
	    my $trunk  = $members->{$port}->{'trunk'};
	    my $node;
	    my $iface;

	    if (! ($port =~ /^[\-\w]+\:[\-\w]+$/)) {
		fatal("SetupVlans: Illegal port '$port'");
	    }
	    if (! ($speed =~ /^[\d]+$/)) {
		fatal("SetupVlans: Illegal speed '$speed'");
	    }
	    if (! ($duplex eq "full" || $duplex eq "half")) {
		fatal("SetupVlans: Illegal duplex '$duplex'");
	    }

	    if (! exists($vlantable->{$id})) {
		$vlantable->{$id} = {};
		$attrtable->{$id} = {"virtual"    => $vtag,
				     "stack"      => $class,
				     "trunk_mode" => $trunk_mode};
	    }
	    $vlantable->{$id}->{$port} = [$speed, $duplex, $trunk];

	    # For doing access and sanity checks below.
	    if ($port =~ /^(.+):(.+)$/) {
		($node,$iface) = ($1, $2);
	    }
	    $nodes{$node} = []
		if (!exists($nodes{$node}));
	    push(@{ $nodes{$node} }, $iface);
	}
    }

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

    # Stoller wrote:
    # 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.

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

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

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

	# 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 ...

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

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

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

	    if ($debug) {
		print STDERR "$id $node:$iface $speed $duplex trunk:$trunk\n";
	    }
	    if (! $impotent) {
		DBQueryFatal("update interfaces set ".
			     "   current_speed='$speed',duplex='$duplex', ".
			     "   trunk=$trunk ".
			     "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    = $attrtable->{$id}->{"virtual"};
	my $class   = $attrtable->{$id}->{"stack"};
	my $trunk_mode = $attrtable->{$id}->{"trunk_mode"};
	my @members = keys(%{ $vlantable->{$id} });
	my $mstring = "@members";
	my $outer_id;
	my $vlan;

	# Not doing stacks yet.
	$class = "Experimental";

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

	# Insert (or modify) outer vlans entry.
	my $query_result =
	    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();
	    $vlan = VLan->Lookup($outer_id);
	    if (!defined($vlan)) {
		print STDERR "*** $0:\n".
			     "    Could not lookup vlan for $outer_id\n";
		$errors++;
		next;
	    }

	    #
	    # List of members to destroy.
	    #
	    my @curmembers;
	    if ($vlan->MemberList(\@curmembers) != 0) {
		print STDERR "Could not get member list for $vlan\n";
		$errors++;
		next;
	    }
	    foreach my $member (@curmembers) {
		if ($vlan->DelMember($member) != 0) {
		    print STDERR "Could not delete $member from $vlan\n";
		    $errors++;
		}
	    }
	}
	else {
	    $vlan = VLan->Create($experiment, $vtag);
	    if (!defined($vlan)) {
		print STDERR "*** $0:\n".
			     "    Could not insert vlan table entry for $id\n";
		$errors++;
		next;
	    }
	    $vlan->SetClass($class);
	    $outer_id = $vlan->lanid();
	    $vlan->SetAttribute("trunk_mode", $trunk_mode)
		if (defined($trunk_mode));

	    # Insert mapping between inner and outer vlan entries.
	    $query_result =
		DBQueryWarn("insert into elabinelab_vlans ".
			    "      (exptidx,pid,eid,inner_id,outer_id,stack) ".
			    "values ($exptidx, '$pid', '$eid', '$id', ".
			    "        '$outer_id', '$class')");
	    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";

		$vlan->Destroy();
		$errors++;
		next;
	    }
	}
	if ($debug) {
	    print STDERR "Mapping inner id $id to outer id $outer_id\n";
	    print STDERR "  $mstring\n";
	}
	foreach my $port (@members) {
	    my ($nodeid, $iface) = split(":", $port);
	    if (!$vlan->IsMember($nodeid, $iface) &&
		!$vlan->AddMember($nodeid, $iface)) {
		print STDERR "*** $0:\n".
		    "    Could not $port to $vlan\n";
		$errors++;
	    }
	}
	$vmaptable{$id} = $outer_id;
	# Okay, save outer_id up for passing to snmpit below.
	push(@outer_ids, $outer_id);
	# And save vlan object for getting the tag.
	$outer_vlans{$outer_id} = $vlan;
    }
    # Not doing stacks yet.
    my $stackopt = "";
    my $debugopt = ($debug ? "-v $dlevel" : "");
    
    # Now call snmpit to create the actual vlans.
    if ($debug) {
	print STDERR "Running 'snmpit $stackopt -t $pid $eid @outer_ids'\n";
    }
    return $errors
	if ($impotent);
    
    mysystem("$TB/bin/snmpit $debugopt $stackopt -t $pid $eid @outer_ids");
    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;
    }
    my @results = ();
    foreach my $id (keys %vmaptable) {
	my $outer_vlan = $outer_vlans{$vmaptable{$id}};

	if ($outer_vlan->Refresh() != 0) {
	    print STDERR "*** Could not refresh $outer_vlan\n";
	    $errors++;
	    next;
	}
	my $tagnum = $outer_vlan->GetTag();
	if ($tagnum <= 0) {
	    print STDERR "*** Could not get vlan tag for $outer_vlan\n";
	    $errors++;
	    next;
	}
	push (@results, "$id#$tagnum");
    }
    return $errors, join(",", @results);

}

#
# This is common to list and destroy and trunk.
#
sub MapVlans(@)
{
    my @vlanids = @_;
    
    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 (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 (@vlanids) {
	my $id = shift(@vlanids);

	if ($id eq "") { next ; }
	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;
	}

	my $vlan = VLan->Lookup($mapping{$id});
	if (!defined($vlan)) {
	    print STDERR "*** $0:\n".
		         "    Cannot find vlan object for vlan id: $id\n";
	    next;
	}
	push(@inner_ids, $id);
	push(@outer_ids, $mapping{$id});
	$outer_vlans{$mapping{$id}} = $vlan;
    }
    return 0;
}

#
# Add ports to a vlan, creating it if needed. This is mostly to support
# inner firewalls.
# 
sub MakeVlan($)
{
    fatal("Unsupported for ElabinElab");
}

#
# 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($)
{
    my ($args) = @_;

    if (! exists($args->{'vlans'})) {
	fatal("DestroyVlans: Missing arguments");
    }
    my @vlanids     = @{ $args->{'vlans'} };
    my $cleartrunks = $args->{'cleartrunks'};
    my $cleartags   = $args->{'cleartags'};
    my @done        = ();
    my $errors      = 0;
    my $class;
    my $debugopt = ($debug ? "-v $dlevel" : "");
    
    MapVlans(@vlanids);
    # If no vlans, do nothing! snmpit will end up removing all the vlans!
    return 0
	if (! @outer_ids);
    return 0
	if ($impotent);

    #
    # Clear the trunks first.
    #
    if ($cleartrunks) {
	my %ports    = ();
	my @portlist;

	foreach my $vlanid (@vlanids) {
	    my $outer_id = $mapping{$vlanid};
	    my $vlan     = $outer_vlans{$outer_id};
	
	    $vlan->PortList(\@portlist);
	    foreach my $port (@portlist) {
		$ports{$port} = $port;
	    }
	}
	foreach my $port (keys(%ports)) {
	    my ($nodeid, $iface) = split(":", $port);
	    
	    if ($debug) {
		print STDERR "Running 'snmpit -U $port'\n";
	    }
	    mysystem("$TB/bin/snmpit $debugopt -U $port");

	    if ($?) {
		print STDERR "*** $0:\n".
		    "    snmpit -U $port failed!\n";
		$errors = $? >> 8;
		goto bad;
	    }
	    DBQueryFatal("update interfaces set ".
			 "   current_speed=0,trunk=0 ".
			 "where node_id='$nodeid' and iface='$iface'");
	}
    }

    #
    # Okay, ask snmpit to tear down these vlans. 
    #
    foreach my $vlanid (@vlanids) {
	my $outer_id = $mapping{$vlanid};
	my $vlan     = $outer_vlans{$outer_id};
	my $vname    = 
	my $class    = $vlan->GetClass();
	# Not doing stacks yet;
	my $stackopt = "";
	my $tagopt   = ($cleartags ? "-C" : "");

	#
	# If the vlan is not created on the switch, we can skip the call
	# to snmpit.
	#
	if ($vlan->CreatedOnSwitches()) {
	    if ($debug) {
		print STDERR
		  "Running 'snmpit $stackopt $tagopt -o $outer_id $pid $eid'\n";
	    }
	    mysystem("$TB/bin/snmpit ".
		     "$debugopt $stackopt $tagopt -o $outer_id $pid $eid");
	    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 -o can
		# be retried until all of the vlans are finally gone; At
		# that point the DB state can be removed.
		#
		print STDERR "'snmpit $stackopt $tagopt ".
		    "-o $outer_id $pid $eid' failed!\n";
		$errors = $? >> 8;
		goto bad;
	    }
	}

	#
	# Leave the outer translation and lan entry intact if cleartags
	# is not set. This sorta mimics what happens on the outer emulab
	# when -r is used; the actual vlans are removed but the lans
	# table entries are left behind. This is very important for protogeni
	# inside of ElabInElab, where we need to reserve the vlan tags,
	# but allow the lans to be torn down and recreated, without changing
	# those tag reservations. 
	#
	goto done
	    if (!$cleartags);

	if ($vlan->ClearReservedVlanTag() != 0) {
	    print STDERR "Could not clear tag reservation for $vlan\n";
	    $errors++;
	    goto bad;
	}
	
	#
	# Remove the outer vlan table entries first. 
	#
	if ($debug) {
	    print STDERR "Removing $outer_id from lans table\n";
	}
	if ($vlan->Destroy() != 0) {
	    print STDERR "Could not Destroy() $vlan\n";
	    $errors++;
	    goto bad;
	}
	#
	# Since the above worked, we can remove the mappings too.
	# 
	if ($debug) {
	    print STDERR "Removing $outer_id from elabinelab_vlans table\n";
	}
	if (!DBQueryWarn("delete from elabinelab_vlans ".
			 "where pid='$pid' and eid='$eid' and ".
			 "      inner_id='$vlanid'")) {
	    $errors++;
	    goto bad;
	}
      done:
	push(@done, $vlanid);
    }
  bad:
    return $errors, join(",", @done);
}
#
# 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 ($args)  = @_;

    if (! exists($args->{'vlans'})) {
	fatal("List: Missing arguments");
    }
    my @vlanids = @{ $args->{'vlans'} };
    my @pairs;

    MapVlans(@vlanids);
    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);
    my $output = `$command`;
    if ($?) {
	# Yuck failed.
	print STDERR "*** $0:\n".  "    snmpit -L failed!\n";
	return $? >> 8;
    }
    return 0, $output;
}

#
# 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 ($args)  = @_;
860
    my $interface;
861 862 863 864 865 866 867 868 869 870 871 872 873

    if (! (exists($args->{'mode'}) && exists($args->{'vlans'}) &&
	   exists($args->{'port'}))) {
	fatal("Trunk: Missing arguments");
    }
    my $mode    = $args->{'mode'};
    my $port    = $args->{'port'};
    my @vlanids = @{ $args->{'vlans'} };

    # Taint check these args.
    if (! ($mode eq "-T" || $mode eq "-E" || $mode eq "-U")) {
	fatal("Trunk: Improper mode '$mode'");
    }
874
    if (! ($port =~ /^[-\w]+:[-\w\/\.]+$/)) {
875 876 877 878 879 880 881 882 883 884 885 886 887
	fatal("Trunk: Illegal port '$port'");
    }
    # Not doing stacks yet.
    my $class    = "Experimental";
    my $stackopt = "";
    if (0 && exists($args->{'stack'})) {
	$class = $args->{'stack'};
	if ($class ne "Control" && $class ne "Experimental") {
	    fatal("Trunk: Improper class argument: $class");
	}
    }
    my $debugopt = ($debug ? "-v $dlevel" : "");

888 889
    $port =~ /^([-\w]+):([-\w\/\.]+)/;
    my ($nodeid, $iface) = ($1,$2);
890

891 892 893
    my $node = Node->Lookup($nodeid);
    if (!defined($node)) {
	fatal("Trunk: No such node $nodeid");
894
    }
895 896
    my $reservation = $node->Reservation();
    if (! (defined($reservation) && $reservation->SameExperiment($experiment))) {
897 898
	fatal("Trunk: $node not allocated to $pid/$eid");
    }
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    
    #
    # Older code sends a card, newer code sends an iface.
    # Eventually flush this backwards compat code. 
    #
    if ($iface =~ /\d+/) {
	$interface = Interface->Lookup($nodeid, $iface, 1);
    }
    else {
	$interface = Interface->LookupByIface($nodeid, $iface);
    }
    if (!defined($interface)) {
	fatal("Trunk: No such interface $iface on $nodeid");
    }
    # In case we got a card.
    $iface = $interface->iface();

916 917 918
    MapVlans(@vlanids);
    if ($mode eq "-U") {
	if ($class eq "Experimental") {
919
	    my $query_result =
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
		DBQueryFatal("select iface from vinterfaces " .
			     "where node_id='$node' and type='vlan' and ".
			     "      iface='$iface'");
	    if ($query_result->numrows == 0) {
		fatal("Trunk: $port not trunked in database");
	    }
	}
	#
	# Okay, ask snmpit to Untrunk
	#
	if ($debug) {
	    print STDERR "Running 'snmpit $stackopt -U $port'\n";
	}
	mysystem("$TB/bin/snmpit $debugopt $stackopt -U $port");
	if ($?) {
	    # Yuck failed.
	    fatal("snmpit $stackopt -U failed!");
	}
	#
	# and clean up the database
	#
	if ($class eq "Experimental") {
942 943
	    $interface->Update({"trunk" => 0}) == 0 or
		fatal("Trunk: Could not set trunk=0 for $interface");
944 945 946 947 948 949
	}
	return 0;
    }
    if (($mode eq "-E") || ($mode eq "-T")) {
	# First, update the status of the port in the database
	if ($class eq "Experimental") {
950 951
	    $interface->Update({"trunk" => 1}) == 0 or
		fatal("Trunk: Could not set trunk=1 for $interface");
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
	}
	#
	# Okay, ask snmpit to trunk these vlans. 
	#
	my $command =
	    "$TB/bin/snmpit $debugopt $stackopt $mode $port @outer_ids";
	if ($debug) { print STDERR "Running $command\n"; }
	mysystem($command);
	if ($?) {
	    # Yuck failed.
	    fatal("Trunk: snmpit $stackopt $mode $mode @outer_ids failed!");
	}
	return 0;
    }
    print STDERR "*** unknown mode for trunk request: $mode \n";
    return 1;
}

#
# Port control function.
#
sub PortControl($)
{
    my ($args)  = @_;

    if (! (exists($args->{'command'}) && exists($args->{'ports'}))) {
	fatal("PortControl: Missing arguments");
    }
    my $command = $args->{'command'};
    my @ports   = @{ $args->{'ports'} };

    # Not doing stacks yet;
    my $class    = "Experimental";
    my $debugopt = ($debug ? "-v $dlevel" : "");

    #
    # Check the ports. Must be valid format and belong to node reserved
    # to the elabinelab.
    #
    foreach my $port (@ports) {
992 993 994
	my $interface;
	
	if (! ($port =~ /^[-\w]+:[-\w\/\.]+$/)) {
995 996 997
	    fatal("PortControl: Illegal port '$port'");
	}

998 999
	$port =~ /^([-\w]+):([-\w\/\.]+)/;
	my ($nodeid, $iface) = ($1,$2);
1000 1001 1002 1003 1004

	my $node = Node->Lookup($nodeid);
	if (!defined($node)) {
	    fatal("PortControl: No such node $nodeid");
	}
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
	#
	# Older code sends a card, newer code sends an iface.
	# Eventually flush this backwards compat code. 
	#
	if ($iface =~ /\d+/) {
	    $interface = Interface->Lookup($nodeid, $iface, 1);
	}
	else {
	    $interface = Interface->LookupByIface($nodeid, $iface);
	}
1015
	if (!defined($interface)) {
1016
	    fatal("PortControl: No such interface $iface on $nodeid");
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
	}
	my $reservation = $node->Reservation();
	if (!defined($reservation) ||
	    !$experiment->SameExperiment($reservation)) {
	    fatal("PortControl: $nodeid is not reserved to $experiment");
	}
    }
    SWITCH: for ($command) {
	/enable/ && do {
	    $command = "-e";
	    last;
	};
	/disable/ && do {
	    $command = "-d";
	    last;
	};
	/auto/ && do {
	    $command = "-a";
	    last;
	};
	/10mbit/ && do {
	    $command = "-p 10";
	    last;
	};
	/100mbit/ && do {
	    $command = "-p 100";
	    last;
	};
	/1000mbit/ && do {
	    $command = "-p 1000";
	    last;
	};
	/full/ && do {
	    $command = "-u full";
	    last;
	};
	/half/ && do {
	    $command = "-u half";
	    last;
	};
	# 'default' case
	Fatal("PortControl: Unknown command $command");
    }
    #
    # Okay, ask snmpit to do the deed.
    #
    if ($debug) {
	print STDERR "Running 'snmpit $command @ports\n";
    }
    mysystem("$TB/bin/snmpit $debugopt $command @ports");
    if ($?) {
	# Yuck failed.
	fatal("snmpit $command @ports");
    }
    return 0;
}

#
# Reserve a set of vlan tags that are going to be needed by the inner elab.
#
sub ReserveVlanTags($)
{
    my ($argtable) = @_;
    my %vmaptable  = ();
    my @outer_ids  = ();
    my $errors     = 0;

    foreach my $id (keys(%{ $argtable })) {
	my $vname   = $argtable->{$id}->{'virtual'};
	my $class   = $argtable->{$id}->{'stack'};
	my $tags    = $argtable->{$id}->{'tags'};

	if (! ($id =~ /^[\d]+$/)) {
	    fatal("ReserveVlanTags: Illegal id '$id'");
	}
	if (! ($vname =~ /^[\-\w]+$/)) {
	    fatal("ReserveVlanTags: Illegal vname '$vname'");
	}
	if (defined($tags)) {
	    fatal("ReserveVlanTags: Illegal tags format")
		if (!ref($tags));
	    foreach my $tag (@{ $tags }) {
		fatal("ReserveVlanTags: Illegal tag $tag")
		    if (! ($tag =~ /^\d*$/));
	    }
	}
	if (!defined($class)) {
	    $class = "Experimental";
	}
	elsif ($class ne "Control" && $class ne "Experimental") {
	    fatal("ReserveVlanTags: Illegal class '$class'");
	}
    }

    #
    # Create local vlan objects. They have no members yet, but are just
    # placeholders to hold the reserved vlantags.
    #
    foreach my $id (keys(%{ $argtable })) {
	my $vname   = $argtable->{$id}->{'virtual'};
	my $class   = $argtable->{$id}->{'stack'};
	my $tags    = $argtable->{$id}->{'tags'};
	my $tagopt  = (defined($tags) ? join(",", @{$tags}) : undef);
	my $outer_id;
	my $vlan;

	# Not doing stacks yet.
	$class = "Experimental";

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

	# Insert (or modify) outer vlans entry.
	my $query_result =
	    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();
	    $vlan = VLan->Lookup($outer_id);
	    if (!defined($vlan)) {
		print STDERR "Could not lookup vlan for $outer_id\n";
		$errors++;
		next;
	    }
	}
	else {
	    $vlan = VLan->Create($experiment, $vname);
	    if (!defined($vlan)) {
		print STDERR "Could not insert vlan table entry for $id\n";
		$errors++;
		next;
	    }
	    $vlan->SetClass($class);
	    $outer_id = $vlan->lanid();

	    # Insert mapping between inner and outer vlan entries.
	    $query_result =
		DBQueryWarn("insert into elabinelab_vlans ".
			    "      (exptidx,pid,eid,inner_id,outer_id,stack) ".
			    "values ($exptidx, '$pid', '$eid', '$id', ".
			    "        '$outer_id', '$class')");
	    if (!$query_result || !$query_result->numrows) {
		#
		# Failed, must remove vlans entry too. We keep going though
		# 
		print STDERR "Could not insert elabinelab_vlans table entry ".
			     "for $id/$outer_id\n";
		$vlan->Destroy();
		$errors++;
		next;
	    }
	}
	if ($debug) {
	    print STDERR "Mapping inner id $id to outer id $outer_id\n";
	}
	$vmaptable{$id} = $outer_id;
	# Okay, save outer_id up for passing to snmpit below.
	push(@outer_ids, (defined($tagopt) ? "$outer_id,$tagopt" : $outer_id));
	# And save vlan object for getting the tag.
	$outer_vlans{$outer_id} = $vlan;
    }
    # Not doing stacks yet.
    my $stackopt = "";
    my $debugopt = ($debug ? "-v $dlevel" : "");
    
    # Now call snmpit to reserve the vlan tags
    if ($debug) {
	print STDERR "Running 'snmpit $stackopt -A $pid $eid @outer_ids'\n";
    }
    return $errors
	if ($impotent);
    
    mysystem("$TB/bin/snmpit $debugopt $stackopt -A $pid $eid @outer_ids");
    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 -A failed!\n";
	$errors = $? >> 8;
    }
    my @results = ();
    foreach my $id (keys %vmaptable) {
	my $outer_vlan = $outer_vlans{$vmaptable{$id}};

	if ($outer_vlan->Refresh() != 0) {
	    print STDERR "*** Could not refresh $outer_vlan\n";
	    $errors++;
	    next;
	}
	my @tags = $outer_vlan->GetReservedVlanTags();
	if (! @tags) {
	    print STDERR "*** Could not get vlan tags for $outer_vlan\n";
	    $errors++;
	    next;
	}
	push (@results, "$id#" . join(":", @tags));
    }
    return $errors, join(",", @results);
}

#
# Clear vlan tag reservations made above. The lans cannot be created.
#
sub UnReserveVlanTags($)
{
    my ($argtable) = @_;
    my $errors     = 0;

    foreach my $id (keys(%{ $argtable })) {
	my $vname   = $argtable->{$id}->{'virtual'};
	my $class   = $argtable->{$id}->{'stack'};
	my $tags    = $argtable->{$id}->{'tags'};

	if (! ($id =~ /^[\d]+$/)) {
	    fatal("SetupVlans: Illegal id '$id'");
	}
	if (! ($vname =~ /^[\-\w]+$/)) {
	    fatal("SetupVlans: Illegal vname '$vname'");
	}
	if (defined($tags)) {
	    fatal("ReserveVlanTags: Illegal tags format")
		if (!ref($tags));
	    foreach my $tag (@{ $tags }) {
		fatal("ReserveVlanTags: Illegal tag $tag")
		    if (! ($tag =~ /^\d*$/));
	    }
	}
	if (!defined($class)) {
	    $class = "Experimental";
	}
	elsif ($class ne "Control" && $class ne "Experimental") {
	    fatal("SetupVlans: Illegal class '$class'");
	}
    }

    #
    # Create local vlan objects. They have no members yet, but are just
    # placeholders to hold the reserved vlantags.
    #
    foreach my $id (keys(%{ $argtable })) {
	my $vname   = $argtable->{$id}->{'virtual'};
	my $class   = $argtable->{$id}->{'stack'};
	my $tags    = $argtable->{$id}->{'tags'};

	# Not doing stacks yet.
	$class = "Experimental";

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

	#
	# Find translation entry.
	#
	my $query_result =
	    DBQueryFatal("select outer_id from elabinelab_vlans ".
			 "where pid='$pid' and eid='$eid' and inner_id='$id'");
	
	if (!$query_result || !$query_result->numrows) {
	    print STDERR "No translation table entry for $id\n";
	    $errors++;
	    next;
	}
	my ($outer_id) = $query_result->fetchrow();
	my $vlan = VLan->Lookup($outer_id);
	if (!defined($vlan)) {
	    #
	    # Safe to clear it from the reserved table since it is not on a
	    # switch.
	    #
	    if (!$impotent) {
		if (defined($tags)) {
		    foreach my $tag (@{ $tags }) {
			VLan::ClearReservedVlanTag($outer_id, $tag) == 0
			    or $errors++;
		    }
		}
		else {
		    VLan::ClearReservedVlanTag($outer_id) == 0
			or $errors++;
		}
	    }
	}
	else {
	    #
	    # Cannot clear a reservation for a lan that is on the switches.
	    #
	    if ($vlan->CreatedOnSwitches()) {
		print STDERR "vlan $id exists on a stack, cannot clear.\n";
		$errors++;
		next;
	    }
	    if (!$impotent) {
		if (defined($tags)) {
		    foreach my $tag (@{ $tags }) {
			$vlan->ClearReservedVlanTag($tag) == 0
			    or $errors++;
		    }
		}
		else {
		    $vlan->ClearReservedVlanTag() == 0
			or $errors++;
		}
	    }
	}
    }
    return $errors;
}

sub fatal($)
{
    my ($msg) = @_;

    die("*** $0:\n",
	"    $msg\n");
}