manage_instance.in 110 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2018 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 23 24 25 26 27 28 29 30
# 
# {{{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/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
use CGI;
use POSIX ":sys_wait_h";
31
use POSIX qw(setsid strftime ceil floor);
32
use Date::Parse;
33
use JSON;
34 35 36 37 38 39

#
# Back-end script to manage APT profiles.
#
sub usage()
{
Leigh Stoller's avatar
Leigh Stoller committed
40 41
    print("Usage: manage_instance snapshot instance ".
	  "[-n node_id] [-i imagename] [-u node|all]\n");
42 43 44
    print("Usage: manage_instance consoleurl instance node\n");
    print("Usage: manage_instance terminate instance\n");
    print("Usage: manage_instance refresh instance\n");
45 46 47
    print("Usage: manage_instance reboot instance node_id ...\n");
    print("Usage: manage_instance reload instance node_id ...\n");
    print("Usage: manage_instance deletenodes instance node_id ...\n");
48
    print("Usage: manage_instance monitor instance\n");
49
    print("Usage: manage_instance lockdown instance set|clear user|admin\n");
50
    print("Usage: manage_instance panic instance set|clear\n");
51
    print("Usage: manage_instance linktest instance [-k | level]\n");
52
    print("Usage: manage_instance writecreds instance directory\n");
53
    print("Usage: manage_instance updatekeys instance [uid] \n");
54
    print("Usage: manage_instance extend instance ".
55
	  "[-M] [-m message | -f filename] hours\n");
56
    print("Usage: manage_instance denyextension instance [-m message] [filename]\n");
57
    print("Usage: manage_instance maxextension instance\n");
58
    print("Usage: manage_instance moreinfo instance [-m message] [filename]\n");
59
    print("Usage: manage_instance utilization instance\n");
60
    print("Usage: manage_instance schedterminate instance [-m message] days [filename]\n");
61
    print("Usage: manage_instance idledata instance\n");
62
    print("Usage: manage_instance openstackstats instance\n");
Leigh Stoller's avatar
Leigh Stoller committed
63
    print("Usage: manage_instance getmanifests instance\n");
64
    print("Usage: manage_instance applyextensionpolicy instance\n");
65 66
    exit(-1);
}
67
my $optlist     = "dt:s";
68
my $debug       = 0;
69
my $silent      = 0;
70
my $webtask_id;
71
my $webtask;
72 73
my $this_user;
my $geniuser;
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $QUICKVM     = "$TB/sbin/protogeni/quickvm";

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use EmulabConstants;
use emdb;
use emutil;
100
use libEmulab;
101
use libtestbed;
102 103 104 105
use User;
use Project;
use APT_Profile;
use APT_Instance;
106
use APT_Geni;
107 108
use GeniXML;
use GeniHRN;
109 110 111
use Genixmlrpc;
use GeniResponse;
use GeniSlice;
112
use GeniImage;
113
use GeniUser;
114
use WebTask;
115
use EmulabFeatures;
116 117 118

# Protos
sub fatal($);
119
sub UserError($);
120
sub DoSnapshot();
121
sub DoConsole();
122
sub DoTerminate();
123
sub DoSchedTerminate();
124
sub DoExtend();
125
sub DoDenyOrMoreInfo($);
126
sub DoRefresh();
127
sub DoReboot();
128
sub DoReload();
129
sub DoLockdown();
130
sub DoPanic();
131
sub DoManifests();
132
sub DoLinktest();
133
sub DoUpdateKeys();
134
sub DoDeleteNodes();
135
sub DoUtilization();
136
sub DoIdleData();
137
sub DoOpenstack();
138 139
sub DoCheckAutoApprove();
sub CheckAutoApprove($$);
140
sub DoMaxExtension();
141
sub DoMaxExtensionInternal($$);
142
sub DoApplyExtensionPolicy();
143
sub WriteCredentials();
144
sub StartMonitor();
145
sub StartMonitorInternal(;$);
146
sub DoImageTrackerStuff($$$$$$$);
147
sub DenyExtensionInternal($);
148
sub ExtendInternal($$$$$);
149 150
sub CallMethodOnAggregates($$$@);
sub ResponseErrorMessage($$);
151 152 153 154 155 156 157 158 159 160 161 162

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
}
163 164 165
if (defined($options{"d"})) {
    $debug++;
}
166 167 168
if (defined($options{"s"})) {
    $silent = 1;
}
169
if (@ARGV < 2) {
170 171
    usage();
}
172
my $action   = shift(@ARGV);
173 174
my $uuid     = shift(@ARGV);
my $instance = APT_Instance->Lookup($uuid);
175 176 177
if (!defined($instance)) {
    $instance = APT_Instance->LookupBySlice($uuid);
}
178
if (!defined($instance)) {
179 180 181
    # Lets not make this a fatal error; when coming from the web interface,
    # we do not need to send email. 
    UserError("No such instance $uuid");
182
}
183 184 185 186 187 188 189 190 191 192 193
#
# Grab the webtask object.
#
if (defined($webtask_id)) {
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not lookup/create webtask for profile");
    }
    $webtask->AutoStore(1);
}

194 195 196 197 198 199 200 201 202 203
if (getpwuid($UID) eq "nobody") {
    $this_user = User->ImpliedUser();
}
else  {
    $this_user = User->ThisUser();
}
# If a guest user, we will not have an actual user, which is okay.
if (defined($this_user)) {
    $geniuser = GeniUser->CreateFromLocal($this_user);
}
204

205
if ($action eq "snapshot") {
206 207
    DoSnapshot();
}
208 209 210
if ($action eq "extend") {
    DoExtend();
}
211
elsif ($action eq "denyextension") {
212 213 214 215
    DoDenyOrMoreInfo("deny")
}
elsif ($action eq "moreinfo") {
    DoDenyOrMoreInfo("info")
216
}
217
elsif ($action eq "consoleurl") {
218 219
    DoConsole()
}
220 221 222
elsif ($action eq "terminate") {
    DoTerminate()
}
223 224 225
elsif ($action eq "schedterminate") {
    DoSchedTerminate()
}
226 227 228
elsif ($action eq "refresh") {
    DoRefresh()
}
229 230 231
elsif ($action eq "reboot") {
    DoReboot()
}
232 233 234
elsif ($action eq "reload") {
    DoReload()
}
235 236 237
elsif ($action eq "monitor") {
    StartMonitor()
}
238 239 240
elsif ($action eq "lockdown") {
    DoLockdown()
}
241 242 243
elsif ($action eq "panic") {
    DoPanic()
}
244 245 246
elsif ($action eq "linktest") {
    DoLinktest()
}
247 248 249
elsif ($action eq "updatekeys") {
    DoUpdateKeys()
}
250 251 252
elsif ($action eq "writecreds") {
    WriteCredentials()
}
253 254 255
elsif ($action eq "getmanifests") {
    DoManifests()
}
256 257 258
elsif ($action eq "deletenodes") {
    DoDeleteNodes()
}
259 260 261
elsif ($action eq "utilization") {
    DoUtilization()
}
262 263 264
elsif ($action eq "idledata") {
    DoIdleData()
}
265 266 267
elsif ($action eq "openstackstats") {
    DoOpenstack()
}
268 269 270
elsif ($action eq "maxextension") {
    DoMaxExtension()
}
271 272 273
elsif ($action eq "checkautoapprove") {
    DoCheckAutoApprove()
}
274 275 276
elsif ($action eq "applyextensionpolicy") {
    DoApplyExtensionPolicy()
}
277 278 279
else {
    usage();
}
280 281 282 283 284 285 286
exit(0);

#
# Take a snapshot. Implies a single node instance, for now.
#
sub DoSnapshot()
{
287 288
    my $errmsg;
    my $logfile;
289
    my $errcode        = -1;
290
    my $exitcode       = -1;
291 292
    my $needunlock     = 0;
    my $old_status     = $instance->status();
293 294
    my $node_id;
    my $imagename;
295
    my $cloneprofile;
296
    my $update_profile;
297 298
    my $copyback_uuid;
    my $copyback_urn;
299 300 301
    my $swebtask;
    my $nosnapshot     = 0;
    my $mustnotexist   = 0;
302
    my $wholedisk      = 0;
303
    my $update_prepare = 0;
304 305
    my $doversions = 0;
    my $usetracker = 0;
306
    my $operation = "image-only"; # Default to just snapshot.
307

308
    my $optlist = "n:i:u:Uc:O:Sse";
309 310 311 312 313 314 315 316 317 318
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"n"})) {
	$node_id = $options{"n"};
    }
    if (defined($options{"i"})) {
	$imagename = $options{"i"};
    }
319 320 321
    if (defined($options{"c"})) {
	$cloneprofile = $options{"c"};
    }
322 323 324 325 326 327
    if (defined($options{"u"})) {
	$update_profile = $options{"u"};
	if ($update_profile !~ /^(node|all)$/) {
	    usage();
	}
    }
328 329 330
    if (defined($options{"U"})) {
	$update_prepare = 1;
    }
331 332 333
    if (defined($options{"s"})) {
	$nosnapshot = 1;
    }
334 335 336 337 338
    if (defined($options{"e"})) {
	$wholedisk = 1;
	# Must be a brand new image for wholedisk. 
	$mustnotexist = 1;
    }
339 340 341 342 343 344 345 346 347 348 349 350 351 352
    if (defined($options{"S"})) {
	$nosnapshot = 1;
	$mustnotexist = 1;
    }
    if (defined($options{"O"})) {
	$operation = $options{"O"};
	if ($operation !~
	    /^(update-profile|copy-profile|new-profile|image-only)$/) {
	    usage();
	}
	if ($operation eq "update-profile") {
	    $update_profile = "node";
	}
    }
353 354 355 356 357 358
    if (defined($cloneprofile) && defined($update_profile)) {
	fatal("Not allowed to update profile when cloning a profile");
    }
    if (defined($cloneprofile) && !defined($imagename)) {
	fatal("Must supply image name when cloning a profile");
    }
359 360 361 362 363 364 365
    if ($old_status ne "ready") {
	fatal("Instance must be in the ready state to take a snapshot");
    }
    my $slice = $instance->GetGeniSlice();
    if (!defined($slice)) {
	fatal("No slice for quick VM: $uuid");
    }
366
    
367
    #
368
    # Might be a clone (manage_profile).
369
    #
370
    my $sliver_urn;
371 372
    my $aggregate;
    my $node;
373 374 375 376 377 378 379 380
    my $profile;

    if (defined($cloneprofile)) {
	$profile = APT_Profile->Lookup($cloneprofile);
    }
    else {
	$profile = APT_Profile->Lookup($instance->profile_id());
    }
381
    if (!defined($profile)) {
382 383
	fatal("Could not lookup profile for " .
	      (defined($cloneprofile) ? "cloning" : "snapshot"));
384
    }
385 386
    my $project = Project->Lookup($profile->pid_idx());
    if (!defined($project)) {
387
	fatal("Could not lookup project for $profile");
388 389
    }
    
390
    #
391
    # Sanity checks. 
392
    #
393
    my @aggs = $instance->AggregateList();
394 395
    if (! @aggs) {
	fatal("No slivers for instance!");
396
    }
397
    if (!defined($node_id)) {
398
	# We snapshot the one node in the instance.
399 400 401 402 403 404 405 406 407
	if (@aggs != 1) {
	    fatal("Too many aggregates (> 1) to snapshot");
	}
	my ($agg) = @aggs;
	my $manifest = GeniXML::Parse($agg->manifest());
	if (! defined($manifest)) {
	    fatal("Could not parse manifest for $agg");
	}
	my @nodes = GeniXML::FindNodes("n:node", $manifest)->get_nodelist();
408 409 410
	if (@nodes != 1) {
	    fatal("Too many nodes (> 1) to snapshot");
	}
411
	($node)     = @nodes;
412
	$sliver_urn = GeniXML::GetSliverId($node);
413 414
	$node_id    = GeniXML::GetVirtualId($node);
	$aggregate  = $agg;
415 416 417
	# Profile Snapshot, always use the profile name. Clone passes in name.
	if (!defined($imagename)) {
	    $imagename = $profile->name();
418
	}
419
    }
420
    else {
421 422
	my $nodecount = 0;
	
423 424 425 426 427 428 429 430
	# Find the node in its manifest.
	foreach my $agg (@aggs) {
	    my $manifest = GeniXML::Parse($agg->manifest());
	    if (! defined($manifest)) {
		fatal("Could not parse manifest for $agg");
	    }
	    foreach my $ref (GeniXML::FindNodes("n:node",
						$manifest)->get_nodelist()) {
431 432
		$nodecount++;
		
433 434 435
		my $client_id   = GeniXML::GetVirtualId($ref);
		my $manager_urn = GetManagerId($ref);
		my $urn          = GeniXML::GetSliverId($ref);
436 437 438

		# No sliver urn or a different aggregate.
		next
439 440 441
		    if (! (defined($urn) &&
			   defined($manager_urn) &&
			   $manager_urn eq $agg->aggregate_urn()));
442 443 444 445 446 447 448

		if ($node_id eq $client_id) {
		    $node = $ref;
		    $sliver_urn = $urn;
		    $aggregate = $agg;
		    last;
		}
449 450 451 452
	    }
	}
	if (!defined($sliver_urn)) {
	    fatal("Could not find node '$node_id' in manifest");
453
	}
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
	#
	# So, we want Profile snapshot above (of a single node profile) and
	# Node snapshot in a single node profile to behave the same wrt the
	# image name, so look at the nodecount to see if need to append the
	# nodeid to the imagename. 
	#
	if (!defined($imagename)) {
	    $imagename = $profile->name();
	    if ($nodecount > 1) {
		$imagename .= "." . $node_id;
	    }
	}
    }
    #
    # Make sure a valid imagename. This a local test of course, but this
    # only works on IG aggregates anyway.
    #
    if (! TBcheck_dbslot($imagename, "images",
			 "imagename", TBDB_CHECKDBSLOT_ERROR)) {
473 474 475
	$errmsg   = "Invalid imagename: " . TBFieldErrorString() . "\n";
	$errcode  = GENIRESPONSE_ERROR;
	$exitcode = 1;
476
	goto uerror;
477 478
    }
    
479
    #
480 481 482
    # Instruct the remote cluster to copy the image back to its origin,
    # but we need to ask the IMS for uuid of the image that is running,
    # so we can tell the cluster, which then tells the origin cluster.
483 484
    # We also need to know what the new URN of the image will be, for
    # updating the profile. 
485 486 487 488 489 490
    #
    if (GetSiteVar("protogeni/use_imagetracker") &&	
	EmulabFeatures->FeatureEnabled("APT_UseImageTracker",
					   $this_user, $project)) {
	$usetracker = 1;

491 492 493 494
	#
	# When cloning, we use the URN returned by the cluster; it is
	# the origin of the new image.
	#
495 496
	if (!defined($cloneprofile)) {
	    my $rval = DoImageTrackerStuff($aggregate, $node, $project,
497
					   $imagename,
498 499 500 501 502 503 504
					   \$copyback_uuid, \$copyback_urn,
					   \$errmsg);
	    if ($rval) {
		if ($rval < 0) {
		    fatal($errmsg);
		}
		else {
505 506
		    $errcode  = GENIRESPONSE_ERROR;
		    $exitcode = 1;
507 508 509
		    goto uerror;
		}
	    }
510 511 512 513
	}
    }
    if (0) {
	fatal("$copyback_uuid, $copyback_urn\n");
514 515
    }

516
    #
517 518 519
    # We are not going to allow this if the instance is on a different
    # cluster then where the image was originally created, since otherwise
    # the image provenancewill look like spaghetti. 
520
    #
521
    if (defined($update_profile)) {
522 523
	my $diskref = GeniXML::GetDiskImage($node);
	if (defined($diskref)) {
524
	    my $authority = $aggregate->GetGeniAuthority();
525
	    my $image_url = GeniXML::GetText("url", $diskref);
526
	    if (defined($image_url) && !$usetracker) {
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
		require URI;

		# Get the hostname for the image URL.
		my $uri = URI->new($image_url);
		if (!defined($uri)) {
		    fatal("Could not parse $image_url");
		}
		my $image_host = $uri->host();

		# Get the hostname for the authority.
		$uri = URI->new($authority->url());
		if (!defined($uri)) {
		    fatal("Could not parse authority URL");
		}
		my $authority_host = $uri->host();

		# Compare domains.
		$image_host =~ s/^([^.]+\.)//;
		$authority_host =~ s/^([^.]+\.)//;
	
		if ($image_host ne $authority_host) {
		    $errmsg  = "Not allowed to take a snapshot on this cluster";
549 550
		    $errcode  = GENIRESPONSE_ERROR;
		    $exitcode = 1;
551
		    goto uerror;
552 553 554
		}
	    }
	}
555 556 557 558
	# Do this here to avoid output to logfile.
	$doversions =
	    EmulabFeatures->FeatureEnabled("APT_ProfileVersions",
					   $this_user, $project);
559 560
    }
    if ($slice->Lock()) {
561
	$errmsg  = "Experiment is busy, please try again later.";
562 563
	$errcode = GENIRESPONSE_BUSY;
	$exitcode = 1;
564
	goto uerror;
565 566
    }
    $needunlock = 1;
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    if (!$nosnapshot) {
	#
	# Grab the webtask, but only after we have it locked, since we are
	# going to modify it. This is a different webtask then the one we
	# got on the command line. The command line webtask is for reporting
	# he results of the command, while the instance webtask is used to
	# report ongoing status of the imaging operation (to the web UI).
	#
	$swebtask = $instance->webtask();
	# We reuse this so clear it.
	$swebtask->Reset();
	$swebtask->AutoStore(1);
	# These are for the web server (imaging status).
	$swebtask->aggregate_urn($aggregate->aggregate_urn());
	$swebtask->client_id($node_id);
	$swebtask->operation($operation) if (defined($operation));
	$swebtask->imagename($imagename);
	
	$instance->SetStatus("imaging");
	$aggregate->SetStatus("imaging");
    }
589

590 591 592
    # Shorten default timeout
    Genixmlrpc->SetTimeout(60);
    
593 594
    #
    # This returns pretty fast, and then the imaging takes place in
595
    # the background at the aggregate. 
596
    #
597
    my $response =
598
	$aggregate->CreateImage($sliver_urn, $imagename,
599
				$update_prepare, $copyback_uuid,
600
				undef, $nosnapshot, $mustnotexist, $wholedisk);
601
    if ($response->code() != GENIRESPONSE_SUCCESS) {
602 603 604 605 606 607 608
	$errcode = $response->code();
	($exitcode,$errmsg) = ResponseErrorMessage($aggregate, $response);
	# Important to tell web user about these.
	if ($response->code() == GENIRESPONSE_NOSPACE ||
	    $response->code() == GENIRESPONSE_ALREADYEXISTS) {
	    $exitcode = 1;
	}
609 610 611 612
	if (!$nosnapshot) {
	    $instance->SetStatus($old_status);
	    $aggregate->SetStatus($old_status);
	}
613
	goto uerror;
614 615 616
    }
    my ($image_urn, $image_url,
	$version_urn, $version_url) = @{ $response->value() };
617 618 619 620
    #
    # For version zero, kill the version number.
    #
    if (!defined($version_urn) || $version_urn =~ /:0$/) {
621 622 623
	$version_urn = $image_urn;
	$version_url = $image_url
    }
624
    my $image_name;
625

626 627 628 629 630 631
    # When using the image server we use URNs. 
    if ($usetracker) {
	# DoImageTrackerStuff determined that we use whatever the cluster
	# tells us, cause it is the home of the image.
	if (!defined($copyback_urn)) {
	    $image_name = $version_urn;
Leigh Stoller's avatar
Leigh Stoller committed
632 633
	}
	else {
634
	    $image_name = $copyback_urn;
Leigh Stoller's avatar
Leigh Stoller committed
635
	}
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
    }
    elsif ($aggregate->OnLocalCluster()) {
	$image_name = $version_urn;
    }
    else {
	$image_name = $version_url;
    }
    
    if ($nosnapshot) {
	if (defined($webtask)) {
	    $webtask->image_urn($version_urn);
	    $webtask->image_url($version_url);
	    $webtask->image_name($image_name);
	}
	print "$version_urn,$version_url,$image_name\n";
	$slice->UnLock();
	exit(0);
    }
    if (defined($swebtask)) {
	$swebtask->image_urn($version_urn);
	$swebtask->image_url($version_url);
657
	$swebtask->image_name($image_name);
658

Leigh Stoller's avatar
Leigh Stoller committed
659 660 661
	# We tell the web interface that the image has to be copied
	# back,
	if (defined($copyback_uuid)) {
662
	    $swebtask->copyback_uuid($copyback_uuid);
Leigh Stoller's avatar
Leigh Stoller committed
663
	}
664
    }
665
    print "$version_urn,$version_url,$image_name\n";
666 667 668 669 670

    #
    # Exit and leave child to poll.
    #
    if (! $debug) {
671 672 673 674
        $logfile = TBMakeLogname("snapshot");
	
	if (my $childpid = TBBackGround($logfile)) {
	    # Parent exits normally, web interface watches.
675 676 677 678 679
	    exit(0);
	}
	# Let parent exit;
	sleep(2);
    }
680 681
    # Bind the process id. This is important when the caller is
    # manage_profile, doing a clone.
682 683
    $webtask->SetProcessID($PID)
	if (defined($webtask));
684 685 686 687

    #
    # Poll for a reasonable amount of time.
    #
688
    my $seconds  = 1500;
689
    my $interval = 15;
690
    my $ready    = 0;
691
    my $sliver_ready = 0;
692
    my $failed   = 0;
693

694
    while ($seconds > 0) {
695 696
	sleep($interval);
	$seconds -= $interval;
697
    
698
	my $response = $aggregate->SliceStatus();
699
	if ($response->code() != GENIRESPONSE_SUCCESS &&
700
	    $response->code() != GENIRESPONSE_NETWORK_ERROR &&
701
	    $response->code() != GENIRESPONSE_SERVER_UNAVAILABLE &&
702 703 704 705 706 707
	    $response->code() != GENIRESPONSE_BUSY) {
	    $errmsg = "Sliverstatus failed: ". $response->output() . "\n";
	    $failed = 1;
	    last;
	}
	next
708
	    if ($response->code() == GENIRESPONSE_BUSY ||
709
		$response->code() == GENIRESPONSE_SERVER_UNAVAILABLE ||
710
		$response->code() == GENIRESPONSE_NETWORK_ERROR);
711

712
	my $blob = $response->value();
713
	# This is the per-aggregate status, we always set this for web UI.
714
	$aggregate->UpdateSliverStatusAll($blob->{'details'});
715
	
716 717 718 719
	if ($blob->{'status'} eq "failed") {
	    $failed = 1;
	    last;
	}
720 721 722 723
	elsif ($blob->{'status'} eq "ready") {
	    $sliver_ready = 1;
	}
	
724 725 726
	#
	# We are watching for the image status to report ready or failed.
	#
727
	$response = $aggregate->ImageInfo($image_urn);
728
	if ($response->code() != GENIRESPONSE_SUCCESS &&
729
	    $response->code() != GENIRESPONSE_NETWORK_ERROR &&
730
	    $response->code() != GENIRESPONSE_SERVER_UNAVAILABLE &&
731 732 733 734 735 736
	    $response->code() != GENIRESPONSE_BUSY) {
	    $errmsg = "Imageinfo failed: ". $response->output() . "\n";
	    $failed = 1;
	    last;
	}
	next
737
	    if ($response->code() == GENIRESPONSE_BUSY ||
738
		$response->code() == GENIRESPONSE_SERVER_UNAVAILABLE ||
739
		$response->code() == GENIRESPONSE_NETWORK_ERROR);
740

741
	my $imageblob = $response->value();
742
	if (defined($swebtask)) {
743 744 745 746 747 748 749 750 751
	    my %blobcopy = %{ $imageblob };

	    #
	    # If the image is ready, but needs to be copied back to
	    # its origin, hold of ready till later. We will wait for
	    # the copyback to finish, see below.
	    #
	    if ($imageblob->{'status'} eq "ready" && defined($copyback_uuid)) {
		$blobcopy{'status'} = "copying";
Leigh Stoller's avatar
Leigh Stoller committed
752
	    }
753 754
	    # This is also being updated by the event system.
	    $instance->UpdateImageStatus(\%blobcopy);
755
	}
756
	if ($imageblob->{'status'} eq "ready") {
757 758 759
	    $ready = 1;
	    last;
	}
760
	elsif ($imageblob->{'status'} eq "failed") {
761 762 763
	    $failed = 1;
	    last;
	}
764
    }
765
    # Cause of image status events.
766 767
    $swebtask->Refresh()
	if (defined($swebtask));
768
    
769 770 771 772
    if ($failed) {
	$errmsg = "Imaging failed"
	    if (!defined($errmsg));
	goto bad;
773
    }
774 775
    elsif (!$ready) {
	$errmsg  = "Imaging timed out";
776
	$errcode = -2;
777 778
	goto bad;
    }
Leigh Stoller's avatar
Leigh Stoller committed
779 780 781 782 783 784
    #
    # We cannot change a geni-lib script profile, so no need to do this.
    # But we can change a portal converted profile.
    #
    elsif (defined($update_profile) &&
	   (!defined($profile->script()) || $profile->portal_converted())) {
785
	#
Leigh Stoller's avatar
Leigh Stoller committed
786 787
	# New image. Might not have changed if the cluster is not doing
	# image versions.
788
	#
789
	# DoImageTrackerStuff determined that we use whatever the cluster
790
	# tells us, cause it is the home of the image.
Leigh Stoller's avatar
Leigh Stoller committed
791 792
	#
	my $newimage = $version_urn
793
	    if ($usetracker && !defined($copyback_urn));
Leigh Stoller's avatar
Leigh Stoller committed
794 795 796
	# And fall back to url
	$newimage = $version_url
	    if (!defined($newimage));
797

Leigh Stoller's avatar
Leigh Stoller committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
	#
	# Okay, is the rspec going to change. This is kinda annoying to
	# figure out, so lets just run the code in impotent mode and have
	# it tell us the number of nodes that will get updated.
	#
	my $changed = 
	    $profile->UpdateDiskImage($node_id, $newimage,
				      ($update_profile eq "all" ? 1 : 0), 1);

	if ($changed > 0) {
	    #
	    # Create a new version of the profile and update the rspec
	    # to reflect the new image version. 
	    #
	    if ($doversions) {
		$profile = $profile->NewVersion($this_user);
		if (!defined($profile)) {
		    print STDERR "Could not create new profile version\n";
		    $webtask->Exited(70)
			if (defined($webtask));
		    exit(1);
		}
	    }
	    $profile->UpdateDiskImage($node_id, $newimage,
				      ($update_profile eq "all" ? 1 : 0), 0);
	    $profile->InsertImageRecords();
	    #
	    # For a portal converted profile, we need to regen the script.
	    #
	    if ($profile->portal_converted()) {
		if ($profile->Convert2Genilib() != 0) {
		    fatal("Could not convert rspec to geni-lib");
		}
	    }
	}
833
    }
834
    $instance->SetStatus("ready");
835
    $aggregate->SetStatus("ready");
Leigh Stoller's avatar
Leigh Stoller committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
    
    #
    # If there is a copyback_uuid, we want to wait for that to finish.
    #
    if (defined($copyback_uuid)) {
	#
	# We know the copyback is done when the IMS has the info.
	#
	my $copied  = 0;
	$seconds  = 1000;

	while ($seconds > 0) {
	    sleep($interval);
	    $seconds -= $interval;

	    #
	    # It would clearly be more more efficient to just look in
	    # the IMS database. 
	    #
	    Genixmlrpc->SetContext(APT_Geni::GeniContext());
	    my $blob = GeniImage::GetImageData($copyback_urn, \$errmsg);
	    Genixmlrpc->SetContext(undef);
	    # We get back undefined if the image is not posted yet.
	    if (defined($blob)) {
		$copied = 1;
		last;
	    }
	    sleep($interval);
	}
	# Tell the web interface. 
	if (!$copied) {
	    $errmsg  = "Failed to copy image back to its origin cluster";
	    $errcode = 1;
	    goto bad;
	}
871 872
	elsif (defined($swebtask)) {
	    $swebtask->image_status("ready");
Leigh Stoller's avatar
Leigh Stoller committed
873 874
	}
    }
875
    $swebtask->Exited(0);
876 877 878
    $webtask->Exited(0)
	if (defined($webtask));
    $slice->UnLock();
879
    
880 881 882 883 884 885 886
    if (defined($logfile)) {
	if (-s $logfile) {
	    SENDMAIL($TBOPS,
		     "Instance Snapshot Complete",
		     "Finished taking snapshot of $instance.\n",
		     $TBOPS, undef, $logfile);
	}
887 888
	unlink($logfile);
    }
889 890 891 892 893
    if (!$sliver_ready) {
	#
	# Image is ready, but sliver is not. Start a monitor so that
	# web interface is updated.
	#
Leigh Stoller's avatar
Leigh Stoller committed
894
	StartMonitorInternal();
895
    }
896
    exit(0);
897
  bad:
898
    if (!$sliver_ready) {
899
	#
900 901
	# Image is ready, but sliver is not. Start a monitor so that
	# web interface is updated.
902
	#
Leigh Stoller's avatar
Leigh Stoller committed
903
	StartMonitorInternal();
904
    }
905
    $instance->SetStatus("ready");
906
    $aggregate->SetStatus("ready");
907
    if (defined($logfile)) {
908 909 910 911 912
	SENDMAIL($TBOPS,
		 "Snapshot failed",
		 "Error taking snapshot of $instance:\n\n".
		 "$errmsg\n",
		 $TBOPS, undef, $logfile);
913 914
	unlink($logfile);
    }
915 916 917 918 919 920
  uerror:
    print STDERR "$errmsg\n";
    if (defined($errmsg) && defined($webtask)) {
	$webtask->Exited($errcode);
	$webtask->output($errmsg);
    }
921
    # For display in the imaging modal.
Leigh Stoller's avatar
Leigh Stoller committed
922 923 924 925
    if (defined($errmsg) && defined($swebtask)) {
	$swebtask->Exited($errcode);
	$swebtask->output($errmsg);
    }
926 927 928
    $slice->UnLock()
	if ($needunlock);

929
    exit($errcode);
930
}
931

932
sub DoImageTrackerStuff($$$$$$$)
933
{
934
    my ($aggregate, $node, $project, $newname, $puuid, $purn, $perrmsg) = @_;
935 936 937 938 939 940 941 942 943 944 945 946 947 948
    my $node_id = GeniXML::GetVirtualId($node);
    my $errmsg;

    #
    # If we do not have a diskinfo section, we will use the URN we get back
    # from the cluster (it is a snapshot of the default image).
    #
    my $diskinfo = GeniXML::GetDiskImage($node);
    return 0
	if (!defined($diskinfo));

    #
    # This one needs more thought, it might be a URL.
    #
949 950 951 952 953
    my $image_token = GeniXML::GetText("name", $diskinfo);
    if (!defined($image_token)) {
	$image_token = GeniXML::GetText("url", $diskinfo);
	return 0
	    if (!defined($image_token));
954
    }
955 956 957
    if (GeniHRN::IsValid($image_token)) {
	my ($auth,$ospid) = GeniHRN::ParseImage($image_token);
	if (!defined($ospid)) {
958
	    $$perrmsg = "Invalid image urn: $image_token";
959 960 961 962
	    return 1;
	}
    }
    
963
    Genixmlrpc->SetContext(APT_Geni::GeniContext());
964
    my $blob = GeniImage::GetImageData($image_token, \$errmsg);
965 966 967
    Genixmlrpc->SetContext(undef);
    
    if (!defined($blob)) {
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	if (GeniHRN::IsValid($image_token)) {
	    #
	    # See if this is for a system image (emulab-ops). If it is,
	    # and the domain is not the MS, then retry with a MS URN.
	    #
	    # This is sorta temporary; at some point there will not be any
	    # profiles using the URNs that are not in the image tracker.
	    # Of course a user is free to set the URN to anything the want,
	    # which is why I expect this code to be here for a while. 
	    #
	    my $urn;
	    my $hrn = GeniHRN->new($image_token);
	    my ($auth,$ospid,$os,$vers) = $hrn->ParseImage();
	    if ($ospid eq TBOPSPID() && $auth ne "emulab.net") {
		$urn = GeniHRN::GenerateImage("emulab.net",
						 TBOPSPID(), $os, $vers);
984 985 986
		Genixmlrpc->SetContext(APT_Geni::GeniContext());
		$blob = GeniImage::GetImageData($urn, \$errmsg);
		Genixmlrpc->SetContext(undef);
987 988 989
	    }
	}
	if (!defined($blob)) {
990 991 992
	    $$perrmsg = "Could not get info from the image server for ".
		"$image_token:\n" . $errmsg;
	    return 1;
993
	}
994 995
    }
    #
996
    # System Image? We use the URN we get back from CreateImage().
997 998 999
    # The cluster will be the origin for the new image.
    #
    return 0
1000 1001 1002 1003
	if (exists($blob->{'issystem'}) && $blob->{'issystem'});
    # Image aliases are also considered system images.
    return 0
	if (exists($blob->{'isimagealias'}) && $blob->{'isimagealias'});
1004

1005
    my $image_urn     = $blob->{'urn'};
1006 1007 1008 1009
    my $copyback_uuid = $blob->{'version_uuid'};
    my $copyback_urn  = $image_urn;

    my $hrn = GeniHRN->Parse($image_urn);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    if (!defined($hrn)) {
	$$perrmsg = "Could not parse $image_urn\n";
	return -1;
    }
    if (!$hrn->IsImage()) {
	$$perrmsg = "$image_urn is not an image URN\n";
	return -1;
    }
    my $projhrn = GeniHRN->Parse($blob->{'project_urn'});
    if (!defined($projhrn)) {
	$$perrmsg = "Could not parse " . $blob->{'project_urn'} . "\n";
	return -1;
    }

    #
    # Whenever we cross projects, we expect the cluster to create
    # a new image. We use the URN that is returned.
    #
    if (lc($projhrn->subauth()) ne lc($project->pid())) {
	# We use the URN we get back from CreateSliver().
	return 0;
    }
1032 1033 1034 1035

    #
    # What happens if the user is doing a snapshot on the cluster where
    # the image lives? The copyback (import) makes no sense in that case,
1036
    # We can use the URN the cluster returns.
1037
    #
1038
    if (lc($hrn->domain()) eq lc($aggregate->domain())) {
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
	return 0;
    }

    #
    # Different cluster
    #
    # Is this node currently running a different image then what
    # the new name will be? Is so, then we expect the cluster to
    # start a new image and we use the URN it returns.
    #
    if ($newname ne $hrn->osname()) {
1050
	return 0;
1051 1052 1053 1054 1055
    }

    #
    # If we are going to update the profile, we need to know what to
    # change the image urn to, and that depends on what version the
1056 1057 1058 1059 1060
    # image is currently at, AT THE ORIGIN CLUSTER. The urn we get back
    # from the snapshotting cluster is not what we care about, we need
    # a urn for the origin cluster. But that depends on what version the
    # origin cluster is at (the highest numbered version). But if we are
    # doing a snapshot of an earlier version, we cannot generate the
1061
    # version here, we have to ask what it will be. 
1062 1063
    #
    if ($blob->{'isversioned'}) {
1064
	$copyback_urn = GeniHRN::GenerateImage($hrn->authority(),
1065 1066
					       $hrn->ospid(),
					       $hrn->osname(),
1067
					       $blob->{'maxversion'} + 1);
1068 1069 1070 1071 1072 1073
    }
    $$puuid = $copyback_uuid;
    $$purn  = $copyback_urn;
    return 0;
}

1074 1075 1076 1077 1078
#
# Ask the console URL for a node in an instance.
#
sub DoConsole()
{
1079
    my $errmsg;
1080
    usage()
1081 1082
	if (!@ARGV);
    my $node_id = shift(@ARGV);
1083

1084 1085 1086 1087 1088
    #
    # Sanity check to make sure the node is really in the rspec, since
    # we need its sliver urn to ask for the console url.
    #
    my $sliver_urn;
1089
    my $sliver;
1090
    foreach my $obj ($instance->AggregateList()) {
1091 1092 1093 1094
	my $manifest = GeniXML::Parse($obj->manifest());
	if (! defined($manifest)) {
	    fatal("Could not parse manifest for $obj");
	}
1095 1096 1097
	my @nodes = (GeniXML::FindNodes("n:node", $manifest)->get_nodelist(),
		     GeniXML::FindNodesNS("n:vhost", $manifest,
					  $GeniXML::EMULAB_NS)->get_nodelist());
1098
	foreach my $node (@nodes) {
1099 1100 1101
	    my $client_id   = GeniXML::GetVirtualId($node);
	    my $urn         = GeniXML::GetSliverId($node);
	    my $manager_urn = GetManagerId($node);
1102 1103 1104

	    # No sliver urn or a different aggregate.
	    next
1105 1106 1107
		if (! (defined($urn) &&
		       defined($manager_urn) &&
		       $manager_urn eq $obj->aggregate_urn()));
1108 1109

	    if ($node_id eq $client_id) {
1110
		$sliver_urn = $urn;
1111 1112
		$sliver = $obj;
	    }
1113 1114 1115 1116 1117
	}
    }
    if (!defined($sliver_urn)) {
	fatal("Could not find node '$node_id' in manifest");
    }
1118 1119 1120 1121 1122 1123 1124
    if ($sliver->GetAptAggregate()->CheckStatus(\$errmsg)) {
	print STDERR "$errmsg\n";
	if (defined($webtask)) {
	    $webtask->output($errmsg);
	    $webtask->Exited(GENIRESPONSE_SERVER_UNAVAILABLE);
	}
	exit(1);
1125
    }
1126 1127
    my $response = $sliver->ConsoleInfo($sliver_urn);

1128
    if ($response->code() == GENIRESPONSE_RPCERROR) {
1129
	print STDERR "RPC Error: " . $response->error() . "\n";
1130
	if (defined($webtask)) {
1131
	    $webtask->output($response->error());
1132 1133
	    $webtask->Exited($response->code());
	}
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
	exit(-1);
    }
    if ($response->code() == GENIRESPONSE_NETWORK_ERROR ||
	$response->code() == GENIRESPONSE_SERVER_UNAVAILABLE) {
	print STDERR "RPC Error: " . $response->error() . "\n";
	if (defined($webtask)) {
	    $webtask->output($response->error());
	    $webtask->Exited($response->code());
	}
	exit(1);
1144
    }
1145 1146 1147 1148
    if ($response->code() == GENIRESPONSE_UNAVAILABLE) {
	print STDERR "Server says there is no console for $node_id\n";
	if (defined($webtask)) {
	    $webtask->output("Sorry, $node_id does not have a console line");
1149 1150
	    $webtask->Exited($response->code());
	}
1151
	exit(1);
1152 1153 1154 1155 1156
    }
    if ($response->code() == GENIRESPONSE_SEARCHFAILED) {
	print STDERR "Server says $node_id has been deallocated\n";
	if (defined($webtask)) {
	    $webtask->output("Sorry, $node_id has been deallocated");
1157 1158
	    $webtask->Exited($response->code());
	}
1159
	exit(1);
1160
    }
1161 1162 1163 1164 1165 1166
    if ($response->code() == GENIRESPONSE_FORBIDDEN) {
	print STDERR "Server says access to $node_id console is forbidden\n";
	if (defined($webtask)) {
	    $webtask->output("Sorry, access to $node_id console is forbidden");
	    $webtask->Exited($response->code());
	}
1167
	exit(1);
1168
    }
1169 1170 1171 1172 1173
    if ($response->code() == XMLRPC_NO_SUCH_METHOD) {
	print STDERR "Server does not support console access\n";
	if (defined($webtask)) {
	    $webtask->output("Sorry, server does not support console access");
	    $webtask->Exited(GENIRESPONSE_NOT_IMPLEMENTED);
1174
	}
1175 1176 1177 1178
	exit(1);
    }
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	fatal($response->error());
1179 1180 1181
    }
    my $url;
    my $pswd;
1182
    my $logurl;
1183 1184 1185 1186 1187
	
    if (ref($response->value())) {
	$url  = $response->value()->{'url'};
	$pswd = $response->value()->{'password'}
	    if (exists($response->value()->{'password'}));
1188 1189 1190 1191
	$logurl = $response->value()->{'logurl'}
	    if (exists($response->value()->{'logurl'}));

	print Dumper($response->value());
1192 1193 1194
    }
    else {
	$url = $response->value();
1195
    }
1196
    if (defined($webtask)) {
1197
	if ($response->code()) {
1198
	    $webtask->output($response->error());
1199 1200 1201 1202
	}
	else {
	    $webtask->url($url);
	    $webtask->password($pswd) if (defined($pswd));
1203
	    $webtask->logurl($logurl) if (defined($logurl));
1204
	}
1205
	$webtask->Exited($response->code());
1206
	exit($response->code());
1207 1208 1209
    }
    # For command line operation too.
    if ($response->code()) {
1210
	fatal($response->error());
1211
    }
1212 1213
    print $url . "\n";
    print $pswd . "\n" if (defined($pswd));
1214
    print $logurl . "\n" if (defined($logurl));
1215 1216
    exit(0);
}
1217

1218 1219 1220 1221 1222 1223
#
# Terminate
#
sub DoTerminate()
{
    my $errmsg;
1224 1225
    my $errcode;
    my $exitcode = 1;
1226
    my $logfile;
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    my $expired = $RECORDHISTORY_TERMINATED;

    if (@ARGV) {
	my $arg = shift(@ARGV);
	if ($arg eq "-e") {
	    $expired = $RECORDHISTORY_EXPIRED;
	}
	else {
	    usage();
	}
    }
1238 1239 1240
    
    my $slice = $instance->GetGeniSlice();
    if (!defined($slice)) {
1241 1242 1243 1244
	#
	# No slice (typically) means we never got far enough to the
	# get the sliver created on the backend cluster.
	#
1245 1246 1247 1248 1249 1250 1251
	goto killit;
    }
    #
    # Lock the slice in case it is doing something else, like taking
    # a disk image.
    #
    if ($slice->Lock()) {
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
	#
	# A special case is if the slice is provisioning. This means the
	# user is giving up on it, and we want to tell the aggregate to
	# kill it. Not all aggregates are going to allow this, so need
	# to be able to deal with that.
	#
	if ($instance->status() ne "provisioned") {
	    fatal("Slice is busy, cannot lock it");
	}
	if (!$instance->canceled()) {
	    print "Marking instance canceled\n";
	    $instance->MarkCanceled();
	}
	sleep(1);
	# We have an obvious race here since we do not have the lock.
	exit(0);
1268 1269 1270 1271 1272 1273 1274
    }
    my $old_status = $instance->status();
    $instance->SetStatus("terminating");

    #
    # Exit and let caller poll for status.
    #
1275
    if (!$debug) {
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        $logfile = TBMakeLogname("terminate");
	
	if (my $childpid = TBBackGround($logfile)) {
	    my $status = 0;
	    #
	    # Wait a couple of seconds to see if there is going to be an
	    # immediate error. Then return and let it continue to run. This
	    # allows the web server to see quick errors. Later errors will
	    # have to be emailed. 
	    #
1286
	    sleep(5);
1287 1288 1289 1290 1291 1292 1293
	    my $foo = waitpid($childpid, &WNOHANG);
	    if ($foo) {
		$status = $? >> 8;
	    }
	    exit($status);
	}
    }
1294

1295 1296 1297 1298 1299 1300 1301
    # Skip terminated aggregates, since we retry later on failure.
    my @agglist;
    foreach my $agg ($instance->AggregateList()) {
	push(@agglist, $agg)
	    if ($agg->status() ne "terminated");
    }
    my $response;
1302

1303 1304 1305 1306 1307
    $errcode = CallMethodOnAggregates("Terminate", 10, \$response, @agglist);
				      
    if ($errcode) {
	$exitcode = -1;
	$errmsg   = $response;
1308 1309
	goto bad;
    }
1310

1311
    #
1312
    # Look at all the responses, update the status. 
1313
    #
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    my @responses = @{$response};
    foreach my $agg (@agglist) {
	my $response = shift(@responses);
	my $code = $response->code();

	# SEARCHFAILED is success too
	if ($code == GENIRESPONSE_SUCCESS ||
	    $code == GENIRESPONSE_SEARCHFAILED) {
	    $agg->SetStatus("terminated");
	    next;
	}
	($exitcode,$errmsg) = ResponseErrorMessage($agg, $response);
	
	#
	# These will typically clear up at some point so abort
	# sending any email.
	#
	if ($code == GENIRESPONSE_BUSY ||
	    $code == GENIRESPONSE_SERVER_UNAVAILABLE ||
	    $code == GENIRESPONSE_NETWORK_ERROR) {
	    if (defined($logfile)) {
		unlink($logfile);
		$logfile = undef;
	    }
	    $errcode  = $code;
	    $exitcode = 1;
	}
	else {
	    # We are going to send mail below, so exit with positive status
	    # so web interface does not send email.
	    $errcode  = $code;
	    $exitcode = 1;
1346 1347
	}
    }
1348 1349 1350 1351 1352
    # Will have to try again later.
    goto bad
	if ($errcode);

    $instance->SetStatus("terminated");
1353
    $slice->Delete();
1354
    $instance->RecordHistory($expired);
1355 1356 1357 1358 1359
  killit:
    $instance->Delete();
    unlink($logfile)
	if (defined($logfile));
    exit(0);
1360
    
1361 1362 1363
  bad:
    print STDERR $errmsg . "\n";
    $instance->SetStatus($old_status);
1364
    if (defined($logfile)) {
1365 1366
	my $instance_name = $instance->name();
	my $slice_uuid    = $slice->uuid();
1367 1368
	SENDMAIL($TBOPS,
		 "Unable to terminate instance $uuid",
1369 1370
		 "Name: $instance_name\n".
		 "Slice: $slice_uuid\n\n".
1371
		 "$errmsg\n",
1372 1373
		 $TBOPS, undef, $logfile)
	    if (!$silent);
1374 1375
	unlink($logfile);
    }
1376 1377 1378 1379
    if (defined($webtask)) {
	$webtask->output($errmsg);
	$webtask->Exited($errcode);
    }
1380 1381 1382 1383 1384
    #
    # Also, mark the instance as canceled so that the apt daemon will
    # pick it up later (for the case that the instance is not expired)
    #
    $instance->MarkCanceled();
1385 1386
    $slice->UnLock();
    exit($exitcode);
1387 1388 1389
}

#
1390
# Request an extension; all this code used to be in PHP, that was silly.
1391 1392
#
sub DoExtend()
1393
{
1394
    my $force    = 0;
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    my $errcode  = 1;
    my $autoextend_maximum = GetSiteVar("aptui/autoextend_maximum");
    my $autoextend_maxage  = GetSiteVar("aptui/autoextend_maxage");
    my $autoextend_freedays= 2;
    my $creator       = $instance->GetGeniUser();
    my $slice         = $instance->GetGeniSlice();
    my $name          = $instance->name();
    my $url           = $instance->webURL();
    my $clusters      = join(",", map { $_->domain() }
			     $instance->AggregateList());
1405
    my $pcount        = $instance->physnode_count();
1406 1407 1408 1409 1410
    my $expires_time  = str2time($slice->expires());
    my $created_time  = str2time($instance->created());
    my $extensions    = $instance->Brand()->ExtensionsEmailAddress();
    my $granted       = 0;
    my $needapproval  = 0;
1411
    my $autoapprove_info;