template_swapin.in 13.6 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 @ExptStates  = ();
71 72 73 74 75 76 77 78 79 80
# 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";
81
my $dbcontrol   = "$TB/sbin/opsdb_control";
82
my $archcontrol = "$TB/bin/archive_control";
83
my $CVSBIN      = "/usr/bin/cvs";
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
# In libdb
my $projroot = PROJROOT();

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
# 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.
#
132 133 134
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
135
}
136 137 138
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
my $user_uid   = $this_user->uid();
139 140 141 142 143

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

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

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

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

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

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

200 201 202 203 204 205 206 207 208
#
# 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.
#
209 210 211 212 213 214 215 216
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);
217 218

    if (my $childpid = AuditStart(LIBAUDIT_DAEMON, $logname,
Kevin Atkinson's avatar
Kevin Atkinson committed
219
				  LIBAUDIT_LOGONLY|LIBAUDIT_NODELETE|LIBAUDIT_FANCY)) {
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
	#
	# 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);
	    }
239
	    if ($experiment->batchmode()) {
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 278 279 280
		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
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

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

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
#
# 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!");
}

317 318 319
# Event connect before starting swapin so we catch all the states.
SetupEventHandler()
    if ($experiment->batchmode());
320

321
#
322
# Now do the swapin (or it gets queued if a batch experiment).
323
#
324
my @arguments = ($swapexp, "-q", "-x", "-s", "in", $pid, $eid);
325 326 327 328 329

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

330 331 332 333 334 335
#
# At this point, we need to force a cleanup no matter how we exit.
# See the END block below.
#
$justexit = 0;

336 337 338 339
#
# We will spew forth info to the user each time the batch daemon tries to
# swap it in. 
#
340
if ($experiment->batchmode()) {
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    #
    # 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.
376
		print "Experiment has been removed from the batch queue.\n";
377 378 379 380 381 382 383 384 385 386 387

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

388 389 390 391
#
# Lets commit the experiment archive now that it is active. The experiment is
# already running, but thats not a big deal.
#
392
system("$archcontrol -t swapin commit $pid $eid");
393 394 395 396
if ($?) {
    fatal(-1, "Could not commit archive!");
}

397 398 399 400 401 402 403 404 405 406 407 408 409 410
#
# 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";

# Tag the template with an instance tag. This tag is used to associate
# records with this instance with the actual template.
System("$CVSBIN -d $cvsdir rtag -n -r ".
       "  $template_tag $instance_tag $guid/setup") == 0
    or fatal(-1, "Could not rtag with instance tag in $cvsdir");

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

414 415
# Stop the web interface from spewing.
TBExptCloseLogFile($pid, $eid)
416 417 418 419
    if (defined($logname));

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

421
# Email is sent from libaudit at exit ...
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
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;
    }
475 476 477
    if (defined($options{"f"})) {
	$foreground = 1;
    }
478 479
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
#
# 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);
}

528 529 530 531 532
#
# Cleanup the mess.
#
sub cleanup()
{
533 534 535 536 537 538
    # For debugging.
    $experiment->BackupUserData()
	if (defined($experiment));

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

540 541
    # Stop the web interface from spewing.
    TBExptCloseLogFile($pid, $eid)
542
	if (defined($logname));
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
}

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. 
	#
580 581
	SENDMAIL($TBOPS, 
		 "Template Creation Failure: $pid/$eid",
582 583 584 585 586 587 588 589 590
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}