endexp.in 10 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/usr/bin/perl -wT
use English;
use Getopt::Std;

#
# This gets invoked from the Web interface. Terminate an experiment.
# Most of the STDOUT prints are never seen since the web interface
# repeats only errors. My plan is make this script the front end to
# experiment termination and make tbend a backend program that no one
# uses.
#
# The -b (batch) argument is so that this script can be part of a batchmode
# that starts/ends experiments offline. In that case, we don't want to put
# it into the background and send email, but just want an exit status 
# returned to the batch system.
#
17 18 19 20
# Note about exit value. -1 means error. 0 means backgrounded. 1 means
# termination happened immediately. The web page uses this to decide
# what kind of message to give the user. 
#
21 22 23 24 25 26 27 28 29 30 31 32 33
sub usage()
{
    print STDOUT "Usage: endexp [-b] <pid> <eid>\n";
    exit(-1);
}
my  $optlist = "b";

#
# Configure variables
#
my $TB     = "@prefix@";
my $DBNAME = "@TBDBNAME@";
my $TBOPS  = "@TBOPSEMAIL@";
34
my $TBLOGS = "@TBLOGSEMAIL@";
35

36 37 38 39 40 41 42
#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;

43 44 45 46
my $tbdir    = "$TB/bin/";
my $projroot = "/proj";
my $tbdata   = "tbdata";
my $batch    = 0;
47 48 49 50
my $logname;
my $dbuid;
my $user_name;
my $user_email;
51 52
my @row;
    
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#
# Untaint the path
# 
$ENV{'PATH'} = '/bin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 2) {
    usage();
}
my $pid   = $ARGV[0];
my $eid   = $ARGV[1];
if (defined($options{"b"})) {
    $batch = $options{"b"};
}

#
# Untaint the arguments.
#
if ($pid =~ /^([-\@\w.]+)$/) {
    $pid = $1;
}
87 88 89
else {
    die("Tainted argument $pid!\n");
}
90 91 92
if ($eid =~ /^([-\@\w.]+)$/) {
    $eid = $1;
}
93 94 95
else {
    die("Tainted argument $eid!\n");
}
96 97

#
98
# Verify user and get his DB uid.
99
#
100 101 102
if (! UNIX2DBUID($UID, \$dbuid)) {
    die("*** $0:\n".
	"    You do not exist in the Emulab Database.\n");
103 104
}

105 106 107
#
# Get email info for user.
#
108 109 110
if (! UserDBInfo($dbuid, \$user_name, \$user_email)) {
    die("*** $0:\n".
	"    Cannot determine your name and email address.\n");
111
}
112 113

#
Leigh Stoller's avatar
Leigh Stoller committed
114 115
# Verify that this person is allowed to end the experiment.
# Note that any script down the line has to do an admin check also. 
116
#
117 118 119 120
if ($UID && !TBAdmin($UID) &&
    !TBExptAccessCheck($dbuid, $pid, $eid, TB_EXPT_DESTROY)) {
    die("*** $0:\n".
	"    You do not have permission to end this experiment!\n");
121 122 123
}

#
Leigh Stoller's avatar
Leigh Stoller committed
124 125 126
# We have to protect against trying to end an experiment that is currently
# in the process of being terminated. We use a "wrapper" state (actually
# a timestamp so we can say when termination was requested) since
127
# terminating consists of a couple of different experiment states down inside
Leigh Stoller's avatar
Leigh Stoller committed
128 129
# the tb scripts. 
#
130
DBQueryFatal("lock tables experiments write");
Leigh Stoller's avatar
Leigh Stoller committed
131 132

$query_result =
133
    DBQueryFatal("SELECT * FROM experiments WHERE eid='$eid' and pid='$pid'");
Leigh Stoller's avatar
Leigh Stoller committed
134

135 136 137
if (! $query_result->numrows) {
    die("*** $0:\n".
	"    No such experiment $pid/$eid exists!\n");
Leigh Stoller's avatar
Leigh Stoller committed
138
}
139 140 141 142 143 144 145
my %hashrow = $query_result->fetchhash();
my $expt_head_login = $hashrow{'expt_head_uid'};
my $estate          = $hashrow{'state'};
my $expt_path       = $hashrow{'path'};
my $isbatchexpt     = $hashrow{'batchmode'};
my $ebatchstate     = $hashrow{'batchstate'};

146 147
if (defined($hashrow{'expt_locked'})) {
    $val = $hashrow{'expt_locked'};
148
    
149 150 151 152
    die("*** $0:\n".
	"    It appears that $pid/$eid went into transition at $val.\n".
	"    You will be notified via email when the experiment is no\n".
	"    longer in transition.\n");
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
}

#
# Batch experiments get a different protocol to avoid races with the
# batch daemon. We can kill the experiment directly, but only if the
# batch daemon is not currently working on it. In this case, its the
# same as killing an experiment that is not running.
#
# XXX: This script is run from the batch daemon. Use the batch state
# to determine when this was invoked from the batch daemon for a valid
# teardown. 
#
if ($isbatchexpt && $ebatchstate ne BATCHSTATE_TERMINATING) {
    #
    # Set the canceled state. This will prevent the batch_daemon from trying
    # to run it (once the table is unlocked). It might already be running,
    # but we deal with that by looking at the batch state.
    #
    DBQueryFatal("UPDATE experiments set canceled=1 ".
		 "WHERE eid='$eid' and pid='$pid'");

    if ($ebatchstate ne BATCHSTATE_POSTED) {
	#
	# Daemon does the rest ... Exit with non zero status so that caller
	# knows (web server) that the batch experiement cannot be ended
	# at this time.
	#
	print "Batch Experiment $eid in project $pid is currently running.\n".
	      "You will receive email notification when the experiment is\n".
	      "torn down and you can reuse the experiment name\n";
	exit(0);
    }
    DBQueryFatal("unlock tables");

    #
    # Cleanup Experiment state.
    # 
    ExptCleanup();
    
Leigh Stoller's avatar
Leigh Stoller committed
192 193 194 195 196 197 198 199 200 201
    exit(1);
}

#
# Okay, check state. We do not allow termination to start when the
# experiment is in transition. A future task would be to allow this,
# but for now the experiment must be in one of a few states to proceed
#
# Seems like too many states!
#
202 203 204 205
if ($estate eq EXPTSTATE_PRERUN ||
    $estate eq EXPTSTATE_ACTIVATING ||
    $estate eq EXPTSTATE_SWAPPING ||
    $estate eq EXPTSTATE_TERMINATING) {
206 207 208 209
    die("*** $0:\n".
	"    It appears that experiment $pid/$eid is in transition.\n".
	"    The user that created the experiment will be notified via\n".
        "    email when the experiment is no longer in transition.\n");
Leigh Stoller's avatar
Leigh Stoller committed
210 211 212 213
}

#
# Set the timestamp now, and unlock the experiments table.
214
#
215
DBQueryFatal("UPDATE experiments SET expt_locked=now() ".
216
	     "WHERE eid='$eid' and pid='$pid'");
217

218 219 220
DBQueryFatal("unlock tables");

#
221 222
# XXX - At this point a failure is going to leave things in an
# inconsistent state.
223
#
224 225 226 227 228

#
# Get email address of the experiment head, which may be different than
# the person who is actually terminating the experiment, since its polite
# to let the original creator know whats going on. 
229 230 231 232 233 234 235 236 237 238
#
my $expt_head_name;
my $expt_head_email;

if (! UserDBInfo($expt_head_login, \$expt_head_name, \$expt_head_email)) {
    print STDERR "*** WARNING: ".
	         "Could not determine name/email for $expt_head_login.\n";
    $expt_head_name  = "TBOPS";
    $expt_head_email = $TBOPS;
}
Leigh Stoller's avatar
Leigh Stoller committed
239

240 241 242 243
#
# If not in batch mode, go into the background. Parent exits.
#
if (! $batch) {
244 245 246 247 248 249 250 251 252
    $logname = `mktemp /tmp/end-$pid-$eid.XXXXXX`;

    if ($logname =~ /^([-\@\w.\/]+)$/) {
	$logname = $1;
    }
    else {
	die("Bad data in logfile name: $logname");
    }
    
253
    if (TBBackGround($logname)) {
254 255 256 257 258 259 260 261 262 263 264
	#
	# Parent exits normally
	#
	print STDOUT
	    "Experiment $pid/$eid is now terminating\n".
	    "You will be notified via email when the experiment has been\n".
	    "torn down, and you can reuse the experiment name.\n";
	exit(0);
    }
}

265 266 267
#
# Sanity check states in case someone changes something.
#
268 269 270
if ($estate eq EXPTSTATE_ACTIVE) { 
    print STDOUT "Running tbswapout with arguments: $pid $eid\n";
    if (system("$tbdir/tbswapout $pid $eid") != 0) {
Leigh Stoller's avatar
Leigh Stoller committed
271 272
	fatal("tbswapout failed!\n");
    }
273 274
    
    $estate = ExpState($pid,$eid);
275
    if ($estate ne EXPTSTATE_SWAPPED) {
276 277
	fatal("Experiment is in the wrong state: $estate\n");
    }
Leigh Stoller's avatar
Leigh Stoller committed
278
}
279

280 281 282
if ($estate eq EXPTSTATE_SWAPPED) {
    print STDOUT "Running tbend with arguments: $pid $eid\n";
    if (system("$tbdir/tbend $pid $eid") != 0) {
283 284 285
	fatal("tbend failed!\n");
    }    
    $estate = ExpState($pid,$eid);
286
    if ($estate ne EXPTSTATE_TERMINATED) {
287 288
	fatal("Experiment is in the wrong state: $estate\n");
    }
Leigh Stoller's avatar
Leigh Stoller committed
289 290
}

Leigh Stoller's avatar
Leigh Stoller committed
291
if ($estate ne EXPTSTATE_TERMINATED && $estate ne EXPTSTATE_NEW) {
292 293
    fatal("Experiment is in the wrong state: $estate\n");
}
294 295

#
296
# Cleanup DB state and remove directory.
297
# 
298
ExptCleanup();
299

300
print "Termination Success\n";
301 302 303 304 305 306 307 308 309

#
# In batch mode, just exit without sending email.
#
if ($batch) {
    exit(0);
}

#
310
# Send email notification to user.
311
#
312 313 314 315 316 317
my $message =
    "Experiment `$eid' in project `$pid' has been terminated.\n" .
    "You may now reuse `$eid' as an experiment name.\n\n" .
    "Appended below is the output of the experiment teardown. If you\n" .
    "have any questions or comments, please include the output below\n" .
    "in your message to $TBOPS\n";
318

319 320 321 322 323 324 325
SENDMAIL("$user_name <$user_email>",
	 "TESTBED: Experiment $pid/$eid Terminated",
	 $message,
	 "$user_name <$user_email>",
	 "Cc:  $expt_head_name <$expt_head_email>\n".
	 "Bcc: $TBLOGS",
	 ($logname));
326

327 328 329
if (defined($logname)) {
    unlink("$logname");
}
330 331
exit 0;

332
sub fatal($)
333 334
{
    my($mesg) = $_[0];
335
    
336 337
    print STDOUT $mesg;

Leigh Stoller's avatar
Leigh Stoller committed
338 339 340
    #
    # Kill this for convenience later.
    # 
341
    DBQueryWarn("update experiments set expt_locked=NULL ".
Leigh Stoller's avatar
Leigh Stoller committed
342 343
		"WHERE eid='$eid' and pid='$pid'");

344 345 346 347 348 349 350 351
    #
    # In batch mode, exit without sending the email. 
    #
    if ($batch) {
	exit(-1);
    }

    #
352
    # Send a message to the testbed list. Append the logfile.
353
    #
354 355 356 357 358 359 360
    SENDMAIL("$user_name <$user_email>",
	     "TESTBED: Termination Failure: $pid/$eid",
	     $mesg,
	     "$user_name <$user_email>",
	     "Cc:  $expt_head_name <$expt_head_email>\n".
	     "Bcc: $TBOPS",
	     ($logname));
361

362 363 364
    if (defined($logname)) {
	unlink("$logname");
    }
365 366 367
    exit(-1);
}

368
sub ExptCleanup()
369 370
{
    #
371 372 373 374 375
    # Try to remove experiment directory. We allow for it not being there
    # cause we often run the tb programs directly. We also allow for not
    # having permission, in the case that an admin type is running this,
    # in which case it won't be allowed cause of directory permissions. Thats
    # okay since admin types should rarely end experiments in other projects.
376
    #
377 378 379 380 381
    print STDOUT "Removing experiment directory: $expt_path ... \n";
    if (system("rm -rf $expt_path")) {
	print "*** WARNING: Not able to remove experiment directory.\n";
	print "             Someone will need to do this by hand.\n";
    }
382 383

    #
384 385 386 387
    # Remove all trace from the DB.
    # 
    DBQueryWarn("DELETE from nsfiles ".
		"WHERE eid='$eid' and pid='$pid'");
388

389 390
    DBQueryWarn("DELETE from exppid_access ".
		"WHERE exp_eid='$eid' and exp_pid='$pid'");
391

392 393
    DBQueryWarn("DELETE from experiments ".
		"WHERE eid='$eid' and pid='$pid'");
394
}
395 396