status.ajax 51.7 KB
Newer Older
1 2
<?php
#
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
# 
# {{{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/>.
# 
# }}}
#
chdir("..");
25
include_once("webtask.php");
26 27 28 29 30 31 32 33 34 35 36 37
include_once("geni_defs.php");
chdir("apt");
include_once("profile_defs.php");
include_once("instance_defs.php");

# Set these globals below.
$instance = null;
$creator  = null;

#
# Locate the objects and check permission.
#
38
function StatusSetupAjax($needmodify)
39 40 41 42 43 44 45 46 47 48 49
{
    global $this_user, $ajax_args;
    global $instance, $creator;

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing instance uuid");
	return 1;
    }
    $uuid = $ajax_args["uuid"];
    $instance = Instance::Lookup($uuid);
    if (!$instance) {
50 51
	SPITAJAX_ERROR(GENIRESPONSE_SEARCHFAILED,
                       "no such instance uuid: $uuid");
52 53 54 55 56 57 58 59 60 61
	return 1;
    }
    $creator = GeniUser::Lookup("sa", $instance->creator_uuid());
    if (! $creator) {
	$creator = User::LookupByUUID($instance->creator_uuid());
    }
    if (!$creator) {
	SPITAJAX_ERROR(1, "no such instance creator");
	return 1;
    }
62
    # Admin users do whatever they like.
63 64 65
    if (isset($this_user) && ISADMIN()) {
	return 0;
    }
66 67 68 69
    # Foreign admins can look.
    if (isset($this_user) && ISFOREIGN_ADMIN() && !$needmodify) {
	return 0;
    }
70 71 72 73 74 75 76 77 78 79 80 81 82 83
    # For a guest user; must be the same guest that created experiment.
    if (get_class($creator) == "GeniUser") {
        if (isset($_COOKIE['quickvm_user']) &&
            $_COOKIE['quickvm_user'] == $creator->uuid()) {
            return 0;
        }
	SPITAJAX_ERROR(1, "You do not have permission!");
	return 1;
    }
    # An experiment created by a real user, can be accessed by other
    # members of the project, subject to modify restrictions.
    if (! (isset($this_user) && get_class($creator) == "User" &&
           $instance->CanView($this_user) &&
           (!$needmodify || $instance->CanModify($this_user)))) {
84 85 86 87 88 89 90 91 92 93 94
	SPITAJAX_ERROR(1, "You do not have permission!");
	return 1;
    }
    return 0;
}

#
# Status/
#
function Do_GetInstanceStatus()
{
95
    global $instance, $creator, $APTBASE;
96

97
    if (StatusSetupAjax(0)) {
98 99
	return;
    }
100 101
    $blob = array();
    $blob["status"] = $instance->status();
102
    $blob["canceled"] = $instance->canceled() ? 1 : 0;
103 104
    $blob["sliverstatus"] = array();
    $blob["sliverurls"]   = array();
105 106 107 108 109

    if ($instance->logfileid()) {
        $blob["logfile_url"] =
            "$APTBASE/spewlogfile.php?logfile=" . $instance->logfileid();
    }
110
    
111 112 113 114
    #
    # If we have all of our manifests, the client can request them
    # and show the topology.
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
115
    $havemanifests = $instance->slivers() ? 1 : 0;
116
    # Openstack experiment?
117
    $haveopenstack = $instance->isopenstack() ? 1 : 0;
118 119 120 121 122 123

    foreach ($instance->slivers() as $sliver) {
        if (!$sliver->manifest()) {
            $havemanifests = 0;
        }
        else {
124 125 126 127 128 129
            $statusblob  = array();

            foreach ($sliver->StatusArray() as $status) {
                if (isset($status["sliver_data"])) {
                    $statusblob[$status["client_id"]]
                        = $status["sliver_details"];
130
                }
131
            }
132
            $blob["sliverstatus"][$sliver->aggregate_urn()] = $statusblob;
133
        }
134
        if ($sliver->public_url()) {
135 136
            $blob["sliverurls"][] = array("name" => $sliver->aggregate_name(),
                                          "url"  => $sliver->public_url());
137
        }
138
    }
139
    $blob["havemanifests"] = $havemanifests;
140
    $blob["haveopenstackstats"] = $haveopenstack;
141 142

    # Reflect errors back to the user.
143
    $webtask = $instance->WebTask();
144
    if ($webtask && $webtask->exited()) {
145 146
        $blob["code"] = $webtask->exitcode();
        
147
        if ($webtask->exitcode() == GENIRESPONSE_INSUFFICIENT_NODES) {
148 149
            # All the info in the results from the cluster.
            $blob["reason"]  = "";
150
        }
151
        elseif ($webtask->exitcode() == GENIRESPONSE_INSUFFICIENT_BANDWIDTH) {
152 153
            $blob["reason"]  = "Not enough available bandwidth for a link.\n\n";
        }
154 155 156 157 158 159 160 161 162
        elseif ($webtask->exitcode() == GENIRESPONSE_NO_CONNECT) {
            $blob["reason"]  = "Could not map all requested links to physical ".
	    "resources. Not enough free resources currently. ".
	    "Please try again later.\n\n";
	}
        elseif ($webtask->exitcode() == GENIRESPONSE_MAPPING_IMPOSSIBLE) {
            $blob["reason"]  = "Your topology cannot instantiated. ".
	    "You have most likely asked for hardware that does not exist.\n\n";
        }
163
        elseif ($webtask->exitcode() == GENIRESPONSE_NO_MAPPING) {
164
            $blob["reason"]  = "Your topology could not be mapped to physical ".
165 166
                "resources. In addition to any information below, you can ".
                "click on the 'Sliver' button above, which will provide ".
Leigh B Stoller's avatar
Leigh B Stoller committed
167 168
                "lots of info, some of which might be useful in figuring out ".
                "why it failed.\n\n";
169
        }
170
        elseif ($webtask->exitcode() == GENIRESPONSE_TIMEDOUT) {
171 172 173
            $blob["reason"]  = "Your experiment timed out while setting up, ".
                "most likely because one or more nodes failed to boot. The ".
                "node consoles may provide more information.\n\n";
174
        }
175
        elseif ($webtask->exitcode() == GENIRESPONSE_BADARGS) {
176 177 178 179 180 181
            #
            # This is GENIRESPONSE_BADARGS which typically means an error
            # in the input rspec, something the user must have put in it.
            #
            $blob["reason"]  = "Your topology source contains invalid ".
                "values.\n\n";
182
        }
183 184 185 186 187 188 189 190 191
        elseif ($webtask->exitcode() == GENIRESPONSE_NOSPACE) {
            #
            # Over Quota.
            #
            $blob["reason"]  = "You are over your disk quota at the target ".
                "cluster, probably because of too many saved disk images. ".
                "Please click on the 'Storage->My Disk Images' above and delete ".
                "images you no longer need.";
        }
192 193 194 195 196 197 198 199
        elseif ($webtask->exitcode() == GENIRESPONSE_STITCHER_ERROR) {
            #
            # This is GENIRESPONSE_STITCHER_ERROR which is a catch all.
            #
            $blob["reason"]  = "Your multi-site topology could not be ".
                "stitched together. Please look closely at the ".
                "error message below to see what went wrong.\n\n";
        }
200
        else {
201
            $blob["reason"] = "";
202
        }
203
        $blob["reason"] .= htmlentities($webtask->TaskValue("output"));
204 205 206
        $blob["canclearerror"]
            = ($webtask->exitcode() ==
               GENIRESPONSE_SETUPFAILURE_BOOTFAILED ? 1 : 0);
207
    }
208
    SPITAJAX_RESPONSE($blob);
209 210 211 212 213 214 215
}

#
# Terminate.
#
function Do_TerminateInstance()
{
216
    global $instance, $creator, $this_user, $ajax_args;
217

218 219
    # Check for read permission, and then check for Terminate permission.
    if (StatusSetupAjax(0)) {
220 221
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
222
    if (!(ISADMIN() || $instance->CanTerminate($this_user))) {
223 224 225
        SPITAJAX_ERROR(1, "Not enough permission to terminate");
        return;
    }
226
    $uuid = $instance->uuid();
227

228 229 230 231 232 233 234
    if ($instance->admin_lockdown()) {
        SPITAJAX_ERROR(1, "This experiment has been locked down by an ".
                       "administrator. The lock must be cleared before ".
                       "it can terminated.");
        return;

    }
235 236 237
    $webtask = WebTask::CreateAnonymous();
    $webtask_id = $webtask->task_id();

238
    if ($instance->user_lockdown()) {
239 240 241
        if (! (isset($this_user) &&
               ($instance->creator() == $this_user->uid() || ISADMIN()))) {
            SPITAJAX_ERROR(1, "Not enough permission to terminate; ".
242
                           "experiment is locked down.");
243
            $webtask->Delete();
244 245 246
            return;
        }
        $override = substr($uuid, 2, 5);
247

248 249 250
        if (! (isset($ajax_args["lockdown_override"]) &&
               $ajax_args["lockdown_override"] == $override)) {
            SPITAJAX_ERROR(1, "Lockdown override is incorrect");
251
            $webtask->Delete();
252 253 254 255
            return;
        }
        $retval = SUEXEC($this_user->uid(), "nobody",
                         "webmanage_instance -t $webtask_id -- ".
256
                         "  lockdown $uuid clear user",
257 258
                         SUEXEC_ACTION_CONTINUE);
        if ($retval) {
259
            $webtask->Refresh();
260 261

            if ($webtask && $webtask->exited()) {
262
                SPITAJAX_ERROR(1, $webtask->output());
263 264 265 266
            }
            else {
                SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
            }
267
            $webtask->Delete();
268 269 270
            return;
        }
    }
271 272
    $webtask->Reset();
    
273 274 275
    # We do not want to see the busy errors, and that is the only error
    # that gets returned, that is not also emailed by the script. So just
    # use the ignore option.
276
    $retval = SUEXEC("nobody", "nobody",
277
                     "webmanage_instance -t $webtask_id terminate $uuid",
278
                     SUEXEC_ACTION_IGNORE);
279 280 281 282 283 284 285 286 287 288
    if ($retval) {
        $webtask->Refresh();
        if (!$webtask->exited() || $retval < 0) {
            # Email sent by manage_instance in this case.
            SPITAJAX_ERROR(-1, "Internal error terminating experiment");
        }
        else {
            SPITAJAX_ERROR(1, "Unable to terminate experiment at this time: " .
                           $webtask->output());
        }
289
    }
290
    else {
291
	SPITAJAX_RESPONSE("");
292 293
    }
    $webtask->Delete();
294 295 296 297 298 299 300 301 302
}

#
# Manifest.
#
function Do_GetInstanceManifest()
{
    global $instance, $creator;

303
    if (StatusSetupAjax(0)) {
304 305 306
	return;
    }

307 308 309 310 311 312 313 314
    $blob = array();

    foreach ($instance->slivers() as $sliver) {
        if ($sliver->manifest()) {
            $blob[$sliver->aggregate_urn()] = $sliver->manifest();
        }
    }
    SPITAJAX_RESPONSE($blob);
315 316 317 318 319 320 321
}

#
# SSH Auth Object
#
function Do_GetSSHAuthObject()
{
322
    global $instance, $creator, $this_user;
323 324 325 326 327 328 329 330
    global $ajax_args;

    if (!isset($ajax_args["hostport"])) {
	SPITAJAX_ERROR(1, "Missing hostport");
	return 1;
    }
    $hostport = $ajax_args["hostport"];
    
331
    if (StatusSetupAjax(0)) {
332 333
	return;
    }
334
    if (! ((isset($this_user) && $instance->CanDoSSH($this_user)) ||
Leigh B Stoller's avatar
Leigh B Stoller committed
335 336
	   (isset($_COOKIE['quickvm_user']) &&
	    $_COOKIE['quickvm_user'] == $creator->uuid()))) {
337 338
	SPITAJAX_ERROR(1, "Not allowed to ssh; ".
                       "only the creator or a project member");
339 340 341
	return;
    }
    
342
    $nodeid = $ajax_args["nodeid"];
343 344
    $auth   = SSHAuthObject(isset($this_user) ?
                            $this_user->uid() : $creator->uid(), $hostport);
345 346 347 348 349 350 351
    if (!$auth) {
	SPITAJAX_ERROR(1, "Could not create authentication object");
	return;
    }
    SPITAJAX_RESPONSE($auth);
}

352 353 354 355
function Do_RequestExtension()
{
    global $instance, $creator, $this_user, $suexec_output;
    global $ajax_args;
356
    $force   = 0;
357 358 359 360 361 362 363 364 365
    $autoextend_maximum = TBGetSiteVar("aptui/autoextend_maximum");

    if (StatusSetupAjax(1)) {
	goto bad;
    }
    if (isset($this_user)) {
        $project = Project::Lookup($instance->pid_idx());
        if ($project) {
            $group = $project->DefaultGroup();
366 367
            if (!(ISADMINISTRATOR() ||
                  FeatureEnabled("NewPortalExtend", $this_user, $group))) {
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
                return Do_RequestExtensionOld();
            }
        }
    }
    $uuid = $instance->uuid();
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
    if (!slice) {
	SPITAJAX_ERROR(1, "no slice for instance");
	goto bad;
    }

    if ($autoextend_maximum == 0 && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Extensions are currenly disabled; please ".
                       "contact us if you need to make special arrangements.");
	goto bad;
    }

    if (!isset($ajax_args["howlong"]) || $ajax_args["howlong"] == "") {
386
	SPITAJAX_ERROR(1, "Missing number of hours");
387 388 389
	goto bad;
    }
    $wanted = $ajax_args["howlong"];
390 391 392
    if (preg_match("/^\d+$/", $wanted)) {
        if ($wanted < 1) {
            SPITAJAX_ERROR(1, "Hours must be an integer greater then 1");
393 394 395
            goto bad;
        }
    }
396 397
    elseif (!strtotime($wanted)) {
        SPITAJAX_ERROR(1, "Invalid characters in hours");
398
        goto bad;
399
    }
400 401 402 403 404 405 406
    if (isset($ajax_args["maxextension"]) && $ajax_args["maxextension"] != "") {
        $maxextension = $ajax_args["maxextension"];
        if (!strtotime($maxextension)) {
            SPITAJAX_ERROR(1, "Invalid max extension date");
            goto bad;
        }
    }
407 408 409 410
    if (ISADMIN()) {
	if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
            $reason = $ajax_args["reason"];
        }
411 412 413
	if (isset($ajax_args["force"]) && $ajax_args["force"]) {
            $force = 1;
        }
414
    }
415
    else if ($wanted >= 24) {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	if (!isset($ajax_args["reason"]) || $ajax_args["reason"] == "") {
	    SPITAJAX_ERROR(1, "Missing reason");
	    goto bad;
	}
	$reason = $ajax_args["reason"];
    }
    if (isset($reason)) {
        if (!TBvalid_fulltext($reason)) {
	    SPITAJAX_ERROR(1, "Illegal characters in reason");
	    goto bad;
        }
        $filename = tempnam("/tmp", "extension");
        $fp = fopen($filename, "w");
        fwrite($fp, $reason);
        fclose($fp);
    }        
    $webtask = WebTask::CreateAnonymous();
    $retval = SUEXEC("nobody", "nobody",
		     "webmanage_instance -t " . $webtask->task_id() . " -- ".
435 436
                     "  extend $uuid " .
                     (isset($filename) ? "-f $filename " : "").
437
                     (isset($maxextension) ? "-e '$maxextension' " : "").
438
                     ($force ? "-F " : "") . "'$wanted'",
439 440 441 442 443 444
		     SUEXEC_ACTION_IGNORE);
    $webtask->Refresh();
    if (isset($filename)) {
        unlink($filename);
    }
    if ($retval != 0) {
445
        if (!$webtask->exited() || $retval < 0) {
446
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
447
            SPITAJAX_ERROR(-1, "Internal error extending experiment");
448 449
        }
        else {
450 451 452 453 454 455
            if ($webtask->exitcode() == GENIRESPONSE_REFUSED) {
                # This is an important error, tell tbops.
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
            # Need to pass exitcode through on this one.
            SPITAJAX_ERROR($webtask->exitcode(), $webtask->output());
456 457 458 459 460 461
        }
        $webtask->Delete();
        goto bad;
    }
    # Refresh. 
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
462 463 464
    $blob = array("expiration" => DateStringGMT($slice->expires()),
                  "granted"    => $webtask->TaskValue("granted"),
                  "message"    => $webtask->TaskValue("message"));
465
    $webtask->Delete();
466
    SPITAJAX_RESPONSE($blob);
467 468 469 470 471
bad:
delay:
    sleep(1);
}

472
function Do_DenyOrMoreinfo($action)
473 474 475
{
    global $instance, $creator, $this_user, $suexec_output;
    global $ajax_args;
476
    $lockout  = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
477
    $extrargs = "";
478

479 480
    # Really, only admins can do this.
    if (StatusSetupAjax(0)) {
481 482 483 484 485 486 487 488 489 490 491 492
	goto bad;
    }
    $uuid = $instance->uuid();
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
    if (!slice) {
	SPITAJAX_ERROR(1, "no slice for instance");
	goto bad;
    }
    if (!ISADMIN()) {
	SPITAJAX_ERROR(1, "You do not have permission to do this.");
	goto bad;
    }
493
    if ($action == "terminate" && $instance->admin_lockdown()) {
494 495 496 497 498 499
        SPITAJAX_ERROR(1, "This experiment has been locked down by an ".
                       "administrator. The lock must be cleared before ".
                       "it can terminated.");
        return;

    }
500 501 502 503
    if (($action == "terminate" || $action == "deny") &&
        isset($ajax_args["lockout"]) && $ajax_args["lockout"] != "0") {
        $lockout = 1;
    }
504 505
    if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
        $reason = $ajax_args["reason"];
506
        
507
        if (!TBvalid_fulltext($reason)) {
508 509 510 511 512
	    SPITAJAX_ERROR(1, "Illegal characters in message");
	    goto bad;
        }
        $filename = tempnam("/tmp", "extension");
        $fp = fopen($filename, "w");
513
        fwrite($fp, $reason);
514
        fclose($fp);
Leigh B Stoller's avatar
Leigh B Stoller committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    }
    if ($action == "terminate") {
        if (!isset($ajax_args["howlong"]) || $ajax_args["howlong"] == "") {
            SPITAJAX_ERROR(1, "Missing number of days");
            goto bad;
        }
        $days = $ajax_args["howlong"];
        if (! preg_match("/^\d+$/", $days)) {
            SPITAJAX_ERROR(1, "Invalid characters in days");
            goto bad;
        }
        $extrargs = $days;
    }
    $action = ($action == "deny" ? "denyextension" :
               ($action == "terminate" ? "schedterminate": "moreinfo"));
530 531 532
    $webtask = WebTask::CreateAnonymous();
    $retval = SUEXEC("nobody", "nobody",
		     "webmanage_instance -t " . $webtask->task_id() . " -- ".
Leigh B Stoller's avatar
Leigh B Stoller committed
533
                     "  $action $uuid $extrargs " .
534 535 536 537 538 539 540
                        (isset($filename) ? $filename : ""),
		     SUEXEC_ACTION_IGNORE);
    $webtask->Refresh();
    if (isset($filename)) {
        unlink($filename);
    }
    if ($retval != 0) {
541 542 543 544 545
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-1, "Internal error");
        }
        else {
546 547 548 549
            # This is an important error, tell tbops.
            if ($webtask->exitcode() == GENIRESPONSE_REFUSED) {
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
550 551
            # Need to pass exitcode through on this one.
            SPITAJAX_ERROR($webtask->exitcode(), $webtask->output());
552 553
        }
        $webtask->Delete();
554
        return;
555 556
    }
    $webtask->Delete();
557 558 559 560 561 562 563 564
    if ($lockout) {
        if (Do_Lockout()) {
            SPITAJAX_ERROR(-1, "Could not disable extensions");
            return;
        }
        # Do_Lockout() issued a success.
        return;
    }
565
    SPITAJAX_RESPONSE("Success");
566
    return;
567 568 569 570 571
bad:
    $webtask->Delete();
    sleep(1);
}

572 573 574 575 576 577 578 579
function Do_DenyExtension()
{
    Do_DenyOrMoreinfo("deny");
}
function Do_MoreInfo()
{
    Do_DenyOrMoreinfo("info");
}
Leigh B Stoller's avatar
Leigh B Stoller committed
580 581 582 583
function Do_SchedTerminate()
{
    Do_DenyOrMoreinfo("terminate");
}
584

585 586 587 588 589
#
# Request a console URL and pass back to the status page.
#
function Do_ConsoleURL()
{
590
    global $instance, $creator, $this_user, $suexec_output;
591
    global $ajax_args, $TBDB_TRUST_LOCALROOT;
592

593
    if (StatusSetupAjax(0)) {
594 595 596
	return;
    }
    if (!isset($this_user)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
597
	SPITAJAX_ERROR(1, "Only registered users can view node consoles");
598 599
	return;
    }
600
    if (!isset($ajax_args["node"])) {
601
	SPITAJAX_ERROR(1, "Missing node argument");
602 603 604 605 606 607 608 609 610
	return 1;
    }
    $node = $ajax_args["node"];
    $uuid = $instance->uuid();
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
    if (!slice) {
	SPITAJAX_ERROR(1, "no slice for instance");
	return 1;
    }
611
    $webtask = WebTask::CreateAnonymous();
612
    $retval = SUEXEC("nobody", "nobody",
613 614
		     "webmanage_instance -t " . $webtask->task_id() . " ".
                     "  consoleurl $uuid " .
615
		     escapeshellarg($node),
616
		     SUEXEC_ACTION_IGNORE);
617
    $webtask->Refresh();
618

619 620 621 622
    if ($retval != 0) {
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-1, "Internal error getting console info");
Leigh B Stoller's avatar
Leigh B Stoller committed
623
        }
624 625 626 627
        else {
            # JS needs this exitcode.
            SPITAJAX_ERROR($webtask->exitcode(),
                           "Could not get console info: ". $webtask->output());
628
        }
629
        $webtask->Delete();
630
	return;
631
    }
632 633 634 635 636 637 638 639 640 641 642 643
    #
    # If the user has 'user' privs in the current project/group
    # then we do not return the root password. They can still look
    # at the console though.
    #
    $group = $instance->Group();
    $trust = $group->UserTrust($this_user);
        
    $taskdata = $webtask->TaskData();
    $blob = array();
    $blob["url"] = $taskdata["url"];
    if (isset($taskdata["password"]) &&
644
        (ISADMIN() || TBMinTrust($trust, $TBDB_TRUST_LOCALROOT))) {
645 646 647 648
        $blob["password"] = $taskdata["password"];
    }
    if (isset($taskdata["logurl"])) {
        $blob["logurl"] = $taskdata["logurl"];
649
    }
650
    SPITAJAX_RESPONSE($blob);
651
    $webtask->Delete();
652
    return;
653 654
}

655 656 657 658 659
#
# Fire off a snapshot.
#
function Do_Snapshot()
{
660
    global $this_user, $instance, $suexec_output;
661
    global $ajax_args;
Leigh B Stoller's avatar
Leigh B Stoller committed
662
    $errors = array();
663

664
    if (StatusSetupAjax(0)) {
665 666
	return;
    }
667 668
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can snapshot nodes");
669 670
	return;
    }
671 672
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];
Leigh B Stoller's avatar
Leigh B Stoller committed
673 674
    $checkonly = (isset($ajax_args["checkonly"]) &&
                  $ajax_args["checkonly"] == 1 ? 1 : 0);
675

676 677 678 679 680 681 682 683
    #
    # As per Rob, if an experiment is locked down, then only the creator,
    # project leader, or an admininstrator.
    #
    if ($instance->admin_lockdown() || $instance->user_lockdown()) {
        if ($this_idx != $instance->creator_idx() && !ISADMIN() &&
            !$instance->Project()->IsLeader($this_user)) {
            SPITAJAX_ERROR(1, "Not enough permission, ".
Leigh B Stoller's avatar
Leigh B Stoller committed
684
                           "experiment is locked down.");
685 686 687
            return;
        }
    }
688 689 690 691
    if ($instance->status() != "ready") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }
692 693 694 695 696 697 698 699 700 701 702 703 704
    if (!isset($ajax_args["operation"]) || $ajax_args["operation"] == "") {
        SPITAJAX_ERROR(-1, "Must supply operation!");
        return;
    }
    $operation = $ajax_args["operation"];
    if (! ($operation == "update-profile" ||
           $operation == "copy-profile" ||
           $operation == "new-profile" ||
           $operation == "image-only")) {
        SPITAJAX_ERROR(-1, "Invalid operation!");
        return;
    }
           
705 706 707 708
    #
    # The profile also has to belong to the user, since it is
    # going to be modified to use the new image.
    #
709 710
    $profile = Profile::Lookup($instance->profile_id(),
			       $instance->profile_version());
711 712 713 714
    if (!$profile) {
	SPITAJAX_ERROR(1, "Cannot lookup profile for instance");
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
715 716
    if ($operation == "update-profile" &&
        ($this_idx != $profile->creator_idx() && !ISADMIN())) {
Leigh B Stoller's avatar
Leigh B Stoller committed
717
	SPITAJAX_ERROR(1, "Not your profile to change. Make a copy first!");
718 719
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
720
    $optargs = "";
Leigh B Stoller's avatar
Leigh B Stoller committed
721
    if (isset($ajax_args["node_id"]) && $ajax_args["node_id"] != "") {
Leigh B Stoller's avatar
Leigh B Stoller committed
722 723
        $node_id = $ajax_args["node_id"];
        if (!TBvalid_vnode_id($node_id)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
724 725 726 727
            $errors["node_id"] = "Invalid node id";
        }
        else {
            $optargs .= " -n $node_id ";
Leigh B Stoller's avatar
Leigh B Stoller committed
728
        }
729
    } 
730 731 732 733
    if (isset($ajax_args["update_prepare"]) &&
        $ajax_args["update_prepare"]) {
        $optargs .= " -U ";
    }
734 735 736
    if (isset($ajax_args["wholedisk"]) && $ajax_args["wholedisk"]) {
        $optargs .= " -e ";
    }
737 738 739
    if (isset($ajax_args["nosnapshot"]) && $ajax_args["nosnapshot"]) {
        $optargs .= " -S ";
    }
740 741
    if (isset($ajax_args["imagename"]) && $ajax_args["imagename"] != "") {
        if (!TBvalid_imagename($ajax_args["imagename"])) {
Leigh B Stoller's avatar
Leigh B Stoller committed
742 743 744 745
            $errors["imagename"] = "Invalid imagename, alphanumeric only";
        }
        else {
            $optargs .= " -i " . escapeshellarg($ajax_args["imagename"]);
746
        }
Leigh B Stoller's avatar
Leigh B Stoller committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
    }
    if (isset($ajax_args["description"]) && $ajax_args["description"] != "") {
        $desc = $ajax_args["description"];
        
        if (!TBvalid_fulltext($desc)) {
            $errors["description"] = "Illegal characters";
        } 
        elseif (strlen($desc) > 225) { 
            $errors["description"] = "Too long, must be < 225 chars";
        }
        elseif (strlen($desc) < 10) {
            $errors["description"] = "Too short, must be >= 10 chars";
        }
        elseif (!$checkonly) {
            $filename = tempnam("/tmp", "description");
            $fp = fopen($filename, "w");
            fwrite($fp, $desc);
            fclose($fp);
            chmod($filename, 0666);        
            $optargs .= " -D $filename";
        }
    }
    if (count($errors)) {
        SPITAJAX_ERROR(2, $errors);
        return;
    }
    if ($checkonly) {
        SPITAJAX_RESPONSE("Success");
        return;
776
    }
777 778
    $optargs .= " -O $operation ";

779 780 781
    #
    # Call out to the backend.
    #
782
    $webtask = WebTask::CreateAnonymous();
783
    $retval = SUEXEC($this_user->uid(), "nobody",
784
		     "webmanage_instance -t " . $webtask->task_id() . " " .
785
                     "  snapshot $uuid $optargs",
786
		     SUEXEC_ACTION_IGNORE);
787
    $webtask->Refresh();
Leigh B Stoller's avatar
Leigh B Stoller committed
788 789 790
    if (isset($filename)) {
        unlink($filename);
    }
791
    if ($retval != 0) {
792 793 794 795
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-11, "Internal error creating snapshot");
        }
796
        else {
797 798
            SPITAJAX_ERROR(1, "Could not create snapshot: ".
                           $webtask->output());
799
        }
800
        $webtask->Delete();
801
	return;
802
    }
803
    $webtask->Delete();
804 805 806 807 808 809 810 811
    SPITAJAX_RESPONSE("Success");
}

#
# Return snapshot status.
#
function Do_SnapshotStatus()
{
812
    global $this_user, $instance;
813 814
    global $ajax_args;

815
    if (StatusSetupAjax(0)) {
816 817
	return;
    }
818 819
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can snapshot nodes");
820 821
	return;
    }
822
    $this_idx = $this_user->uid_idx();
823 824 825 826 827
    if ($this_idx != $instance->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission");
	return;
    }
    $webtask = $instance->WebTask();
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
    if (!$webtask) {
	SPITAJAX_ERROR(1, "No status descriptor found");
	return;
    }
    $taskdata = $webtask->TaskData();
    $blob = array();

    #
    # Size is in KB to avoid bigint problems. But kill the KB.
    # 
    if (isset($taskdata["image_size"])) {
	if (preg_match("/^(\d+)KB$/", $taskdata["image_size"], $matches)) {
	    $taskdata["image_size"] = $matches[1]; 
	}
	$blob["image_size"] = $taskdata["image_size"];
    }
    else {
	$blob["image_size"] = 0;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
847 848 849
    if (isset($taskdata["copyback_uuid"])) {
        $blob["copyback_uuid"] = $taskdata["copyback_uuid"];
    }
850 851 852 853 854 855 856 857 858
    $blob["image_status"] = $taskdata["image_status"];
    
    #
    # Lets put the node status in too. The backend has helpfully told us
    # the aggregate and node to track down the status.
    #
    if (isset($taskdata["aggregate_urn"]) && isset($taskdata["client_id"])) {
        $sliver = InstanceSliver::Lookup($instance, $taskdata["aggregate_urn"]);
        if ($sliver) {
859 860 861 862 863
            foreach ($sliver->StatusArray() as $status) {
                if (isset($status["sliver_data"]) &&
                    $status["client_id"] == $taskdata["client_id"]) {
                    $blob["node_status"] = $status["sliver_details"]["rawstate"];
                    break;
864 865 866 867
                }
            }
        }
    }
868 869 870 871
    if ($webtask->exited()) {
	# Success, but not sure what to report. Come back to this later.
	$blob["exited"]   = $webtask->exited();
	$blob["exitcode"] = $webtask->exitcode();
872 873 874
        if (isset($taskdata["image_name"])) {
            $blob["image_name"] = $taskdata["image_name"];
        }
875
    }
876 877 878
    SPITAJAX_RESPONSE($blob);
}

879 880 881 882 883
#
# Ask the backend to refresh sliverstatus
#
function Do_Refresh()
{
884
    global $this_user, $instance, $suexec_output;
885 886
    global $ajax_args;

887 888 889
    #
    # Guest users can do this.
    #
890
    if (StatusSetupAjax(0)) {
891 892
	return;
    }
893
    $this_idx = $this_user->uid_idx();
894 895 896 897
    $uuid = $ajax_args["uuid"];
    #
    # Call out to the backend.
    #
898
    $webtask = WebTask::CreateAnonymous();
899
    $retval = SUEXEC("nobody", "nobody",
900 901
		     "webmanage_instance -t " . $webtask->task_id() .
                     " refresh $uuid",
902
		     SUEXEC_ACTION_IGNORE);
903
    $webtask->Refresh();
904 905

    if ($retval != 0) {
906 907 908 909
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-11, "Internal error refreshing status");
        }
910
        else {
911
            SPITAJAX_ERROR(1, "Could not refresh status: ". $webtask->output());
912
        }
913
        $webtask->Delete();
914 915
	return;
    }
916
    $webtask->Delete();
917
    SPITAJAX_RESPONSE("Success");
918 919
}

Leigh B Stoller's avatar
Leigh B Stoller committed
920 921 922 923 924 925 926 927
#
# Reload rhe manifests.
#
function Do_ReloadTopology()
{
    global $this_user, $instance, $suexec_output;
    global $ajax_args;

928
    if (StatusSetupAjax(0)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
929 930 931 932 933 934 935
	return;
    }
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];
    #
    # Call out to the backend.
    #
936
    $webtask = WebTask::CreateAnonymous();
Leigh B Stoller's avatar
Leigh B Stoller committed
937
    $retval = SUEXEC("nobody", "nobody",
938 939
		     "webmanage_instance -t " . $webtask->task_id() .
                     "  getmanifests $uuid",
Leigh B Stoller's avatar
Leigh B Stoller committed
940
		     SUEXEC_ACTION_IGNORE);
Leigh B Stoller's avatar
Leigh B Stoller committed
941
    $webtask->Refresh();
Leigh B Stoller's avatar
Leigh B Stoller committed
942 943

    if ($retval != 0) {
944 945 946 947
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-11, "Internal error getting manifests");
        }
948
        else {
949
            SPITAJAX_ERROR(1, $webtask->output());
Leigh B Stoller's avatar
Leigh B Stoller committed
950
        }
951
        $webtask->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
952 953
	return;
    }
954
    $webtask->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
955 956 957
    SPITAJAX_RESPONSE("Success");
}

958
#
959
# Ask the backend to reboot or reload a node.
960
#
961
function Do_RebootOrReload($which)
962
{
963
    global $this_user, $instance, $suexec_output;
964
    global $ajax_args, $TBDB_TRUST_GROUPROOT;
965

966
    if (StatusSetupAjax(0)) {
967 968
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
969 970 971 972
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can reboot/reload nodes");
	return;
    }
973 974 975
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];

976 977 978 979 980 981
    #
    # As per Rob, if an experiment is locked down, then only the creator,
    # project leader, or an admininstrator.
    #
    if ($instance->admin_lockdown() || $instance->user_lockdown()) {
        if ($this_idx != $instance->creator_idx() && !ISADMIN() &&
982 983
            $instance->Project()->UserTrust($this_user) <
            $TBDB_TRUST_GROUPROOT) {
984 985 986 987 988
            SPITAJAX_ERROR(1, "Not enough permission, ".
                           "experiment is locked down");
            return;
        }
    }
989

Leigh B Stoller's avatar
Leigh B Stoller committed
990 991
    if (!isset($ajax_args["node_ids"])) {
	SPITAJAX_ERROR(1, "Missing node_id list");
992 993
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
994 995 996 997 998 999 1000
    $nodelist = "";
    foreach ($ajax_args["node_ids"] as $node_id) {
        if (!preg_match("/^[-\w]+$/", $node_id)) {
            SPITAJAX_ERROR(1, "Illegal characters in node_id");
            return;
        }
        $nodelist .= " " . escapeshellarg($node_id);
1001 1002 1003 1004 1005 1006 1007 1008 1009
    }
    if ($instance->status() != "ready" && $instance->status() != "failed") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }

    #
    # Call out to the backend.
    #
1010
    $webtask = WebTask::CreateAnonymous();
1011
    $retval = SUEXEC("nobody", "nobody",
1012
		     "webmanage_instance -t " . $webtask->task_id() .
Leigh B Stoller's avatar
Leigh B Stoller committed
1013
                     "  $which $uuid $nodelist",
1014
		     SUEXEC_ACTION_IGNORE);
1015
    $webtask->Refresh();
1016 1017

    if ($retval != 0) {
1018 1019 1020 1021
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-1, "Internal error");
        }
1022
        else {
1023
            SPITAJAX_ERROR(1, $webtask->output());
1024 1025
        }
        $webtask->Delete();
1026 1027
	return;
    }
1028
    $webtask->Delete();
1029 1030
    SPITAJAX_RESPONSE("Success");
}
1031 1032 1033 1034 1035 1036 1037 1038
function Do_Reboot()
{
    Do_RebootOrReload("reboot");
}
function Do_Reload()
{
    Do_RebootOrReload("reload");
}
1039

Leigh B Stoller's avatar
Leigh B Stoller committed
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
#
# Delete nodes from an experiment
#
function Do_DeleteNodes()
{
    global $this_user, $instance, $suexec_output;
    global $ajax_args;

    if (StatusSetupAjax(1)) {
	return;
    }
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can delete nodes");
	return;
    }
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];

    if (!isset($ajax_args["node_ids"])) {
	SPITAJAX_ERROR(1, "Missing node_id list");
	return;
    }
    $nodelist = "";
    foreach ($ajax_args["node_ids"] as $node_id) {
        if (!preg_match("/^[-\w]+$/", $node_id)) {
            SPITAJAX_ERROR(1, "Illegal characters in node_id");
            return;
        }
        $nodelist .= " " . escapeshellarg($node_id);
    }
    if ($this_idx != $instance->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission.");
	return;
    }
    if ($instance->status() != "ready") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }

    #
    # Call out to the backend.
    #
1082
    $webtask = WebTask::CreateAnonymous();
Leigh B Stoller's avatar
Leigh B Stoller committed
1083
    $retval = SUEXEC("nobody", "nobody",
1084
		     "webmanage_instance -t " . $webtask->task_id() .
Leigh B Stoller's avatar
Leigh B Stoller committed
1085 1086
                     "  deletenodes $uuid $nodelist",
		     SUEXEC_ACTION_IGNORE);
1087
    $webtask->Refresh();
Leigh B Stoller's avatar
Leigh B Stoller committed
1088 1089

    if ($retval != 0) {
1090 1091 1092 1093
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-1, "Internal error deleting nodes");
        }
Leigh B Stoller's avatar
Leigh B Stoller committed
1094
        else {
1095
            SPITAJAX_ERROR(1, $webtask->output());
1096 1097
        }
        $webtask->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
1098 1099
	return;
    }
1100
    $webtask->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
1101 1102 1103
    SPITAJAX_RESPONSE("Success");
}

1104 1105 1106 1107 1108 1109 1110 1111
#
# Decrypt the blocks using the per-instance private key.
#
function Do_DecryptBlocks()
{
    global $this_user, $instance, $suexec_output;
    global $ajax_args;

1112
    if (StatusSetupAjax(0)) {
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	return;
    }
    if (!isset($ajax_args["blocks"])) {
	SPITAJAX_ERROR(1, "Missing blocks argument");
	return;
    }
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];
    $result = array();

    #
    # Grab the instance private key and write to a file for smime.
    #
    $infname  = tempnam("/tmp", "decryptin");
    $outfname = tempnam("/tmp", "decryptout");
    $pkeyname = tempnam("/tmp", "decryptkey");

    $fp = fopen($pkeyname, "w");
    fwrite($fp, $instance->private_key());
    fclose($fp);

    #
    # Use smime for each block and store.
    #
    foreach ($ajax_args["blocks"] as $key => $block) {
        $fp = fopen($infname, "w");
        fwrite($fp, $block);
        fclose($fp);
        # Truncate the output file.
        $fp = fopen($outfname, "w");
        fclose($fp);

        $retval =
            myexec("/usr/bin/openssl smime -decrypt -inform PEM -inkey ".
                   "$pkeyname -in $infname -out $outfname");

        if ($retval) {
            SPITAJAX_ERROR(-1, "Internal decryption error");
            return;
        }
        $decrypted = file_get_contents($outfname);
        $result[$key] = $decrypted;
    }
    unlink($infname);
    unlink($outfname);
    unlink($pkeyname);
    SPITAJAX_RESPONSE($result);
}

Leigh B Stoller's avatar
Leigh B Stoller committed
1162 1163 1164 1165 1166 1167 1168
#
# Set or clear the lockout flag
#
function Do_Lockout()
{
    global $this_user;
    global $ajax_args;
1169
    global $TBMAIL_OPS, $TBMAIL_AUDIT;
Leigh B Stoller's avatar
Leigh B Stoller committed
1170

1171 1172
    if (!isset($this_user) || !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission.");
1173
	return -1;
1174
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1175 1176 1177 1178
    $this_idx = $this_user->uid_idx();

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
1179
	return -1;
Leigh B Stoller's avatar
Leigh B Stoller committed
1180 1181 1182
    }
    if (!isset($ajax_args["lockout"])) {
	SPITAJAX_ERROR(1, "Missing lockout value");
1183
	return -1;
Leigh B Stoller's avatar
Leigh B Stoller committed
1184
    }
1185 1186 1187 1188 1189
    if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
        $reason = $ajax_args["reason"];
        
        if (!TBvalid_fulltext($reason)) {
	    SPITAJAX_ERROR(1, "Illegal characters in message");
1190
            return -1;
1191 1192 1193
        }
        $safe_reason = DBQuoteSpecial($reason);
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1194 1195 1196 1197
    $uuid = $ajax_args["uuid"];
    $instance = Instance::Lookup($uuid);
    if (!$instance) {
	SPITAJAX_ERROR(1, "Unknown instance uuid");
1198
	return -1;
Leigh B Stoller's avatar
Leigh B Stoller committed
1199
    }
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    $lockout = ($ajax_args["lockout"] == 0 ? 0 : 1);
    if ($lockout) {
        $reason_clause  = (isset($safe_reason) ?
                           ",extension_disabled_reason='$safe_reason'" : "");
    }
    else {
        $reason_clause  = ",extension_disabled_reason=null";
    }
    if (!DBQueryWarn("update apt_instances set ".
                     "  extension_disabled='$lockout' $reason_clause ".
Leigh B Stoller's avatar
Leigh B Stoller committed
1210 1211
                     "where uuid='$uuid'")) {
	SPITAJAX_ERROR(1, "Database failure.");
1212
	return -1;
Leigh B Stoller's avatar
Leigh B Stoller committed
1213
    }
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    $this_uid = $this_user->uid();
    $pid      = $instance->pid();
    $name     = $instance->name();
    $which    = ($lockout ? "disabled" : "enabled");
    TBMAIL($TBMAIL_AUDIT,
           "Portal experiment $uuid extensions $which",
           "$this_uid has $which extensions for $pid/$name\n\n".
           ($lockout && isset($reason) ? "Reason:\n$reason\n\n" : "").
           $instance->AdminURL() . "\n",
           "From: $TBMAIL_OPS");
    
Leigh B Stoller's avatar
Leigh B Stoller committed
1225
    SPITAJAX_RESPONSE("Success");