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

#
4
# Copyright (c) 2000-2016 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;
Kevin Atkinson's avatar
 
Kevin Atkinson committed
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  = "nqapcr";
49
my $anonmode = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
50
my $passmode = 0;
51
my $impotent = 0;
52
my $rspecmode= 0;
53
my $debug    = 0;
54
my $catout   = 0;
55 56 57 58 59 60

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

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

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

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

87 88 89 90 91 92
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.
93
    die("Must be root! Maybe its a development version?");
94 95 96 97 98
}

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

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

119 120 121 122 123
use constant false => 0;
use constant true  => 1;

sub parse_error($);

124
#
125 126
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
127
#
128 129 130 131 132 133 134 135 136 137
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"a"})) {
    $anonmode = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
138 139 140
if (defined($options{"p"})) {
    $passmode = 1;
}
141 142 143
if (defined($options{"c"})) {
    $catout = 1;
}
144 145
if (defined($options{"r"})) {
    $rspecmode = 1;
146 147 148 149 150
}
if (@ARGV == 1) {
    $nsfile = $ARGV[0];
}
else {
151 152 153 154 155 156
    $pid   = shift(@ARGV);
    $gid   = shift(@ARGV);
    if (@ARGV == 2) {
	$eid  = shift(@ARGV);
    }
    $nsfile= shift(@ARGV);
157 158 159
}

#
160
# Must taint check!
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 ($gid =~ /^([-\w]+)$/) {
	$gid = $1;
    }
    else {
	die("Bad data in argument: $gid.");
    }
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    if (defined($eid)) {
	if ($eid =~ /^([-\w]+)$/) {
	    $eid = $1;
	}
	else {
	    die("Bad data in argument: $eid.");
	}
	$experiment = Experiment->Lookup($pid, $eid);
	if (! defined($experiment)) {
	    tbdie("Cannot find the experiment object for $pid/$eid");
	}
	$exptidx = $experiment->idx();
    }
    else {
	$eid = "ignore";
198
    }
199 200 201 202 203 204 205 206 207 208 209
}

# 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.
    #
210 211 212
    $this_user = User->ThisUser();
    if (! defined($this_user)) {
	tbdie("You ($UID) do not exist!");
213
    }
214

215 216
    # Run as the user for most of this script.
    $EUID = $UID;
217 218
}

219
# Create the defs files.
220
sub GenDefsFile($);
221 222 223 224 225 226
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");

227 228 229 230 231
#
# Touch the output file, to avoid a root owned, 644 file. 
#
if (-e $outfile) {
    unlink($outfile) or
Kevin Atkinson's avatar
 
Kevin Atkinson committed
232
	tbdie("Could not unlink $outfile");
233 234
}
system("touch $outfile") == 0 or
Kevin Atkinson's avatar
 
Kevin Atkinson committed
235
    tbdie("Could not create $outfile");
236

237
#
238 239 240
# 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.
241
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
242
my $cmdargs = "$TB/libexec/ns2ir/parse.proxy ";
243 244
$cmdargs .= " -u " . $this_user->uid() . " "
    if (defined($this_user));
Timothy Stack's avatar
 
Timothy Stack committed
245
$cmdargs .= " -- ";
246
$cmdargs .= " -a"
Leigh B. Stoller's avatar
Leigh B. Stoller committed
247
    if ($anonmode);
248 249 250 251
$cmdargs .= " -n"
    if (defined($options{"n"}));
$cmdargs .= " -q"
    if (defined($options{"q"}));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
252 253
$cmdargs .= " -p"
    if ($passmode);
254 255
$cmdargs .= " -r"
    if ($rspecmode);
256 257
$cmdargs .= " $pid $gid $eid"
    if (!$anonmode);
258 259

#
260
# Run parser, redirecting stdout to a file to capture the parser results.
Kevin Atkinson's avatar
 
Kevin Atkinson committed
261
# Stderr is redirected to the ERR filehandle
262
# Must flip to real root to run ssh.
263
#
264
if ($TESTMODE) {
265
    #
266 267
    # In testmode, no ssh. Just run locally.
    #
Kevin Atkinson's avatar
 
Kevin Atkinson committed
268
    open ERR, "$cmdargs < $infile 2>&1 >> $outfile |";
269 270
}
else {
271
    #
272 273 274 275
    # In non-testmode, must flip to real root for the ssh, and then flip
    # back afterwards.
    # 
    $EUID = $UID = 0;
Kevin Atkinson's avatar
 
Kevin Atkinson committed
276
    open ERR, "sshtb -host $CONTROL $cmdargs < $infile 2>&1 >> $outfile |";
277 278 279
    $EUID = $UID = $SAVEUID;
}

Kevin Atkinson's avatar
 
Kevin Atkinson committed
280 281 282 283 284 285
#
# 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.
#
286
my $errs;
Kevin Atkinson's avatar
 
Kevin Atkinson committed
287 288 289 290 291 292 293 294 295
{
    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);
Kevin Atkinson's avatar
 
Kevin Atkinson committed
296
    tblog_set_default_cause('user');
Kevin Atkinson's avatar
 
Kevin Atkinson committed
297 298 299 300 301 302

    my $err = '';
    
    # assume any output indicates an error
    while (<ERR>) {
	print SERR $_;
303
	$errs .= $_;
Kevin Atkinson's avatar
 
Kevin Atkinson committed
304
	if (/^\s*\*\*\*\s*(.+)/) {
305
	    parse_error($err);
Kevin Atkinson's avatar
 
Kevin Atkinson committed
306 307 308 309 310 311 312 313
	    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+$//;
314
	    parse_error($_);
Kevin Atkinson's avatar
 
Kevin Atkinson committed
315 316 317 318 319 320
	    dblog(TBLOG_ERR, {}, $_) if $_;
	    $err = '';
	} else {
	    $err .= $_;
	}
    }
321
    parse_error($err);
Kevin Atkinson's avatar
 
Kevin Atkinson committed
322 323 324 325 326 327
    dblog(TBLOG_ERR, {}, $err) if $err;

    tblog_exit();
}
close ERR;

328
if ($?) {
329
    my $exit_status = $?;
330
    
331
    if (WIFSIGNALED($exit_status)) {
332 333 334 335 336 337 338 339 340 341
	# 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{$_}] ||= $_}

342
	my $signal  = WTERMSIG($exit_status);
343 344 345 346 347 348 349 350 351 352
	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);
	}
    }
    
353 354 355
    tbdie({cause => 'user', type => 'extra', severity => SEV_ERROR,
	   error => ['ns_parse_failed']},
	  "Parsing failed (error code $exit_status)!");
356
}
357 358 359 360 361 362 363 364
if ($catout) {
    system("/bin/cat $outfile");
}
if ($impotent) {
    unlink($infile);
    unlink($outfile);
    exit(0);
}
365 366 367 368

#
# Run the XML converter on the output. 
#
369
system("$TB/libexec/xmlconvert -p -x $outfile $pid $eid");
370 371 372 373

if ($?) {
    my $exit_status = $? >> 8;
    
374 375 376
    tbdie({type => 'primary', severity => SEV_ERROR,
	   error => ['xml_converter_failed']},
	  "XML converter exited with error code $exit_status!\n");
377 378 379 380 381
}

#
# 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
382 383
# that.

384
my %subnetmap = ();
385
my $WANETMASK = "255.255.255.248";
386 387 388 389 390 391 392 393 394 395 396 397

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+)/);

398
	if ($a eq "69" && $b eq "69") {
399 400 401
	    my $net = inet_ntoa(inet_aton($WANETMASK) & inet_aton($ip));
		
	    if (! defined($subnetmap{$net})) {
402 403
		DBQueryFatal("insert into ipsubnets (exptidx,pid,eid,idx) ".
			     "values ('$exptidx','$pid','$eid', NULL)");
404 405 406 407
		my ($id) =
		    DBQueryFatal("select LAST_INSERT_ID() ".
				 "from ipsubnets")->fetchrow_array();

408 409 410 411 412 413 414 415 416 417
		# 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");
418
	    }
419 420
	    my $newsubnet = inet_ntoa($subnetmap{$net} | inet_aton("$d"));
	    push(@newiplist, "$port:${newsubnet}");
421 422 423 424
	}
	else {
	    push(@newiplist, $ipinfo);
	}
425
    }
426 427 428 429 430
    $newips = join(" ", @newiplist);
    
    if ($newips ne $ips) {
	DBQueryFatal("update virt_nodes set ips='$newips' ".
		     "where vname='$vname' and pid='$pid' and eid='$eid'");
431 432 433 434 435 436 437 438
	
	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'");
	}
439 440 441 442 443 444 445 446 447 448 449 450 451 452
    }
}
#
# 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;
453
	my $net		 = inet_ntoa(inet_aton($WANETMASK) & inet_aton($ip));
454
	
455 456
	if (defined($subnetmap{$net})) {
	    $newip = inet_ntoa($subnetmap{$net} | inet_aton("$d"));
457 458
	}
	($a,$b,$c,$d) = ($dstip =~ /(\d+).(\d+).(\d+).(\d+)/);
459 460 461
	$net          = inet_ntoa(inet_aton($WANETMASK) & inet_aton($dstip));
	if (defined($subnetmap{$net})) {
	    $newdstip = inet_ntoa($subnetmap{$net} | inet_aton("$d"));
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
	}
	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";
501 502 503 504 505 506 507 508 509

    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";
 
510 511 512 513 514 515 516 517 518 519
    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();

520
	print TCL "set hwtypes($type) 1\n";
Timothy Stack's avatar
 
Timothy Stack committed
521
	print TCL "set hwtype_class($type) $class\n";
522 523
	print TCL "set isremote($type) $isrem\n";
	print TCL "set isvirt($type) $isvirt\n";
524 525 526 527
	print TCL "set issubnode($type) $issub\n";

	# Since there are multiple types per class, this is probably not
	# the right thing to do.
528 529 530
	print TCL "set hwtypes($class) 1\n";
	print TCL "set isremote($class) $isrem\n";
	print TCL "set isvirt($class) $isvirt\n";
531 532 533
	print TCL "set issubnode($class) $issub\n";

	if (defined($osid) && $osid ne "") {
534 535 536 537
	    my $osinfo = OSinfo->Lookup($osid);
	    if (defined($osinfo)) {
		my $osname = $osinfo->osname();
		print TCL "set default_osids($type) \"$osname\"\n"
538 539
	    }
	}
540 541
    }
    print TCL "\n";
542
    
543
    print TCL "# Node Aux Types\n";
544 545 546 547 548 549 550 551
    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();

552 553 554
	print TCL "set hwtypes($type) 1\n";
	print TCL "set isremote($type) $isrem\n";
	print TCL "set isvirt($type) $isvirt\n";
555 556 557
	print TCL "set issubnode($type) $issub\n";

	if (defined($osid) && $osid ne "") {
558 559 560 561
	    my $osinfo = OSinfo->Lookup($osid);
	    if (defined($osinfo)) {
		my $osname = $osinfo->osname();
		print TCL "set default_osids($type) \"$osname\"\n"
562 563
	    }
	}
564 565
    }
    print TCL "\n";
566 567 568 569 570 571 572 573 574 575

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

576
    
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    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";

Timothy Stack's avatar
 
Timothy Stack committed
594 595
    print TCL "# Robot areas\n";
    $query_result =
Timothy Stack's avatar
 
Timothy Stack committed
596
	DBQueryFatal("select distinct building from node_startloc");
Timothy Stack's avatar
 
Timothy Stack committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    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";

Timothy Stack's avatar
 
Timothy Stack committed
618 619 620 621 622 623 624 625 626 627 628 629
    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";

630
    print TCL "# Site variables\n";
631
    my %sitevars = ();
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    $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";
649
	$sitevars{$name} = $value;
650 651 652
    }
    print TCL "\n";

653 654 655 656 657 658 659
    #
    # 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,
660 661 662
	"elabinelab/boss_osid" => "FBSD83-STD",
	"elabinelab/ops_osid"  => "FBSD83-STD",
	"elabinelab/fs_osid"   => "FBSD83-STD"
663 664 665
    );
    while (my ($var, $def) = each(%defvalues)) {
	if (!exists($sitevars{$var})) {
666 667
	    ## don't be so alarmist
	    #print "*** WARNING: sitevar $var does not exist or has no value, defaulting to $def\n";
668 669 670 671
	    print TCL "set sitevariables($var) $def\n";
	    $sitevars{$var} = $def;
	}
    }
672

673 674 675
    if (defined($pid)) {
	print TCL "# OSIDs\n";
	$query_result =
676 677 678 679
	    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')");
680
	while (my ($pid,$osname) = $query_result->fetchrow_array()) {
681
	    print TCL "set osids($osname) 1\n";
682
	    print TCL "set osids($pid/$osname) 1\n";
683 684
	}
	print TCL "\n";
685
	print TCL "# External OSIDs\n";
686

687 688 689
	if (defined($this_user)) {
	    my $uid_idx = $this_user->uid_idx();
	    $query_result =
690 691 692 693 694 695 696 697 698
		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 ".
699 700
			     "  AND p.permission_idx='$uid_idx' ".
			     "UNION DISTINCT ".
701 702 703 704 705 706 707 708 709 710 711 712
			     "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' ");
713 714 715 716 717
	    while (my ($pid,$osname) = $query_result->fetchrow_array()) {
		print TCL "set osids($pid/$osname) 1\n";
	    }
	    print TCL "\n";
	}
718 719
	print TCL "# subOSIDs and parent OSIDs (default parent first element)\n";
	$query_result =
720
	    DBQueryFatal("select oi.pid,oi.osname,oi3.osname," . 
David Johnson's avatar
David Johnson committed
721 722
			 "group_concat(oi2.osname separator '\" \"')" . 
			 " from os_submap as osm" . 
723 724 725
			 " 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 ".
726
			 " left join os_info as oi2 on osm.parent_osid=oi2.osid" . 
727 728 729 730 731 732
			 " 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
733
			 " group by oi.osname");
734
		     
735
	while (my ($pid,$osname,$def_parentosid,$parent_osids) = 
736 737 738 739 740 741
	       $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";
742
	    print TCL "set subosids($pid/$osname) \$subosids($osname)\n";
743 744
	}
	print TCL "\n";
745 746
    }

747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    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";
	}
    }

762 763 764 765 766 767 768 769 770 771 772
    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";
    }

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    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";
    }

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    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";
    }

809
    #
810 811 812 813 814 815 816
    # 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.
817
    # 
818
    if (defined($experiment) && $experiment->elabinelab()) {
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
	# 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()) {
850
	$singlenet = $experiment->elabinelab_singlenet();
851
    }
852
    print TCL "set ::GLOBALS::elabinelab_singlenet $singlenet\n";
853

854 855 856 857 858 859 860
    #
    # 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;
861 862 863
    if (defined($experiment) && $experiment->elabinelab() &&
	defined($experiment->maximum_nodes())) {
	# The DB default is null.
864 865 866 867
	$maxnodes = $experiment->maximum_nodes();
    }
    print TCL "set elabinelab_maxpcs $maxnodes\n\n";

868 869 870
    #
    # For Templates.
    #
871 872
    print TCL "# Template goo\n";
    # Does not matter what it is, as long as it is set.
873
    print TCL "set ::DATASTORE \"" . PROJROOT() . "\"\n";
874 875 876 877
    
    if (defined($experiment)) {
	my $instance =
	    Template::Instance->LookupByID($experiment->instance_idx());
878
	
879
	if (defined($instance)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
880
	    my $datastore = $instance->path() . "/datastore";
881
	    my %parameters;
882

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
	    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};
899

900 901
		print TCL "set parameter_list_defaults($name) \"$value\"\n";
	    }
902 903
	}
    }
Kirk Webb's avatar
Kirk Webb committed
904
    print TCL "\n";
905

906
    #
907 908 909
    # Grab all leases this user has access to.  Mark appropriately as RO/RW,
    # depending on privileges and whether or not the lease is currently in
    # use (and how it is being used).
910
    #
911 912
    if (defined($this_user)) {
	my @leases = Lease->AllowedLeases($this_user);
913 914
	print TCL "# Available datasets\n";
	foreach my $lease (@leases) {
915 916
	    my $ro;

Mike Hibler's avatar
Mike Hibler committed
917
	    #
918
	    # Lease must be valid (RW) or grace (RO).
Mike Hibler's avatar
Mike Hibler committed
919
	    #
920
	    if ($lease->state() eq LEASE_STATE_VALID()) {
921
		# Force RO if user does not have RW privs.
922
		$ro = $lease->allow_modify() ? 0 : 1;
923 924 925 926 927
	    } elsif ($lease->state() eq LEASE_STATE_GRACE()) {
		$ro = 1;
	    } else {
		next;
	    }
Mike Hibler's avatar
Mike Hibler committed
928

929 930 931 932 933
	    # must have associated blockstore
	    my $idx = $lease->lease_idx();
	    my $bstore = Blockstore->LookupByLease($idx);
	    next if (!$bstore);

934
	    my $name = $lease->pid() ."/". $lease->lease_id();
935 936 937 938 939 940 941 942 943 944
	    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";
945
	    print TCL "set dataset_readonly($name) $ro\n";
946 947 948 949
	}
	print TCL "\n";
    }

950 951 952 953 954 955 956 957 958 959 960 961 962
    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
963
    print TCL "\n";
964

Kirk Webb's avatar
Kirk Webb committed
965
    print TCL "}\n\n";
966
    close(TCL);
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 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

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