template_swapin.in 14.4 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
4
# Copyright (c) 2006, 2007, 2008 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 $logfile;
70
my $logname;
71
my @ExptStates  = ();
72 73
# For the END block below.
my $cleaning    = 0;
74
my $exptactive  = 0;
75 76 77 78 79 80 81
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
my $CVSBIN      = "/usr/bin/cvs";
85
my $RLOG        = "/usr/bin/rlog";
86 87 88 89 90

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

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
100
use User;
101
use Template;
102
use Experiment;
103
use event;
104
use libaudit;
105

106 107 108
# In libdb
my $projroot = PROJROOT();

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
# 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.
#
134 135 136
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
137
}
138 139 140
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
my $user_uid   = $this_user->uid();
141 142 143 144 145

#
# Before doing anything else, check for overquota ... lets not waste
# our time. Make sure user sees the error by exiting with 1.
#
146
if (system("$checkquota $user_uid") != 0) {
147 148
    tberror("You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    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';
}

#
165
# Grab template and do access check.
166
#
167
$template = Template->Lookup($guid, $version);
168

169 170 171
if (!defined($template)) {
    tbdie("Experiment template $guid/$version does not exist!");
}
172 173 174 175 176
my $project = $template->GetProject();
if (!defined($project)) {
    tbdie("Could not get project for $template");
}
if (! $project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT)) {
177 178 179 180
    tberror("You do not have permission to instantiate template ".
	    "$guid/$version");
    exit(1);
}
181
$pid = $template->pid();
182

183
#
184
# Grab instance; better exist since this is a swapin of an instance!
185
#
186 187 188
# 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.
189
#
190 191 192
$experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    tbdie("Experiment $pid/$eid does not exist!");
193 194
}

195
$instance = Template::Instance->LookupByExptidx($experiment->idx());
196
if (!defined($instance)) {
197
    tbdie("Could not get instance record for experiment $pid/$eid!");
198 199
}

200 201 202
# Need these for default run below.
$instance->BindingList(\%parameters) == 0
    or fatal(-1, "Error getting bindings from $instance!");
203

204 205 206 207 208 209 210 211 212
#
# 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.
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
213
if (! $foreground) {
214 215 216
    # Cleanup
    $experiment->CleanLogFiles() == 0
	or fatal(-1, "Could not clean up logfiles!");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    #
    # If its a batch experiment, then the daemon will set the spewlog,
    # so attach it to the instance instead so that we can see both.
    #
    if ($experiment->batchmode()) {
	$logfile = $instance->CreateLogFile("batchswapin");
    }
    else {
	$logfile = $experiment->CreateLogFile("swapin");
	# We want it to spew to the web.
	$experiment->SetLogFile($logfile);
	# Mark it open since we are going to start using it right away.
	$logfile->Open();	
    }
    if (!defined($logfile)) {
	fatal(-1, "Could not create logfile");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
234
    }
235
    $logname = $logfile->filename();
236 237

    if (my $childpid = AuditStart(LIBAUDIT_DAEMON, $logname,
238
			  LIBAUDIT_LOGONLY|LIBAUDIT_NODELETE|LIBAUDIT_FANCY)) {
239 240 241 242 243 244 245
	#
	# 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) {
246
	    if ($experiment->batchmode()) {
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 278 279 280 281 282 283 284 285 286 287
		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();
Kevin Atkinson's avatar
Kevin Atkinson committed
288 289 290 291 292 293 294 295

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

296 297 298 299 300
    my $creator = $experiment->GetCreator();
    if (defined($creator)) {
	my $expt_head_name  = $creator->name();
	my $expt_head_email = $creator->email();
	
Kevin Atkinson's avatar
Kevin Atkinson committed
301
	AddAuditInfo("cc", "$expt_head_name <$expt_head_email>");
302 303 304
    }
    else {
	tbwarn("Could not determine name/email for experiment creator");
Kevin Atkinson's avatar
Kevin Atkinson committed
305
    }
306 307
}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
#
# All instances currently start with a default run.
#
$run = $instance->NewRun($eid, $this_user, $instance->description());
if (!defined($run)) {
    fatal(-1, "Could not create new experiment run for $instance!");
}

#
# And the bindings for the default run ...
#
foreach my $name (keys(%parameters)) {
    my $value = $parameters{$name};

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

326 327 328
# Event connect before starting swapin so we catch all the states.
SetupEventHandler()
    if ($experiment->batchmode());
329

330
#
331
# Now do the swapin (or it gets queued if a batch experiment).
332
#
333
my @arguments = ($swapexp, "-q", "-x", "-s", "in", $pid, $eid);
334 335 336 337 338

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

339 340 341 342 343 344
#
# At this point, we need to force a cleanup no matter how we exit.
# See the END block below.
#
$justexit = 0;

345 346 347
# And we need to terminate the experiment!
$exptactive = 1;

348 349 350 351
#
# We will spew forth info to the user each time the batch daemon tries to
# swap it in. 
#
352
if ($experiment->batchmode()) {
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
    #
    # 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) {
	    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.
386
		print "Experiment has been removed from the batch queue.\n";
387

Leigh B. Stoller's avatar
Leigh B. Stoller committed
388 389 390
		$instance->DeleteCurrentRun() == 0
		    or exit(-1);

391
		#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
392
		# We are done. User has to requeue batched instance.
393
		#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
394
		exit(0);
395 396 397 398 399 400
	    }
	}
    }
  done:
}

401 402 403 404
#
# Lets commit the experiment archive now that it is active. The experiment is
# already running, but thats not a big deal.
#
405
system("$archcontrol -t swapin commit $pid $eid");
406 407 408 409
if ($?) {
    fatal(-1, "Could not commit archive!");
}

410 411 412 413 414 415 416 417
#
# Do the CVS stuff.
#
my $exptidx      = $instance->exptidx();
my $cvsdir       = "$projroot/$pid/templates/$guid/cvsrepo";
my $instance_tag = "I${exptidx}";
my $template_tag = "T${guid}-$version";

418 419 420 421 422
if (-e $cvsdir) {
    # Tag the template with an instance tag. This tag is used to associate
    # records with this instance with the actual template.
    # The rlog check is so we can deal with old templates that have an
    # incomplete CVS repo.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
423
    System("$RLOG -h $cvsdir/setup/.template,v | ".
424 425 426
	   "  grep -q '${template_tag}:'");
    if (! $?) {
	System("$CVSBIN -d $cvsdir rtag -n -r ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
427
	       "  $template_tag $instance_tag setup") == 0
428 429 430
	       or fatal(-1, "Could not rtag with instance tag in $cvsdir");
    }
}
431

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

435
# Stop the web interface from spewing.
436 437 438 439 440 441
if ($experiment->batchmode()) {
    $logfile->Close();
}
else {
    $experiment->CloseLogFile();
}
442 443 444

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

446
# Email is sent from libaudit at exit ...
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
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;
    }
500 501 502
    if (defined($options{"f"})) {
	$foreground = 1;
    }
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
#
# 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);
}

553 554 555 556 557
#
# Cleanup the mess.
#
sub cleanup()
{
558 559 560 561
    # For debugging.
    $experiment->BackupUserData()
	if (defined($experiment));

562
    if ($exptactive) {
563
	$experiment->Swap($Experiment::EXPT_SWAPOUT, "-force") == 0
564 565 566
	    or exit(-1);
    }

567 568
    $instance->DeleteCurrentRun()
	if (defined($run));
569

570
    # Stop the web interface from spewing.
571 572 573 574 575 576 577 578
    if (defined($logfile)) {
	if ($experiment->batchmode()) {
	    $logfile->Close();
	}
	else {
	    $experiment->CloseLogFile();
	}
    }
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
}

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. 
	#
616 617
	SENDMAIL($TBOPS, 
		 "Template Creation Failure: $pid/$eid",
618 619 620 621 622 623 624 625 626
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}