template_swapout.in 10.3 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2006, 2007 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{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/>.
# 
# }}}
23 24
#
use English;
25
use strict;
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
use Getopt::Std;
use POSIX qw(isatty setsid);
use POSIX qw(strftime);
use Errno qw(EDQUOT);

#
# Terminate a template instance (okay, swap it out and remove it).
#
# 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
	  "Usage: template_swapout [-q] [-w] -e <id> <guid/vers>\n".
	  "switches and arguments:\n".
	  "-w       - wait for template instance to be terminated\n".
	  "-q       - be less chatty\n".
	  "-e <id>  - The instance ID (aka eid)\n".
	  "<guid/vers> - GUID and version to swapin\n");
    exit(-1);
}
54
my $optlist	 = "qwaie:bf";
55 56
my %options      = ();
my $quiet        = 0;
57
my $force        = 0;
58
my $waitmode     = 0;
59
my $batchmode    = 0;	# Called from the batch daemon.
60 61 62 63 64 65 66 67 68 69 70 71 72
my $eid;
my $guid;
my $version;

#
# Configure variables
#
my $TB		= "@prefix@";
my $EVENTSYS	= @EVENTSYS@;
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
my $TBDOCBASE	= "@TBDOCBASE@";
my $TBBASE	= "@TBBASE@";
73
my $STAMPS      = @STAMPS@;
74 75

# Locals
76
my $pid;
77
my $logname;
78
my $logfile;
79
my $exptidx;
80 81
my $template;
my $instance;
82
my $neveractive = 0;
83 84 85 86 87 88
# For the END block below.
my $cleaning    = 0;
my $justexit    = 1;

# Programs we need
my $endexp      = "$TB/bin/endexp";
Leigh Stoller's avatar
Leigh Stoller committed
89 90
my $swapexp     = "$TB/bin/swapexp";
my $endrun      = "$TB/bin/template_exprun";
91 92 93 94 95 96 97 98 99 100 101 102 103

# Protos
sub ParseArgs();
sub fatal($$);
sub sighandler($);

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
104
use Template;
105
use Experiment;
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

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

#
130
# Verify user and get his DB uid and other info for later.
131
#
132 133 134
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
135
}
136
my $user_uid   = $this_user->uid();
137 138 139 140 141 142 143 144 145 146 147 148 149 150

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

#
151
# Grab template info and do access check.
152
#
153
$template = Template->Lookup($guid, $version);
154

155 156
if (!defined($template)) {
    tbdie("Experiment template $guid/$version does not exist!");
157
}
158
if (! $template->AccessCheck($this_user, TB_EXPT_DESTROY)) {
159 160 161
    tberror("You do not have permission to terminate template instance ".
	    "$eid in template $guid/$version");
    exit(1);
162
}
163
$pid = $template->pid();
164

165
#
166 167 168
# Now we need to find the experiment index so we can find the instance.
# This is wrong, but necessary cause of how templates are layered over
# the existing experiment structure.
169
#
170 171
if (! TBExptIDX($template->pid(), $eid, \$exptidx)) {
    fatal(-1, "Could not get experiment index for $pid,$eid!");
172
}
173 174 175 176 177 178

$instance = Template::Instance->LookupByExptidx($exptidx);
if (!defined($instance)) {
    fatal(-1, "Could not get instance record for experiment $exptidx!");
}

179 180 181 182 183 184
# Grab the experiment record for below.
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    fatal(-1, "Experiment $pid/$eid object could not be found!");
}

Leigh Stoller's avatar
Leigh Stoller committed
185
# Check for cancel and dequeue.
Leigh Stoller's avatar
Leigh Stoller committed
186 187
if (! $batchmode) {
    if ($experiment->state() eq EXPTSTATE_ACTIVATING) {
188
	system("$swapexp -x -s out $pid $eid");
Leigh Stoller's avatar
Leigh Stoller committed
189 190
	exit($? >> 8);
    }
Leigh Stoller's avatar
Leigh Stoller committed
191 192 193 194 195 196
    elsif ($experiment->batchmode() &&
	   $experiment->state() eq EXPTSTATE_QUEUED) {
	# User wants to dequeue a batch experiment that is waiting to go.
	system("$swapexp -x -s pause $pid $eid");
	exit($? >> 8);
    }
Leigh Stoller's avatar
Leigh Stoller committed
197 198
}

199 200 201 202 203 204
#
# At this point, we need to force a cleanup no matter how we exit.
# See the END block below.
#
$justexit = 0;

205 206 207 208
if ($STAMPS) {
    $instance->Stamp("template_swapout", "starting");
}

209 210 211 212 213 214 215 216
#
# Catch this so we can clean up.
#
$SIG{TERM} = \&sighandler;

#
# If not in batch mode, go into the background. Parent exits.
#
217
if (! $batchmode) {
218 219
    # Cleanup
    $experiment->CleanLogFiles() == 0
Leigh Stoller's avatar
Leigh Stoller committed
220
	or fatal(-1, "Could not clean up logfiles!");
221
    
222 223 224 225 226 227 228 229 230
    $logfile = $experiment->CreateLogFile("swapout");
    if (!defined($logfile)) {
	fatal(-1, "Could not create logfile!");
    }
    $logname = $logfile->filename();
    # 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();
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

    if (my $childpid = TBBackGround($logname)) {
	#
	# 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) {
	    print("Template instance is now being terminated.\n".
		  "You will be notified via email when the this is done.\n")
		if (! $quiet);
	    exit(0);
	}
	print("Waiting for template instance to terminate.\n")
	    if (! $quiet);
	    
248
	if (-f STDIN && !$quiet) {
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
	    print("You may type ^C at anytime; you will be notified via email.".
		  "\n".
		  "You will not actually interrupt the experiment itself.\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();
}
276 277 278
# Give the web page a chance to start looking at the log file before
# the entire experiment is gone.
sleep(1);
279 280 281 282 283 284 285 286 287

#
# When in waitmode, must put ourselves in another process group so that
# an interrupt to the parent will not have any effect on the backend.
#
if ($waitmode) {
    POSIX::setsid();
}

Leigh Stoller's avatar
Leigh Stoller committed
288
#
289
# Stop the current run, but only if the instance was actually instantiated.
Leigh Stoller's avatar
Leigh Stoller committed
290
#
291 292
if (defined($instance->start_time())) {
    my $opt = ($force ? "-i" : "");
293

294 295 296 297
    if ($STAMPS) {
	$instance->Stamp("template_swapout", "stoprun starting");
    }

298 299
    system("$endrun $opt -a stop -f -e $eid $guid/$version") == 0
	or fatal(-1, "Could not stop the current run!");
Leigh Stoller's avatar
Leigh Stoller committed
300

301 302 303 304
    if ($STAMPS) {
	$instance->Stamp("template_swapout", "stoprun done");
    }

305 306 307 308
    # This sets the stop time.
    $instance->Stop() == 0
	or fatal(-1, "Could not stop experiment instance!");
}
309

310 311 312 313
if ($STAMPS) {
    $instance->Stamp("template_swapout", "endexp starting");
}

314
#
315
# Now do the swapout (or just the termination).
316 317 318
#
# Note special -x option.
#
319 320 321
my @arguments = ($endexp, "-x", "-q");
push(@arguments, "-b")
    if ($batchmode);
322
push(@arguments, ($exptidx));
323 324 325 326 327 328

# Now invoke.
system(@arguments);
fatal($? >> 8, "Could not terminate template instance")
    if ($?);

329 330 331 332
if ($STAMPS) {
    $instance->Stamp("template_swapout", "endexp done");
}

333 334 335 336 337 338 339 340 341 342 343
if (defined($instance->start_time())) {
    # Reminder; instance records are not deleted.
    $instance->Finalize() == 0
	or fatal(-1, "Could not finalize experiment instance!");
}
else {
    # Okay, we *do* delete if the instance was never instantiated.
    print("Deleting instance since it was never swapped in!\n");
    $instance->Delete() == 0
	or fatal(-1, "Could not delete instance!");
}
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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

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 instance ID!");
	exit(1);
    }

    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"w"})) {
	$waitmode = 1;
    }
398 399 400
    if (defined($options{"b"})) {
	$batchmode = 1;
    }
401 402 403
    if (defined($options{"f"})) {
	$force = 1;
    }
404 405 406 407 408 409 410 411 412 413 414 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
}

#
# Cleanup the mess.
#
sub cleanup()
{
}

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}!");
}

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. 
	#
448 449
	SENDMAIL($TBOPS, 
		 "Instance Termination Failure: $pid/$eid",
450 451 452 453 454 455 456 457 458
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}