parse-ns.in 28.1 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3

#
4
# Copyright (c) 2000-2014 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{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/>.
# 
# }}}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
24 25
#

26 27
use English;
use Getopt::Std;
28
use Socket;
29
use File::Basename;
30
use POSIX ":sys_wait_h";
31

32
#
33 34 35 36 37 38
# Parse an ns file. Since the parser runs arbitrary NS file for the user,
# this cannot be safely done on boss without jumping through huge hoops
# to secure tcl and the DB. Yuck! So, instead of running the parser on boss,
# we run it over on ops. This first version operates like this:
#
# NB: This script is setuid.
39 40 41 42
#
sub usage()
{
    print STDOUT
43
	"Usage: parse-ns [options] pid gid eid nsfile\n".
44 45 46 47
        "Where options and arguments are those required by parse.tcl\n";
 
    exit(-1);
}
48
my $optlist  = "nqap";
49
my $anonmode = 0;
50
my $passmode = 0;
51 52
my $impotent = 0;
my $debug    = 0;
53 54 55 56 57 58

#
# Configure variables
#
my $TB       = "@prefix@";
my $TBOPS    = "@TBOPSEMAIL@";
59 60 61 62 63 64 65
my $CONTROL  = "@USERNODE@";
my $TESTMODE = @TESTMODE@;

# Locals
my $infile   = "parse.input";
my $outfile  = "parse.output";
my $SAVEUID  = $UID;
66
my $this_user;
67 68 69
my $pid;
my $gid;
my $eid;
70
my $exptidx;
71
my $nsfile;
72
my $experiment;
73 74 75 76 77 78 79 80 81

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

#
# Untaint the path
# 
82
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/sbin:/usr/sbin";
83 84
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

85 86 87 88 89 90
if ($TESTMODE) {
    # In testmode, drop privs (my devel tree at home is TESTMODE=1)
    $EUID = $UID;
}
elsif ($EUID != 0) {
    # We don't want to run this script unless its the real version.
91
    die("Must be root! Maybe its a development version?");
92 93 94 95 96
}

# This script is setuid, so please do not run it as root. Hard to track
# what has happened.
if ($UID == 0) {
97
    die("Please do not run this as root! Its already setuid!");
98 99
}

100 101 102 103
#
# Testbed Support libraries
#
use lib "@prefix@/lib";
104
use libdb;
105
use libtestbed;
106 107
use libtblog;
use libtblog qw(dblog *SERR);
108
use NodeType;
109 110
use Template;
use Experiment;
111
use User;
112
use BlockstoreType;
113 114
use Blockstore;
use Lease;
115
use OSinfo;
116

117 118 119 120 121
use constant false => 0;
use constant true  => 1;

sub parse_error($);

122
#
123 124
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
125
#
126 127 128 129 130 131 132 133 134 135
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"a"})) {
    $anonmode = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
136 137 138
if (defined($options{"p"})) {
    $passmode = 1;
}
139 140 141
if (@ARGV != 4 && @ARGV != 1) {
    usage();
}
142

143 144 145 146 147 148 149 150
if (@ARGV == 1) {
    $nsfile = $ARGV[0];
}
else {
    $pid   = $ARGV[0];
    $gid   = $ARGV[1];
    $eid   = $ARGV[2];
    $nsfile= $ARGV[3];
151 152 153
}

#
154
# Must taint check!
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
if ($nsfile =~ /^([-\w\/\.]+)$/) {
    $nsfile = $1;
}
else {
    die("Bad data in argument: $nsfile.");
}
   
if (defined($pid)) {
    if ($pid =~ /^([-\w]+)$/) {
	$pid = $1;
    }
    else {
	die("Bad data in argument: $pid.");
    }
    if ($eid =~ /^([-\w]+)$/) {
	$eid = $1;
    }
    else {
	die("Bad data in argument: $eid.");
    }
    if ($gid =~ /^([-\w]+)$/) {
	$gid = $1;
    }
    else {
	die("Bad data in argument: $gid.");
    }
182 183 184 185 186 187

    # Slowly convert to new libraries ...
    $experiment = Experiment->Lookup($pid, $eid);
    if (! defined($experiment)) {
	tbdie("Cannot find the experiment object for $pid/$eid");
    }
188
    $exptidx = $experiment->idx();
189 190 191 192 193 194 195 196 197 198 199
}

# Remove temps cause of swapin by alternates.
unlink($infile);
unlink($outfile);

if (!$TESTMODE) {
    #
    # Get DB uid for sending over to ops. In testmode, it runs locally
    # as the user running the testsuite, obviously.
    #
200 201 202
    $this_user = User->ThisUser();
    if (! defined($this_user)) {
	tbdie("You ($UID) do not exist!");
203
    }
204

205 206
    # Run as the user for most of this script.
    $EUID = $UID;
207 208
}

209
# Create the defs files.
210
sub GenDefsFile($);
211 212 213 214 215 216
GenDefsFile($infile);

# Now append the NS file to. This part is hokey. Fix later.
system("cat $nsfile >> $infile") == 0
    or die("Could not combine TCL defs file and the NS file!\n");

217 218 219 220 221
#
# Touch the output file, to avoid a root owned, 644 file. 
#
if (-e $outfile) {
    unlink($outfile) or
222
	tbdie("Could not unlink $outfile");
223 224
}
system("touch $outfile") == 0 or
225
    tbdie("Could not create $outfile");
226

227
#
228 229 230
# Build up a new command line to run the parser on ops, writing the
# result back to a file if not in anonmode. Remember to tack on the
# user ID to flip to, when not in testmode.
231
#
232
my $cmdargs = "$TB/libexec/ns2ir/parse.proxy ";
233 234
$cmdargs .= " -u " . $this_user->uid() . " "
    if (defined($this_user));
235
$cmdargs .= " -- ";
236
$cmdargs .= " -a"
237
    if ($anonmode);
238 239 240 241
$cmdargs .= " -n"
    if (defined($options{"n"}));
$cmdargs .= " -q"
    if (defined($options{"q"}));
242 243
$cmdargs .= " -p"
    if ($passmode);
244 245
$cmdargs .= " $pid $gid $eid"
    if (!$anonmode);
246 247

#
248
# Run parser, redirecting stdout to a file to capture the parser results.
249
# Stderr is redirected to the ERR filehandle
250
# Must flip to real root to run ssh.
251
#
252
if ($TESTMODE) {
253
    #
254 255
    # In testmode, no ssh. Just run locally.
    #
256
    open ERR, "$cmdargs < $infile 2>&1 >> $outfile |";
257 258
}
else {
259
    #
260 261 262 263
    # In non-testmode, must flip to real root for the ssh, and then flip
    # back afterwards.
    # 
    $EUID = $UID = 0;
264
    open ERR, "sshtb -host $CONTROL $cmdargs < $infile 2>&1 >> $outfile |";
265 266 267
    $EUID = $UID = $SAVEUID;
}

268 269 270 271 272 273
#
# Now read in the results from stderr and correctly insert the errors
# into the database under the process name of the script called above.
# Also echo the results to the non-captured stderr (SERR).  This is
# needed because parse.proxy may be run on ops, not boss.
#
274
my $errs;
275 276 277 278 279 280 281 282 283
{
    my $old_env = \%ENV;
    local %ENV;
    copy_hash %ENV, $old_env;

    my @argv = split /\s+/, $cmdargs;
    my $cmd = basename(shift @argv);
    
    tblog_new_process($cmd, @argv);
284
    tblog_set_default_cause('user');
285 286 287 288 289 290

    my $err = '';
    
    # assume any output indicates an error
    while (<ERR>) {
	print SERR $_;
291
	$errs .= $_;
292
	if (/^\s*\*\*\*\s*(.+)/) {
293
	    parse_error($err);
294 295 296 297 298 299 300 301
	    dblog(TBLOG_ERR, {}, $err) if $err; # flush any previous errors
	    $_ = $1;
	    if (/^\S+:\s*$/) { # error on next line
		$_ = <ERR>;
		print SERR $_;
		s/^\s+//;
	    } 
	    s/\s+$//;
302
	    parse_error($_);
303 304 305 306 307 308
	    dblog(TBLOG_ERR, {}, $_) if $_;
	    $err = '';
	} else {
	    $err .= $_;
	}
    }
309
    parse_error($err);
310 311 312 313 314 315
    dblog(TBLOG_ERR, {}, $err) if $err;

    tblog_exit();
}
close ERR;

316
if ($?) {
317
    my $exit_status = $?;
318
    
319
    if (WIFSIGNALED($exit_status)) {
320 321 322 323 324 325 326 327 328 329
	# The POSIX module doesn't create constants for valid signals
	# (including SIGBUS), thus we have to do it the hard way.

	# Get the mapping from signal num. to name
	use Config;
	my (%sig_num, @sig_name);
	my @names = split ' ', $Config{sig_name};
	@sig_num{@names} = split ' ', $Config{sig_num};
	foreach (@names) {$sig_name[$sig_num{$_}] ||= $_}

330
	my $signal  = WTERMSIG($exit_status);
331 332 333 334 335 336 337 338 339 340
	my $signame = $sig_name[$signal];
	
	if (grep {$_ eq $signame} qw(ILL TRAP EMT FPE BUS SEGV SYS)) {
	    SENDMAIL($TBOPS, "Parser Crashed",
		     "$errs\n",
		     undef, undef, 
		     $nsfile);
	}
    }
    
341 342 343
    tbdie({cause => 'user', type => 'extra', severity => SEV_ERROR,
	   error => ['ns_parse_failed']},
	  "Parsing failed (error code $exit_status)!");
344 345 346 347 348 349 350
}
exit(0)
    if ($impotent);

#
# Run the XML converter on the output. 
#
351
system("$TB/libexec/xmlconvert -p -x $outfile $pid $eid");
352 353 354 355

if ($?) {
    my $exit_status = $? >> 8;
    
356 357 358
    tbdie({type => 'primary', severity => SEV_ERROR,
	   error => ['xml_converter_failed']},
	  "XML converter exited with error code $exit_status!\n");
359 360 361 362 363
}

#
# Now we have to fix up one minor thing; widearea tunnel IPs. These have
# to be unique, but without the DB to ask, there is no easy way to arrange
364 365
# that.

366
my %subnetmap = ();
367
my $WANETMASK = "255.255.255.248";
368 369 370 371 372 373 374 375 376 377 378 379

my $query_result =
    DBQueryFatal("select vname,ips from virt_nodes ".
		 "where pid='$pid' and eid='$eid'");
while (my ($vname,$ips) = $query_result->fetchrow_array()) {
    my @newiplist = ();
    my $newips;

    foreach my $ipinfo (split(" ", $ips)) {
	my ($port,$ip) = split(":", $ipinfo);
	my ($a,$b,$c,$d) = ($ip =~ /(\d+).(\d+).(\d+).(\d+)/);

380
	if ($a eq "69" && $b eq "69") {
381 382 383
	    my $net = inet_ntoa(inet_aton($WANETMASK) & inet_aton($ip));
		
	    if (! defined($subnetmap{$net})) {
384 385
		DBQueryFatal("insert into ipsubnets (exptidx,pid,eid,idx) ".
			     "values ('$exptidx','$pid','$eid', NULL)");
386 387 388 389
		my ($id) =
		    DBQueryFatal("select LAST_INSERT_ID() ".
				 "from ipsubnets")->fetchrow_array();

390 391 392 393 394 395 396 397 398 399
		# We are going to shift the bits up so they do not conflict
		# with the lower part.
		if ($id >= 8192) {
		    die("No more widearea subnets left!\n");
		}
		$id = $id << 3;

		my $cc = ($id & 0xff00) >> 8;
		my $dd = ($id & 0xf8);
		$subnetmap{$net} = inet_aton("192.168.$cc.$dd");
400
	    }
401 402
	    my $newsubnet = inet_ntoa($subnetmap{$net} | inet_aton("$d"));
	    push(@newiplist, "$port:${newsubnet}");
403 404 405 406
	}
	else {
	    push(@newiplist, $ipinfo);
	}
407
    }
408 409 410 411 412
    $newips = join(" ", @newiplist);
    
    if ($newips ne $ips) {
	DBQueryFatal("update virt_nodes set ips='$newips' ".
		     "where vname='$vname' and pid='$pid' and eid='$eid'");
413 414 415 416 417 418 419 420
	
	foreach my $ipinfo (split(" ", $newips)) {
	    my ($port,$ip) = split(":", $ipinfo);

	    DBQueryFatal("update virt_lans set ip='$ip' ".
			 "where vnode='$vname' and vport='$port' ".
			 "      and pid='$pid' and eid='$eid'");
	}
421 422 423 424 425 426 427 428 429 430 431 432 433 434
    }
}
#
# So, if we ended up changing any, we have look for corresponding entries
# in virt_trafgens, and fix them too.
#
if (keys(%subnetmap)) {
    $query_result =
	DBQueryFatal("select vnode,vname,ip,target_ip from virt_trafgens ".
		     "where pid='$pid' and eid='$eid'");
    while (my ($vnode,$vname,$ip,$dstip) = $query_result->fetchrow_array()) {
	my ($a,$b,$c,$d) = ($ip =~ /(\d+).(\d+).(\d+).(\d+)/);
	my $newip        = $ip;
	my $newdstip     = $dstip;
435
	my $net		 = inet_ntoa(inet_aton($WANETMASK) & inet_aton($ip));
436
	
437 438
	if (defined($subnetmap{$net})) {
	    $newip = inet_ntoa($subnetmap{$net} | inet_aton("$d"));
439 440
	}
	($a,$b,$c,$d) = ($dstip =~ /(\d+).(\d+).(\d+).(\d+)/);
441 442 443
	$net          = inet_ntoa(inet_aton($WANETMASK) & inet_aton($dstip));
	if (defined($subnetmap{$net})) {
	    $newdstip = inet_ntoa($subnetmap{$net} | inet_aton("$d"));
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
	}
	if ($ip ne $newip || $dstip ne $newdstip) {
	    DBQueryFatal("update virt_trafgens set ".
			 "       ip='$newip',target_ip='$newdstip' ".
			 "where pid='$pid' and eid='$eid' and ".
			 "      vnode='$vnode' and vname='$vname'");
	}
    }
}
exit(0);


#
# Open up a TCL file and write a bunch of TCL to it!
#
sub GenDefsFile($)
{
    my($fname) = $_[0];

    open(TCL, "> $fname")
	or die("Could not open TCL defs file for writing: $!\n");

    print TCL "namespace eval TBCOMPAT {\n";

    print TCL "# Event Object Types\n";
    my $query_result =
	DBQueryFatal("select idx,type from event_objecttypes");
    while (my ($idx,$type) = $query_result->fetchrow_array()) {
	print TCL "set objtypes($type) $idx\n";
    }
    print TCL "\n";

    print TCL "# Event Event Types\n";
    $query_result =
	DBQueryFatal("select idx,type from event_eventtypes");
    while (my ($idx,$type) = $query_result->fetchrow_array()) {
	print TCL "set eventtypes($type) $idx\n";
    }
    print TCL "\n";
483 484 485 486 487 488 489 490 491

    print TCL "# Event Trigger Types\n";
    $query_result =
      DBQueryFatal("select idx,type from event_triggertypes");
    while (my ($idx,$type) = $query_result->fetchrow_array()) {
      print TCL "set triggertypes($type) $idx\n";
    }
    print TCL "\n";
 
492 493 494 495 496 497 498 499 500 501
    print TCL "# Node Types and Classes\n";
    my @alltypes = NodeType->AllTypes();
    foreach my $typeinfo (@alltypes) {
	my $type   = $typeinfo->type();
	my $class  = $typeinfo->class();
	my $isrem  = $typeinfo->isremotenode();
	my $isvirt = $typeinfo->isvirtnode();
	my $issub  = $typeinfo->issubnode();
	my $osid   = $typeinfo->default_osid();

502
	print TCL "set hwtypes($type) 1\n";
503
	print TCL "set hwtype_class($type) $class\n";
504 505
	print TCL "set isremote($type) $isrem\n";
	print TCL "set isvirt($type) $isvirt\n";
506 507 508 509
	print TCL "set issubnode($type) $issub\n";

	# Since there are multiple types per class, this is probably not
	# the right thing to do.
510 511 512
	print TCL "set hwtypes($class) 1\n";
	print TCL "set isremote($class) $isrem\n";
	print TCL "set isvirt($class) $isvirt\n";
513 514 515
	print TCL "set issubnode($class) $issub\n";

	if (defined($osid) && $osid ne "") {
516 517 518 519
	    my $osinfo = OSinfo->Lookup($osid);
	    if (defined($osinfo)) {
		my $osname = $osinfo->osname();
		print TCL "set default_osids($type) \"$osname\"\n"
520 521
	    }
	}
522 523
    }
    print TCL "\n";
524
    
525
    print TCL "# Node Aux Types\n";
526 527 528 529 530 531 532 533
    my @auxtypes = NodeType->AuxTypes();
    foreach my $typeinfo (@auxtypes) {
	my $type   = $typeinfo->type();
	my $isrem  = $typeinfo->isremotenode();
	my $isvirt = $typeinfo->isvirtnode();
	my $issub  = $typeinfo->issubnode();
	my $osid   = $typeinfo->default_osid();

534 535 536
	print TCL "set hwtypes($type) 1\n";
	print TCL "set isremote($type) $isrem\n";
	print TCL "set isvirt($type) $isvirt\n";
537 538 539
	print TCL "set issubnode($type) $issub\n";

	if (defined($osid) && $osid ne "") {
540 541 542 543
	    my $osinfo = OSinfo->Lookup($osid);
	    if (defined($osinfo)) {
		my $osname = $osinfo->osname();
		print TCL "set default_osids($type) \"$osname\"\n"
544 545
	    }
	}
546 547
    }
    print TCL "\n";
548 549 550 551 552 553 554 555 556 557

    print TCL "# Global Vtypes\n";
    $query_result = 
        DBQueryFatal("select vtype, weight, types ".
                     " from global_vtypes");
    while (my ($vtype, $weight, $types) = $query_result->fetchrow_array()) {
        print TCL "set ::GLOBALS::vtypes($vtype) [Vtype $vtype $weight {$types}]\n";
    }
    print TCL "\n";

558
    
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    print TCL "# Node Permissions\n";
    my %nodeperms = ();
    $query_result =
	DBQueryFatal("select type,pid from nodetypeXpid_permissions");
    while (my ($type,$pid) = $query_result->fetchrow_array()) {
	if (! defined($nodeperms{$type})) {
	    $nodeperms{$type} = [];
	}
	push(@{$nodeperms{$type}}, $pid);
    }
    foreach my $type (keys(%nodeperms)) {
	my @pids = @{$nodeperms{$type}};

	print TCL "set nodetypeXpid_permissions($type) [list @pids]\n";
    }
    print TCL "\n";

576 577
    print TCL "# Robot areas\n";
    $query_result =
578
	DBQueryFatal("select distinct building from node_startloc");
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
    while (my ($building,$floor) = $query_result->fetchrow_array()) {
	print TCL "set areas($building) 1\n";
    }
    print TCL "\n";

    print TCL "# Obstacles\n";
    $query_result = DBQueryFatal(
	"select o.obstacle_id,o.building,o.x1,o.x2,o.y1,o.y2,o.description, ".
	" fi.pixels_per_meter ".
	"from obstacles as o ".
	"left join floorimages as fi on fi.building=o.building");
    while (my ($id,$building,$x1,$x2,$y1,$y2,$description,$ppm) = 
	   $query_result->fetchrow_array()) {
	print TCL "set obstacles($id,$building,x1) " . $x1 / $ppm . "\n";
	print TCL "set obstacles($id,$building,x2) " . $x2 / $ppm . "\n";
	print TCL "set obstacles($id,$building,y1) " . $y1 / $ppm . "\n";
	print TCL "set obstacles($id,$building,y2) " . $y2 / $ppm . "\n";
	print TCL "set obstacles($id,$building,description) {$description}\n";
    }
    print TCL "\n";

600 601 602 603 604 605 606 607 608 609 610 611
    print TCL "# Cameras\n";
    $query_result = DBQueryFatal(
	"select name,building,loc_x,loc_y,width,height from cameras");
    while (my ($name,$building,$loc_x,$loc_y,$width,$height) = 
	   $query_result->fetchrow_array()) {
	print TCL "set cameras($name,$building,x) $loc_x\n";
	print TCL "set cameras($name,$building,y) $loc_y\n";
	print TCL "set cameras($name,$building,width) $width\n";
	print TCL "set cameras($name,$building,height) $height\n";
    }
    print TCL "\n";

612
    print TCL "# Site variables\n";
613
    my %sitevars = ();
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    $query_result = DBQueryFatal("select name,value,defaultvalue " .
        " from sitevariables where ns_include=TRUE");
    while (my ($name,$value,$defaultvalue) = $query_result->fetchrow_array()) {
        # Use the default value if unset, or skip altogether if the default
        # is just the empty string.
        if (!defined($value)) {
            if ($defaultvalue eq "") {
                next;
            } else {
                $value = $defaultvalue;
            }
        }
        # Escape special characters in the value (just braces)
        $value =~ s/([{}])/\\$1/g;
        # Note: braces in tcl act like single quotes in other scripting
        # languages (eg. no interpolation occurs)
	print TCL "set sitevariables($name) {$value}\n";
631
	$sitevars{$name} = $value;
632 633 634
    }
    print TCL "\n";

635 636 637 638 639 640 641
    #
    # XXX Backward compat: we must ensure that certain sitevars exist in
    # the NS defs file as NS parser assumes they do.  If they don't exist,
    # we create them with the "traditional" values.
    #
    my %defvalues = (
	"elabinelab/singlenet" => 0,
642 643 644
	"elabinelab/boss_osid" => "FBSD83-STD",
	"elabinelab/ops_osid"  => "FBSD83-STD",
	"elabinelab/fs_osid"   => "FBSD83-STD"
645 646 647
    );
    while (my ($var, $def) = each(%defvalues)) {
	if (!exists($sitevars{$var})) {
648 649
	    ## don't be so alarmist
	    #print "*** WARNING: sitevar $var does not exist or has no value, defaulting to $def\n";
650 651 652 653
	    print TCL "set sitevariables($var) $def\n";
	    $sitevars{$var} = $def;
	}
    }
654

655 656 657
    if (defined($pid)) {
	print TCL "# OSIDs\n";
	$query_result =
658 659 660 661
	    DBQueryFatal("select distinct o.pid,o.osname from os_info as o ".
			 "left join os_info_versions as v on ".
			 "     v.osid=o.osid and v.vers=o.version ".
			 "where (v.shared=1 or o.pid='$pid')");
662
	while (my ($pid,$osname) = $query_result->fetchrow_array()) {
663
	    print TCL "set osids($osname) 1\n";
664
	    print TCL "set osids($pid/$osname) 1\n";
665 666
	}
	print TCL "\n";
667
	print TCL "# External OSIDs\n";
668

669 670 671
	if (defined($this_user)) {
	    my $uid_idx = $this_user->uid_idx();
	    $query_result =
672 673 674 675 676 677 678 679 680
		DBQueryFatal("SELECT distinct o.pid,o.osname from ".
			     "  os_info AS o ".
			     "left join os_info_versions as v on ".
			     "     v.osid=o.osid and v.vers=o.version ".
			     "left join image_permissions AS p on ".
			     "      p.imageid=o.osid and ".
			     "      p.permission_type='user' ".
			     "WHERE v.ezid!=0 ".
			     "  AND p.imageid is not null ".
681 682
			     "  AND p.permission_idx='$uid_idx' ".
			     "UNION DISTINCT ".
683 684 685 686 687 688 689 690 691 692 693 694
			     "SELECT distinct o.pid,o.osname from ".
			     "  os_info AS o ".
			     "left join os_info_versions as v on ".
			     "     v.osid=o.osid and v.vers=o.version ".
			     "left join image_permissions AS p on ".
			     "      p.imageid=o.osid and ".
			     "      p.permission_type='group' ".
			     "left join group_membership as g ".
			     "     on g.gid_idx=p.permission_idx ".
			     "WHERE v.ezid!=0 ".
			     "  AND p.imageid is not null ".
			     "  AND g.uid_idx='$uid_idx' ");
695 696 697 698 699
	    while (my ($pid,$osname) = $query_result->fetchrow_array()) {
		print TCL "set osids($pid/$osname) 1\n";
	    }
	    print TCL "\n";
	}
700 701
	print TCL "# subOSIDs and parent OSIDs (default parent first element)\n";
	$query_result =
David Johnson's avatar
David Johnson committed
702 703 704
	    DBQueryFatal("select oi.osname,oi3.osname," . 
			 "group_concat(oi2.osname separator '\" \"')" . 
			 " from os_submap as osm" . 
705 706 707
			 " left join os_info as oi on osm.osid=oi.osid" .
			 " left join os_info_versions as ov on ".
			 "      ov.osid=oi.osid and ov.vers=oi.version ".
708
			 " left join os_info as oi2 on osm.parent_osid=oi2.osid" . 
709 710 711 712 713 714
			 " left join os_info_versions as ov2 on ".
			 "      ov2.osid=oi2.osid and ov2.vers=oi2.version ".
			 " left join os_info as oi3 on ov.def_parentosid=oi3.osid" . 
			 " left join os_info_versions as ov3 on ".
			 "      ov3.osid=oi3.osid and ov3.vers=oi3.version ".
			 " where ov.def_parentosid is not NULL" . 
David Johnson's avatar
David Johnson committed
715
			 " group by oi.osname");
716 717 718 719 720 721 722 723 724 725
		     
	while (my ($osname,$def_parentosid,$parent_osids) = 
	       $query_result->fetchrow_array()) {
	    my $parentlist = "\"$def_parentosid\"";
	    if (defined($parent_osids) && $parent_osids ne '') {
		$parentlist .= " \"$parent_osids\"";
	    }
	    print TCL "set subosids($osname) [list $parentlist]\n";
	}
	print TCL "\n";
726 727
    }

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    if (defined($pid)) {
	# Load reserved nodes, for swapmodify.
	$query_result = 
	    DBQueryFatal("select r.vname,r.node_id,n.type from reserved as r ".
			 "left join nodes as n on n.node_id=r.node_id ".
			 "where r.pid='$pid' and r.eid='$eid'");

	print TCL "# Reserved Nodes\n";
	while (($vname,$reserved,$type) = $query_result->fetchrow_array()) {
	    print TCL "lappend reserved_list \"$vname\"\n";
	    print TCL "set reserved_type($vname) \"$type\"\n";
	    print TCL "set reserved_node($vname) \"$reserved\"\n";
	}
    }

743 744 745 746 747 748 749 750 751 752 753
    print TCL "# Physical Node Names\n";
    $query_result =
	DBQueryFatal("select n.node_id,nt.type from nodes as n ".
		     "left join node_types as nt on n.type=nt.type ".
		     "where n.node_id=n.phys_nodeid and nt.isremotenode=0 ".
		     "and n.role='testnode' and nt.type!='dnard'");

    while (($node_id,$type) = $query_result->fetchrow_array()) {
	print TCL "set physnodes($node_id) \"$type\"\n";
    }

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    print TCL "# Client side service names that can be controlled, and when\n";
    $query_result =
	DBQueryFatal("select idx,service,env,whence from client_services");

    while (my ($idx,$service,$env,$whence) = $query_result->fetchrow_array()) {
	print TCL "set servicenames(\"${service}:${env}:${whence}\") \"$idx\"\n";
    }
    print TCL "# Client side service control points: whence and env\n";
    $query_result =
	DBQueryFatal("select service," . 
		     " group_concat(concat_ws(' ',whence,env) separator ', ')" .
		     " from client_services group by service");
    while (my ($service,$points) = $query_result->fetchrow_array()) {
	print TCL "set servicepoints($service) \"$points\"\n";
    }

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    print TCL "# Location info\n";
    $query_result =
	DBQueryFatal("select li.node_id,li.building,li.loc_x,li.loc_y,".
		     "li.loc_z,fi.pixels_per_meter ".
		     "from location_info as li ".
		     "left join floorimages as fi on fi.building=li.building");

    while (my ($node_id,$building,$loc_x,$loc_y,$loc_z,$ppm) =
	   $query_result->fetchrow_array()) {
	print TCL "set location_info($node_id,$building,x) ". 
	    $loc_x / $ppm ."\n";
	print TCL "set location_info($node_id,$building,y) ". 
	    $loc_y / $ppm ."\n";
	if (!defined($loc_z)) {
	    $loc_z = 0.0;
	}
	print TCL "set location_info($node_id,$building,z) ". 
	    $loc_z / $ppm ."\n";
    }

790
    #
791 792 793 794 795 796 797
    # Defaults for ElabInElab settings.
    # System-wide defaults that come from sitevariables integrated above.
    # However, for compatibility, we want existing experiments to retain
    # their current settings for some of these, unless explicitly overridden
    # via NS commands.  So here we initialize elabinelab variables based on
    # existing values, so that the sitevar values won't get used later.
    # These values can still be overridden by explicit settings in the NS file.
798
    # 
799
    if (defined($experiment) && $experiment->elabinelab()) {
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
	# dig out existing OSIDs for the boss/ops/fs nodes
	$query_result =
	    DBQueryFatal("select inner_elab_role,osname from virt_nodes ".
			 " where inner_elab_role!='node' and ".
			 " pid='$pid' and eid='$eid'");
	while (my ($role,$os) = $query_result->fetchrow_array()) {
	    if ($role =~ /^boss/) {
		print TCL "set ::TBCOMPAT::elabinelab_nodeos('boss') $os\n";
		next;
	    }
	    if ($role =~ /^ops/) {
		print TCL "set ::TBCOMPAT::elabinelab_nodeos('ops') $os\n";
		if ($role eq "ops+fs") {
		    print TCL "set ::TBCOMPAT::elabinelab_nodeos('fs') $os\n";
		}
		next;
	    }
	    if ($role =~ /^fs/) {
		print TCL "set ::TBCOMPAT::elabinelab_nodeos('fs') $os\n";
		next;
	    }
	}
    }

    #
    # XXX elabinelab_singlenet must always have a value.
    # This really isn't the place to do this, but I don't want to
    # mess with the TCL code...
    #
    my $singlenet = $sitevars{"elabinelab/singlenet"};
    if (defined($experiment) && $experiment->elabinelab()) {
831
	$singlenet = $experiment->elabinelab_singlenet();
832
    }
833
    print TCL "set ::GLOBALS::elabinelab_singlenet $singlenet\n";
834

835 836 837 838 839 840 841
    #
    # Another ElabinElab setting.
    # This looks much like the compat hack above, but is for a completely
    # different reason.  If an inner-elab has an inner-experiment, the
    # NS file is re-parsed to pick up additional info.
    #
    my $maxnodes = 0;
842 843 844
    if (defined($experiment) && $experiment->elabinelab() &&
	defined($experiment->maximum_nodes())) {
	# The DB default is null.
845 846 847 848
	$maxnodes = $experiment->maximum_nodes();
    }
    print TCL "set elabinelab_maxpcs $maxnodes\n\n";

849 850 851
    #
    # For Templates.
    #
852 853
    print TCL "# Template goo\n";
    # Does not matter what it is, as long as it is set.
854
    print TCL "set ::DATASTORE \"" . PROJROOT() . "\"\n";
855 856 857 858
    
    if (defined($experiment)) {
	my $instance =
	    Template::Instance->LookupByID($experiment->instance_idx());
859
	
860
	if (defined($instance)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
861
	    my $datastore = $instance->path() . "/datastore";
862
	    my %parameters;
863

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
	    print TCL "set ::DATASTORE \"$datastore\"\n";

	    $instance->BindingList(\%parameters) == 0
		or tbdie("Could not get binding list for $instance");
		
	    foreach my $name (keys(%parameters)) {
		my $value = $parameters{$name};

		print TCL "set parameter_list_defaults($name) \"$value\"\n";
	    }
	    
	    $instance->RunBindingList(\%parameters) == 0
		or tbdie("Could not get run binding list for $instance");
		
	    foreach my $name (keys(%parameters)) {
		my $value = $parameters{$name};
880

881 882
		print TCL "set parameter_list_defaults($name) \"$value\"\n";
	    }
883 884
	}
    }
Kirk Webb's avatar
Kirk Webb committed
885
    print TCL "\n";
886

887 888 889 890 891 892 893 894 895
    #
    # XXX for now, all available datasets (leases) are those in the
    # same project as the experiment.
    #
    if (defined($experiment)) {
	my $pid = $experiment->pid();
	my @leases = Lease->AllProjectLeases($pid);
	print TCL "# Available datasets\n";
	foreach my $lease (@leases) {
896 897
	    my $ro;

Mike Hibler's avatar
Mike Hibler committed
898
	    #
899
	    # Lease must be valid (RW) or grace (RO).
Mike Hibler's avatar
Mike Hibler committed
900
	    #
901 902 903 904 905 906 907
	    if ($lease->state() eq LEASE_STATE_VALID()) {
		$ro = 0;
	    } elsif ($lease->state() eq LEASE_STATE_GRACE()) {
		$ro = 1;
	    } else {
		next;
	    }
Mike Hibler's avatar
Mike Hibler committed
908

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
	    # must have associated blockstore
	    my $idx = $lease->lease_idx();
	    my $bstore = Blockstore->LookupByLease($idx);
	    next if (!$bstore);

	    my $name = "$pid/" . $lease->lease_id();
	    my $type = $lease->type();
	    my $node = $bstore->node_id();
	    my $bsid = $bstore->bs_id();
	    my $size = $bstore->total_size();

	    print TCL "set dataset_node($name) $node\n";
	    print TCL "set dataset_bsid($name) $bsid\n";
	    print TCL "set dataset_type($name) $type\n";
	    print TCL "set dataset_size($name) $size\n";
	    print TCL "set dataset_index($name) $idx\n";
925
	    print TCL "set dataset_readonly($name) $ro\n";
926 927 928 929
	}
	print TCL "\n";
    }

930 931 932 933 934 935 936 937 938 939 940 941 942
    print TCL "# Storage Objects\n";
    my @sotypes = BlockstoreType->AllTypes();
    foreach my $sot (@sotypes) {
	my $type  = $sot->type();
	my $cl    = $sot->class();
	my $proto = $sot->protocol();
	print TCL "set sotypes($type) 1\n"
	    if defined($type);
	print TCL "set soclasses($cl) 1\n"
	    if defined($cl);
	print TCL "set soprotocols($proto) 1\n"
	    if defined($proto);
    }
Kirk Webb's avatar
Kirk Webb committed
943
    print TCL "\n";
944

Kirk Webb's avatar
Kirk Webb committed
945
    print TCL "}\n\n";
946
    close(TCL);
947
}
948 949 950 951 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 992 993 994 995

sub parse_error($) {
    my ($mesg) = @_;

    return if parse_invalid_os_error($mesg);
    return if parse_invalid_variable_error($mesg);

    return;
}

sub parse_invalid_os_error($) {
    my ($mesg) = @_;
    my ($type, $osname);

    if ($mesg =~ /^\[tb-set-(\w+)-os\] Invalid osid (\S+)\.$/) {
	($type, $osname) = ($1, $2);
    } else {
	return false;
    }

    tbreport(SEV_ADDITIONAL, {script => 'parse.tcl'}, 'invalid_os',
	     $type, $osname, undef);

    return true;
}

sub parse_invalid_variable_error($) {
    my ($mesg) = @_;
    my ($type, $var);

    if ($mesg =~ /^\[tb-set-hardware\] Invalid hardware type (\S+)\.$/) {
	$var  = $1;
	$type = 'hardware_type';
    } elsif ($mesg =~ /^\[run\] Invalid lan\/link name (\S+)\./) {
	$var  = $1;
	$type = 'lan_link_name';
    } elsif ($mesg =~ /^\[run\] Invalid node name (\S+)\./) {
	$var  = $1;
	$type = 'node_name';
    } else {
	return false;
    }

    tbreport(SEV_ADDITIONAL, {script => 'parse.tcl'}, 'invalid_variable',
	     $type, $var);

    return true;
}