template_swapin.in 13.4 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2006, 2007 University of Utah and the Flux Group.
5 6 7
# All rights reserved.
#
use English;
8
use strict;
9
use Getopt::Std;
10
use POSIX qw(setsid);
11 12 13 14 15 16
use POSIX qw(strftime);
use Errno qw(EDQUOT);
use XML::Simple;
use Data::Dumper;

#
17
# Swapin a previously instantiated template.
18 19 20 21 22 23 24 25 26 27 28 29 30
#
# Exit codes are important; they tell the web page what has happened so
# it can say something useful to the user. Fatal errors are mostly done
# with die(), but expected errors use this routine. At some point we will
# use the DB to communicate the actual error.
#
# $status < 0 - Fatal error. Something went wrong we did not expect.
# $status = 0 - Everything okay.
# $status > 0 - Expected error. User not allowed for some reason. 
# 
sub usage()
{
    print(STDERR
31
	  "Usage: template_swapin [-q] [-w] -e <eid> <guid/vers>\n".
32 33 34 35 36 37 38
	  "switches and arguments:\n".
	  "-w       - wait for template to be instantiated\n".
	  "-q       - be less chatty\n".
	  "-e <eid> - The instance name (unique, alphanumeric, no blanks)\n".
	  "<guid/vers> - GUID and version to swapin\n");
    exit(-1);
}
39
my $optlist	 = "qwe:f";
40 41 42 43 44 45
my %options      = ();
my $quiet        = 0;
my $waitmode     = 0;
my $foreground   = 0;
my $guid;
my $version;
46
my $eid;
47 48 49 50 51 52 53 54 55 56 57

#
# Configure variables
#
my $TB		= "@prefix@";
my $EVENTSYS	= @EVENTSYS@;
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
my $TBDOCBASE	= "@TBDOCBASE@";
my $TBBASE	= "@TBBASE@";
my $CONTROL	= "@USERNODE@";
58
my $BOSSNODE    = "@BOSSNODE@";
59
my $OPSDBSUPPORT= @OPSDBSUPPORT@;
60 61

# Locals
62
my $EVhandle;
63 64
my $template;
my $instance;
65 66 67
my $experiment;
my %parameters;
my $pid;
68
my $run;
69
my $logname;
70
my $template_tag;
71
my @ExptStates  = ();
72 73 74 75 76 77 78 79 80 81
# For the END block below.
my $cleaning    = 0;
my $exptcreated = 0;
my $justexit    = 1;

# Programs we need
my $checkquota  = "$TB/sbin/checkquota";
my $batchexp    = "$TB/bin/batchexp";
my $swapexp     = "$TB/bin/swapexp";
my $endexp      = "$TB/bin/endexp";
82
my $dbcontrol   = "$TB/sbin/opsdb_control";
83
my $archcontrol = "$TB/bin/archive_control";
84 85 86 87 88

# Protos
sub ParseArgs();
sub fatal($$);
sub sighandler($);
89
sub SetupEventHandler();
90 91 92 93 94 95 96 97

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
98
use User;
99
use Template;
100
use Experiment;
101
use event;
102
use libaudit;
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

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

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

#
# Set umask for start/swap. We want other members in the project to be
# able to swap/end experiments, so the log and intermediate files need
# to be 664 since some are opened for append.
#
umask(0002);

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

#
# Verify user and get his DB uid.
#
129 130 131
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
132
}
133 134 135
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
my $user_uid   = $this_user->uid();
136 137 138 139 140

#
# Before doing anything else, check for overquota ... lets not waste
# our time. Make sure user sees the error by exiting with 1.
#
141
if (system("$checkquota $user_uid") != 0) {
142 143
    tberror("You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    exit(1);
}

# Now parse arguments.
ParseArgs();

#
# In wait mode, block SIGINT until we spin off the background process.
#
if ($waitmode) {
    $SIG{QUIT} = 'IGNORE';
    $SIG{TERM} = 'IGNORE';
    $SIG{INT}  = 'IGNORE';
}

#
160
# Grab template and do access check.
161
#
162
$template = Template->Lookup($guid, $version);
163

164 165 166
if (!defined($template)) {
    tbdie("Experiment template $guid/$version does not exist!");
}
167
if (! TBProjAccessCheck($user_uid,
168 169
			$template->pid(), $template->gid(),
			TB_PROJECT_CREATEEXPT)) {
170 171 172 173
    tberror("You do not have permission to instantiate template ".
	    "$guid/$version");
    exit(1);
}
174
$pid = $template->pid();
175

176
#
177
# Grab instance; better exist since this is a swapin of an instance!
178
#
179 180 181
# We need to find the experiment so we can find the instance.
# This is wrong, but necessary cause of how templates are layered over
# the existing experiment structure.
182
#
183 184 185
$experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    tbdie("Experiment $pid/$eid does not exist!");
186 187
}

188
$instance = Template::Instance->LookupByExptidx($experiment->idx());
189
if (!defined($instance)) {
190
    tbdie("Could not get instance record for experiment $pid/$eid!");
191 192
}

193 194 195
# Need these for default run below.
$instance->BindingList(\%parameters) == 0
    or fatal(-1, "Error getting bindings from $instance!");
196

197 198 199 200 201 202 203 204 205
#
# Go to the background now so we have a proper log of what happened.
#
#
$SIG{TERM} = \&sighandler;

#
# Use the logonly option to audit so that we get a record mailed.
#
206 207 208 209 210 211 212 213
if (! ($foreground || $experiment->batchmode())) {
    # Cleanup
    $experiment->CleanLogFiles() == 0
	or fatal(-1, "Could not clean up logfiles!");
    
    $logname = TBExptCreateLogFile($pid, $eid, "swapin");
    TBExptSetLogFile($pid, $eid, $logname);
    TBExptOpenLogFile($pid, $eid);
214 215

    if (my $childpid = AuditStart(LIBAUDIT_DAEMON, $logname,
216
				  LIBAUDIT_LOGONLY|LIBAUDIT_NODELETE|LIBAUDIT_FANCY)) {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
	#
	# Parent exits normally, unless in waitmode. We have to set
	# justexit to make sure the END block below does not run.
	#
	$justexit = 1;

	if (!$waitmode) {
	    #
	    # Before we can actually exit, we need to wait. Totally ick;
	    # the logfile stuff needs work.
	    #
	    while (1) {
		my ($tmp1, $tmp2);

		last
		    if (TBExptGetLogFile($pid, $eid, \$tmp1, \$tmp2));

		sleep(2);
	    }
236
	    if ($experiment->batchmode()) {
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
		print("Experiment $pid/$eid has entered the batch system.\n".
		      "You will be notified when it is fully instantiated.\n")
		    if (! $quiet);
	    }
	    else {
		print("Experiment $pid/$eid is now being instantiated.\n".
		      "You will be notified via email when this is done.\n")
		    if (! $quiet);
	    }
	    exit(0);
	}
	print("Waiting for experiment $eid to fully instantiate.\n")
	    if (! $quiet);
	    
	if (-t STDIN && !$quiet) {
	    print("You may type ^C at anytime; you will be notified via ".
		  "email.\n".
		  "You will not actually interrupt the instantiation.\n");
	}
	
	# Give child a chance to run.
	select(undef, undef, undef, 0.25);
	
	#
	# Reset signal handlers. User can now kill this process, without
	# stopping the child.
	#
	$SIG{TERM} = 'DEFAULT';
	$SIG{INT}  = 'DEFAULT';
	$SIG{QUIT} = 'DEFAULT';

	#
	# Wait until child exits or until user gets bored and types ^C.
	#
	waitpid($childpid, 0);
	
	print("Done. Exited with status: $?\n")
	    if (! $quiet);
	exit($? >> 8);
    }
    TBdbfork();
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

    # Add audit info.  Right now this will only work when called in
    # the child of the script being audited.  Eventually these can be
    # set anywhere.
    AddAuditInfo("which", "$pid/$eid");
    AddAuditInfo("failure_frag", "T. Swapin Failure");
    AddAuditInfo("success_frag", "T. Swapped In");

    my $expt_head_login = $experiment->creator();
    my $expt_head_name;
    my $expt_head_email;
    if (UserDBInfo($expt_head_login, \$expt_head_name, \$expt_head_email)) {
	AddAuditInfo("cc", "$expt_head_name <$expt_head_email>");
    } else {
	tbwarn("Could not determine name/email for $expt_head_login.");
    }
294 295
}

296 297 298
# Event connect before starting swapin so we catch all the states.
SetupEventHandler()
    if ($experiment->batchmode());
299

300
#
301
# Now do the swapin (or it gets queued if a batch experiment).
302
#
303
my @arguments = ($swapexp, "-q", "-x", "-s", "in", $pid, $eid);
304 305 306 307 308

system(@arguments);
fatal($? >> 8, "Could not instantiate the experiment")
    if ($?);

309 310 311 312 313 314
#
# At this point, we need to force a cleanup no matter how we exit.
# See the END block below.
#
$justexit = 0;

315 316 317 318
#
# We will spew forth info to the user each time the batch daemon tries to
# swap it in. 
#
319
if ($experiment->batchmode()) {
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
    #
    # Spin waiting for the state to change in swapexp. We are waiting for
    # it to swapin or go back to swapped.
    #
    my $queued = 0;
    
    while (1) {
	@ExptStates = ();
	event_poll_blocking($EVhandle, 500);

	next
	    if (! @ExptStates);

	foreach my $state (@ExptStates) {
	    print "$state\n";
	    
	    if ($state eq EXPTSTATE_ACTIVATING()) {
		print "Experiment is starting a swapin attempt ...\n";
	    }
	    elsif ($state eq EXPTSTATE_ACTIVE()) {
		print "Experiment swapped in!\n";
		goto done;
	    }
	    elsif ($state eq EXPTSTATE_QUEUED()) {
		# Failed to swapin; still queued in the batch system.
		if (! $queued) {
		    print "Experiment has entered the batch system\n";
		    $queued = 1;
		}
		else {
		    print "Experiment swapin attempt failed.\n";
		}
	    }
	    elsif ($state eq EXPTSTATE_SWAPPED()) {
		# Dumped out of the batch system for some reason.
355
		print "Experiment has been removed from the batch queue.\n";
356 357 358 359 360 361 362 363 364 365 366

		#
		# We are done; remove record of this attempt and exit.
		#
		fatal(1, "Experiment has been removed from the batch queue");
	    }
	}
    }
  done:
}

367 368 369 370
#
# Lets commit the experiment archive now that it is active. The experiment is
# already running, but thats not a big deal.
#
371
system("$archcontrol -t swapin commit $pid $eid");
372 373 374 375
if ($?) {
    fatal(-1, "Could not commit archive!");
}

376
#
377
# All instances currently start with a default run.
378
#
379
$run = $instance->NewRun($eid, $this_user, $instance->description());
380 381 382
if (!defined($run)) {
    fatal(-1, "Could not create new experiment run for $instance!");
}
383

384 385 386 387 388 389 390 391 392 393
#
# And create a tag (and subdir) for this run. This is primarily a convenience
# function for the web interface. The tag is simply an alias to the current
# trunk and does not cause a savepoint or a commit.
#
system("$archcontrol -u -s runs/$eid tag $pid $eid startrun");
if ($?) {
    fatal(-1, "Could not commit archive!");
}

394 395 396
#
# And the bindings for the default run ...
#
397 398
foreach my $name (keys(%parameters)) {
    my $value = $parameters{$name};
399

400 401
    $instance->NewRunBinding($name, $value) == 0
	or fatal(-1, "Error inserting run binding into DB!");
402
}
403

404
$instance->StartRun(Template::STARTRUN_FLAGS_FIRSTRUN()) == 0
405
    or fatal(-1, "Could not update start time in instance record!");
406

407 408
# Stop the web interface from spewing.
TBExptCloseLogFile($pid, $eid)
409 410 411 412
    if (defined($logname));

# Make sure the most recent version gets copied out.
$experiment->CopyLogFiles();
413

414
# Email is sent from libaudit at exit ...
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
exit(0);

#
# Parse command arguments. Once we return from getopts, all that are
# left are the required arguments.
#
sub ParseArgs()
{
    if (! getopts($optlist, \%options)) {
	usage();
    }

    if (@ARGV != 1) {
	usage();
    }
    #
    # Pick up guid/version first and untaint.
    #
    my $tmp = shift(@ARGV);

    if ($tmp =~ /^([\w]*)\/([\d]*)$/) {
	$guid = $1;
	$version = $2;
    }
    else {
	tbdie("Bad data in argument: $tmp");
    }

    if (defined($options{"e"})) {
	$eid = $options{"e"};

	if ($eid =~ /^([-\w]+)$/) {
	    $eid = $1;
	}
	else {
	    tbdie("Bad data in argument: $eid.");
	}
	if (! TBcheck_dbslot($eid, "experiments", "eid",
			   TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper experiment name (id)!");
	}
    }
    else {
	tberror("Must provide an experiment ID (-e option)!");
	exit(1);
    }

    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"w"})) {
	$waitmode = 1;
    }
468 469 470
    if (defined($options{"f"})) {
	$foreground = 1;
    }
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
#
# Subscribe to experiment state change events.
#
sub SetupEventHandler()
{
    my $port = @BOSSEVENTPORT@;
    my $URL  = "elvin://localhost:$port";
    
    # Connect to the event system, and subscribe the the events we want
    $EVhandle = event_register($URL, 0);
    
    if (!$EVhandle) {
	tbdie("Unable to register with event system\n");
    }

    my $tuple = address_tuple_alloc();
    if (!$tuple) {
	tbdie("Could not allocate an address tuple\n");
    }

    %$tuple = ( objtype   => libdb::TBDB_TBEVENT_EXPTSTATE(),
		objname   => "$pid/$eid",
		expt      => "$pid/$eid",
		host      => $BOSSNODE,
	      );
    
    if (!event_subscribe($EVhandle, \&EventHandler, $tuple)) {
	tbdie("Could not subscribe to events\n");
    }
}

#
# Callback for above.
#
sub EventHandler($$$) {
    my ($handle,$notification,undef) = @_;
    
    my $objname   = event_notification_get_objname($handle,$notification);
    my $eventtype = event_notification_get_eventtype($handle,$notification);

    print "$objname, $eventtype\n";

    return
	if ($objname ne "$pid/$eid");

    push(@ExptStates, $eventtype);
}

521 522 523 524 525
#
# Cleanup the mess.
#
sub cleanup()
{
526 527 528 529 530 531
    # For debugging.
    $experiment->BackupUserData()
	if (defined($experiment));

    $instance->DeleteCurrentRun()
	if (defined($run));
532

533 534
    # Stop the web interface from spewing.
    TBExptCloseLogFile($pid, $eid)
535
	if (defined($logname));
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
}

sub fatal($$)
{
    my ($errorstat, $msg) = @_;
    
    tberror $msg;
    tbinfo "Cleaning up and exiting with status $errorstat ...";

    #
    # This exit will drop into the END block below.
    # 
    exit($errorstat);
}

sub sighandler ($) {
    my ($signame) = @_;
    
    $SIG{TERM} = 'IGNORE';
    my $pgrp = getpgrp(0);
    kill('TERM', -$pgrp);
    sleep(1);
    fatal(-1, "Caught SIG${signame}! Killing experiment setup ...");
}

END {
    # Normal exit, nothing to do.
    if (!$? || $justexit) {
	return;
    }
    my $saved_exitcode = $?;
    
    if ($cleaning) {
	#
	# We are screwed; a recursive error. Someone will have to clean
	# up by hand. 
	#
573 574
	SENDMAIL($TBOPS, 
		 "Template Creation Failure: $pid/$eid",
575 576 577 578 579 580 581 582 583
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}