status.ajax 56.5 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
    $blob["sliverstatus"] = array();
104 105 106 107 108

    if ($instance->logfileid()) {
        $blob["logfile_url"] =
            "$APTBASE/spewlogfile.php?logfile=" . $instance->logfileid();
    }
109
    
110
    # Openstack experiment?
111
    $haveopenstack = $instance->isopenstack() ? 1 : 0;
112 113

    foreach ($instance->slivers() as $sliver) {
114 115 116 117 118 119 120 121 122
        $sliverblob = array("status"  => $sliver->status(),
                            "offline" => false);
        #
        # See if the aggregate is offline.
        #
        $aggregate = Aggregate::Lookup($sliver->aggregate_urn());
        if ($aggregate && $aggregate->status() == "down") {
            $sliverblob["offline"] = true;
        }
123
        if (!$sliver->manifest()) {
124
            $sliverblob["havemanifest"] = 0;
125 126
        }
        else {
127 128
            $sliverblob["havemanifest"] = 1;
            $statusblob = array();
129 130 131 132 133

            foreach ($sliver->StatusArray() as $status) {
                if (isset($status["sliver_data"])) {
                    $statusblob[$status["client_id"]]
                        = $status["sliver_details"];
134
                }
135
            }
136
            $sliverblob["details"] = $statusblob;
137
        }
138
        if ($sliver->public_url()) {
139
            $sliverblob["url"] = $sliver->public_url();
140
        }
141
        $blob["sliverstatus"][$sliver->aggregate_urn()] = $sliverblob;
142
    }
143
    $blob["haveopenstackstats"] = $haveopenstack;
144 145

    # Reflect errors back to the user.
146
    $webtask = $instance->WebTask();
147
    if ($webtask && $webtask->exited()) {
148 149
        $blob["code"] = $webtask->exitcode();
        
150
        if ($webtask->exitcode() == GENIRESPONSE_INSUFFICIENT_NODES) {
151 152
            # All the info in the results from the cluster.
            $blob["reason"]  = "";
153
        }
154
        elseif ($webtask->exitcode() == GENIRESPONSE_INSUFFICIENT_BANDWIDTH) {
155 156
            $blob["reason"]  = "Not enough available bandwidth for a link.\n\n";
        }
157 158 159 160 161 162 163
        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. ".
164 165 166
	    "You have most likely asked for hardware that does not exist, ".
            "such as nodes of a type that are not at the target cluster, ".
            "or nodes with too many network interfaces.\n\n";
167
        }
168
        elseif ($webtask->exitcode() == GENIRESPONSE_NO_MAPPING) {
169
            $blob["reason"]  = "Your topology could not be mapped to physical ".
170 171
                "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
172 173
                "lots of info, some of which might be useful in figuring out ".
                "why it failed.\n\n";
174
        }
175
        elseif ($webtask->exitcode() == GENIRESPONSE_TIMEDOUT) {
176 177 178
            $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";
179
        }
180
        elseif ($webtask->exitcode() == GENIRESPONSE_BADARGS) {
181 182 183 184 185 186
            #
            # 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";
187
        }
188 189 190 191 192 193 194 195 196
        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.";
        }
197 198 199 200 201 202 203 204
        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";
        }
205
        else {
206
            $blob["reason"] = "";
207
        }
208
        $blob["reason"] .= htmlentities($webtask->TaskValue("output"));
209 210 211
        $blob["canclearerror"]
            = ($webtask->exitcode() ==
               GENIRESPONSE_SETUPFAILURE_BOOTFAILED ? 1 : 0);
212
    }
213
    SPITAJAX_RESPONSE($blob);
214 215 216 217 218 219 220
}

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

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

233 234 235 236 237 238 239
    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;

    }
240 241 242
    $webtask = WebTask::CreateAnonymous();
    $webtask_id = $webtask->task_id();

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

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

            if ($webtask && $webtask->exited()) {
267
                SPITAJAX_ERROR(1, $webtask->output());
268 269 270 271
            }
            else {
                SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
            }
272
            $webtask->Delete();
273 274 275
            return;
        }
    }
276 277
    $webtask->Reset();
    
278 279 280
    # 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.
281
    $retval = SUEXEC("nobody", "nobody",
282
                     "webmanage_instance -t $webtask_id -- terminate $uuid",
283
                     SUEXEC_ACTION_IGNORE);
284 285 286 287 288 289 290 291 292 293
    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());
        }
294
    }
295
    else {
296
	SPITAJAX_RESPONSE("");
297 298
    }
    $webtask->Delete();
299 300 301 302 303 304 305
}

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

308
    if (StatusSetupAjax(0)) {
309 310
	return;
    }
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    if (isset($ajax_args["aggregate_urn"])) {
        $urn = $ajax_args["aggregate_urn"];
        if (!Instance::ValidURN($urn)) {
            SPITAJAX_ERROR(-1, "Illegal characters in aggregate urn");
            return;
        }
        $sliver = InstanceSliver::Lookup($instance, $urn);
        if (!$sliver) {
            SPITAJAX_ERROR(-1, "No sliver for aggregate urn");
            return;
        }
        SPITAJAX_RESPONSE($sliver->manifest());
    }
    else {
        $blob = array();
326

327 328 329 330
        foreach ($instance->slivers() as $sliver) {
            if ($sliver->manifest()) {
                $blob[$sliver->aggregate_urn()] = $sliver->manifest();
            }
331
        }
332
        SPITAJAX_RESPONSE($blob);
333
    }
334 335 336 337 338 339 340
}

#
# SSH Auth Object
#
function Do_GetSSHAuthObject()
{
341
    global $instance, $creator, $this_user;
342 343 344 345 346 347 348 349
    global $ajax_args;

    if (!isset($ajax_args["hostport"])) {
	SPITAJAX_ERROR(1, "Missing hostport");
	return 1;
    }
    $hostport = $ajax_args["hostport"];
    
350
    if (StatusSetupAjax(0)) {
351 352
	return;
    }
353
    if (! ((isset($this_user) && $instance->CanDoSSH($this_user)) ||
Leigh B Stoller's avatar
Leigh B Stoller committed
354 355
	   (isset($_COOKIE['quickvm_user']) &&
	    $_COOKIE['quickvm_user'] == $creator->uuid()))) {
356 357
	SPITAJAX_ERROR(1, "Not allowed to ssh; ".
                       "only the creator or a project member");
358 359 360
	return;
    }
    
361
    $nodeid = $ajax_args["nodeid"];
362 363
    $auth   = SSHAuthObject(isset($this_user) ?
                            $this_user->uid() : $creator->uid(), $hostport);
364 365 366 367 368 369 370
    if (!$auth) {
	SPITAJAX_ERROR(1, "Could not create authentication object");
	return;
    }
    SPITAJAX_RESPONSE($auth);
}

371 372 373 374
function Do_RequestExtension()
{
    global $instance, $creator, $this_user, $suexec_output;
    global $ajax_args;
375
    $force   = 0;
376 377 378 379 380 381 382 383 384
    $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();
385 386
            if (!(ISADMINISTRATOR() ||
                  FeatureEnabled("NewPortalExtend", $this_user, $group))) {
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
                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"] == "") {
405
	SPITAJAX_ERROR(1, "Missing number of hours");
406 407 408
	goto bad;
    }
    $wanted = $ajax_args["howlong"];
Leigh B Stoller's avatar
Leigh B Stoller committed
409
    if (is_numeric($wanted)) {
410 411
        if ($wanted < 1) {
            SPITAJAX_ERROR(1, "Hours must be an integer greater then 1");
412 413 414
            goto bad;
        }
    }
415 416
    elseif (!strtotime($wanted)) {
        SPITAJAX_ERROR(1, "Invalid characters in hours");
417
        goto bad;
418
    }
419 420 421 422 423 424 425
    if (isset($ajax_args["maxextension"]) && $ajax_args["maxextension"] != "") {
        $maxextension = $ajax_args["maxextension"];
        if (!strtotime($maxextension)) {
            SPITAJAX_ERROR(1, "Invalid max extension date");
            goto bad;
        }
    }
426 427 428 429
    if (ISADMIN()) {
	if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
            $reason = $ajax_args["reason"];
        }
430 431 432
	if (isset($ajax_args["force"]) && $ajax_args["force"]) {
            $force = 1;
        }
433
    }
434
    else if ($wanted >= 24) {
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
	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() . " -- ".
454 455
                     "  extend $uuid " .
                     (isset($filename) ? "-f $filename " : "").
456
                     (isset($maxextension) ? "-e '$maxextension' " : "").
457
                     ($force ? "-F " : "") . "'$wanted'",
458 459 460 461 462 463
		     SUEXEC_ACTION_IGNORE);
    $webtask->Refresh();
    if (isset($filename)) {
        unlink($filename);
    }
    if ($retval != 0) {
464
        if (!$webtask->exited() || $retval < 0) {
465
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
466
            SPITAJAX_ERROR(-1, "Internal error extending experiment");
467 468
        }
        else {
469 470 471 472 473 474
            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());
475 476 477 478 479 480
        }
        $webtask->Delete();
        goto bad;
    }
    # Refresh. 
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
481 482 483
    $blob = array("expiration" => DateStringGMT($slice->expires()),
                  "granted"    => $webtask->TaskValue("granted"),
                  "message"    => $webtask->TaskValue("message"));
484
    $webtask->Delete();
485
    SPITAJAX_RESPONSE($blob);
486 487 488 489 490
bad:
delay:
    sleep(1);
}

491
function Do_DenyOrMoreinfo($action)
492 493 494
{
    global $instance, $creator, $this_user, $suexec_output;
    global $ajax_args;
495
    $lockout  = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
496
    $extrargs = "";
497

498 499
    # Really, only admins can do this.
    if (StatusSetupAjax(0)) {
500 501 502 503 504 505 506 507 508 509 510 511
	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;
    }
512
    if ($action == "terminate" && $instance->admin_lockdown()) {
513 514 515 516 517 518
        SPITAJAX_ERROR(1, "This experiment has been locked down by an ".
                       "administrator. The lock must be cleared before ".
                       "it can terminated.");
        return;

    }
519 520 521 522
    if (($action == "terminate" || $action == "deny") &&
        isset($ajax_args["lockout"]) && $ajax_args["lockout"] != "0") {
        $lockout = 1;
    }
523 524
    if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
        $reason = $ajax_args["reason"];
525
        
526
        if (!TBvalid_fulltext($reason)) {
527 528 529 530 531
	    SPITAJAX_ERROR(1, "Illegal characters in message");
	    goto bad;
        }
        $filename = tempnam("/tmp", "extension");
        $fp = fopen($filename, "w");
532
        fwrite($fp, $reason);
533
        fclose($fp);
Leigh B Stoller's avatar
Leigh B Stoller committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    }
    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"));
549 550 551
    $webtask = WebTask::CreateAnonymous();
    $retval = SUEXEC("nobody", "nobody",
		     "webmanage_instance -t " . $webtask->task_id() . " -- ".
Leigh B Stoller's avatar
Leigh B Stoller committed
552
                     "  $action $uuid $extrargs " .
553 554 555 556 557 558 559
                        (isset($filename) ? $filename : ""),
		     SUEXEC_ACTION_IGNORE);
    $webtask->Refresh();
    if (isset($filename)) {
        unlink($filename);
    }
    if ($retval != 0) {
560 561 562 563 564
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-1, "Internal error");
        }
        else {
565 566 567 568
            # This is an important error, tell tbops.
            if ($webtask->exitcode() == GENIRESPONSE_REFUSED) {
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
569 570
            # Need to pass exitcode through on this one.
            SPITAJAX_ERROR($webtask->exitcode(), $webtask->output());
571 572
        }
        $webtask->Delete();
573
        return;
574 575
    }
    $webtask->Delete();
576 577 578 579 580 581 582 583
    if ($lockout) {
        if (Do_Lockout()) {
            SPITAJAX_ERROR(-1, "Could not disable extensions");
            return;
        }
        # Do_Lockout() issued a success.
        return;
    }
584
    SPITAJAX_RESPONSE("Success");
585
    return;
586 587 588 589 590
bad:
    $webtask->Delete();
    sleep(1);
}

591 592 593 594 595 596 597 598
function Do_DenyExtension()
{
    Do_DenyOrMoreinfo("deny");
}
function Do_MoreInfo()
{
    Do_DenyOrMoreinfo("info");
}
Leigh B Stoller's avatar
Leigh B Stoller committed
599 600 601 602
function Do_SchedTerminate()
{
    Do_DenyOrMoreinfo("terminate");
}
603

604 605 606 607 608
#
# Request a console URL and pass back to the status page.
#
function Do_ConsoleURL()
{
609
    global $instance, $creator, $this_user, $suexec_output;
610
    global $ajax_args, $TBDB_TRUST_LOCALROOT;
611

612
    if (StatusSetupAjax(0)) {
613 614 615
	return;
    }
    if (!isset($this_user)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
616
	SPITAJAX_ERROR(1, "Only registered users can view node consoles");
617 618
	return;
    }
619
    if (!isset($ajax_args["node"])) {
620
	SPITAJAX_ERROR(1, "Missing node argument");
621 622 623 624 625 626 627 628 629
	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;
    }
630
    $webtask = WebTask::CreateAnonymous();
631
    $retval = SUEXEC("nobody", "nobody",
632 633
		     "webmanage_instance -t " . $webtask->task_id() . " ".
                     "  consoleurl $uuid " .
634
		     escapeshellarg($node),
635
		     SUEXEC_ACTION_IGNORE);
636
    $webtask->Refresh();
637

638 639 640 641
    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
642
        }
643 644 645 646
        else {
            # JS needs this exitcode.
            SPITAJAX_ERROR($webtask->exitcode(),
                           "Could not get console info: ". $webtask->output());
647
        }
648
        $webtask->Delete();
649
	return;
650
    }
651 652 653 654 655 656 657 658 659 660 661 662
    #
    # 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"]) &&
663
        (ISADMIN() || TBMinTrust($trust, $TBDB_TRUST_LOCALROOT))) {
664 665 666 667
        $blob["password"] = $taskdata["password"];
    }
    if (isset($taskdata["logurl"])) {
        $blob["logurl"] = $taskdata["logurl"];
668
    }
669
    SPITAJAX_RESPONSE($blob);
670
    $webtask->Delete();
671
    return;
672 673
}

674 675 676 677 678
#
# Fire off a snapshot.
#
function Do_Snapshot()
{
679
    global $this_user, $instance, $suexec_output;
680
    global $ajax_args;
Leigh B Stoller's avatar
Leigh B Stoller committed
681
    $errors = array();
682

683
    if (StatusSetupAjax(0)) {
684 685
	return;
    }
686 687
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can snapshot nodes");
688 689
	return;
    }
690 691
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];
Leigh B Stoller's avatar
Leigh B Stoller committed
692 693
    $checkonly = (isset($ajax_args["checkonly"]) &&
                  $ajax_args["checkonly"] == 1 ? 1 : 0);
694

695 696 697 698 699 700 701 702
    #
    # 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
703
                           "experiment is locked down.");
704 705 706
            return;
        }
    }
707 708 709 710
    if ($instance->status() != "ready") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }
711 712 713 714 715 716 717 718 719 720 721 722 723
    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;
    }
           
724 725 726 727
    #
    # The profile also has to belong to the user, since it is
    # going to be modified to use the new image.
    #
728 729
    $profile = Profile::Lookup($instance->profile_id(),
			       $instance->profile_version());
730 731 732 733
    if (!$profile) {
	SPITAJAX_ERROR(1, "Cannot lookup profile for instance");
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
734 735
    if ($operation == "update-profile" &&
        ($this_idx != $profile->creator_idx() && !ISADMIN())) {
Leigh B Stoller's avatar
Leigh B Stoller committed
736
	SPITAJAX_ERROR(1, "Not your profile to change. Make a copy first!");
737 738
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
739
    $optargs = "";
Leigh B Stoller's avatar
Leigh B Stoller committed
740
    if (isset($ajax_args["node_id"]) && $ajax_args["node_id"] != "") {
Leigh B Stoller's avatar
Leigh B Stoller committed
741 742
        $node_id = $ajax_args["node_id"];
        if (!TBvalid_vnode_id($node_id)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
743 744 745 746
            $errors["node_id"] = "Invalid node id";
        }
        else {
            $optargs .= " -n $node_id ";
Leigh B Stoller's avatar
Leigh B Stoller committed
747
        }
748
    } 
749 750 751 752
    if (isset($ajax_args["update_prepare"]) &&
        $ajax_args["update_prepare"]) {
        $optargs .= " -U ";
    }
753 754 755
    if (isset($ajax_args["wholedisk"]) && $ajax_args["wholedisk"]) {
        $optargs .= " -e ";
    }
756 757 758
    if (isset($ajax_args["nosnapshot"]) && $ajax_args["nosnapshot"]) {
        $optargs .= " -S ";
    }
759 760
    if (isset($ajax_args["imagename"]) && $ajax_args["imagename"] != "") {
        if (!TBvalid_imagename($ajax_args["imagename"])) {
Leigh B Stoller's avatar
Leigh B Stoller committed
761 762 763 764
            $errors["imagename"] = "Invalid imagename, alphanumeric only";
        }
        else {
            $optargs .= " -i " . escapeshellarg($ajax_args["imagename"]);
765
        }
Leigh B Stoller's avatar
Leigh B Stoller committed
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    }
    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;
795
    }
796 797
    $optargs .= " -O $operation ";

798 799 800
    #
    # Call out to the backend.
    #
801
    $webtask = WebTask::CreateAnonymous();
802
    $retval = SUEXEC($this_user->uid(), "nobody",
803
		     "webmanage_instance -t " . $webtask->task_id() . " " .
804
                     "  snapshot $uuid $optargs",
805
		     SUEXEC_ACTION_IGNORE);
806
    $webtask->Refresh();
Leigh B Stoller's avatar
Leigh B Stoller committed
807 808 809
    if (isset($filename)) {
        unlink($filename);
    }
810
    if ($retval != 0) {
811 812 813 814
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-11, "Internal error creating snapshot");
        }
815
        else {
816 817
            SPITAJAX_ERROR(1, "Could not create snapshot: ".
                           $webtask->output());
818
        }
819
        $webtask->Delete();
820
	return;
821
    }
822
    $webtask->Delete();
823 824 825 826 827 828 829 830
    SPITAJAX_RESPONSE("Success");
}

#
# Return snapshot status.
#
function Do_SnapshotStatus()
{
831
    global $this_user, $instance;
832 833
    global $ajax_args;

834
    if (StatusSetupAjax(0)) {
835 836
	return;
    }
837 838
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can snapshot nodes");
839 840
	return;
    }
841
    $this_idx = $this_user->uid_idx();
842 843 844 845 846
    if ($this_idx != $instance->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission");
	return;
    }
    $webtask = $instance->WebTask();
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    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
866 867 868
    if (isset($taskdata["copyback_uuid"])) {
        $blob["copyback_uuid"] = $taskdata["copyback_uuid"];
    }
869 870 871 872 873 874 875 876 877
    $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) {
878 879 880 881 882
            foreach ($sliver->StatusArray() as $status) {
                if (isset($status["sliver_data"]) &&
                    $status["client_id"] == $taskdata["client_id"]) {
                    $blob["node_status"] = $status["sliver_details"]["rawstate"];
                    break;
883 884 885 886
                }
            }
        }
    }
887 888 889 890
    if ($webtask->exited()) {
	# Success, but not sure what to report. Come back to this later.
	$blob["exited"]   = $webtask->exited();
	$blob["exitcode"] = $webtask->exitcode();
891 892 893
        if (isset($taskdata["image_name"])) {
            $blob["image_name"] = $taskdata["image_name"];
        }
894
    }
895 896 897
    SPITAJAX_RESPONSE($blob);
}

898 899 900 901 902
#
# Ask the backend to refresh sliverstatus
#
function Do_Refresh()
{
903
    global $this_user, $instance, $suexec_output;
904 905
    global $ajax_args;

906 907 908
    #
    # Guest users can do this.
    #
909
    if (StatusSetupAjax(0)) {
910 911
	return;
    }
912
    $this_idx = $this_user->uid_idx();
913 914 915 916
    $uuid = $ajax_args["uuid"];
    #
    # Call out to the backend.
    #
917
    $webtask = WebTask::CreateAnonymous();
918
    $retval = SUEXEC("nobody", "nobody",
919 920
		     "webmanage_instance -t " . $webtask->task_id() .
                     " refresh $uuid",
921
		     SUEXEC_ACTION_IGNORE);
922
    $webtask->Refresh();
923 924

    if ($retval != 0) {
925 926 927 928
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-11, "Internal error refreshing status");
        }
929
        else {
930
            SPITAJAX_ERROR(1, "Could not refresh status: ". $webtask->output());
931
        }
932
        $webtask->Delete();
933 934
	return;
    }
935
    $webtask->Delete();
936
    SPITAJAX_RESPONSE("Success");
937 938
}

Leigh B Stoller's avatar
Leigh B Stoller committed
939 940 941 942 943 944 945 946
#
# Reload rhe manifests.
#
function Do_ReloadTopology()
{
    global $this_user, $instance, $suexec_output;
    global $ajax_args;

947
    if (StatusSetupAjax(0)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
948 949 950 951 952 953 954
	return;
    }
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];
    #
    # Call out to the backend.
    #
955
    $webtask = WebTask::CreateAnonymous();
Leigh B Stoller's avatar
Leigh B Stoller committed
956
    $retval = SUEXEC("nobody", "nobody",
957 958
		     "webmanage_instance -t " . $webtask->task_id() .
                     "  getmanifests $uuid",
Leigh B Stoller's avatar
Leigh B Stoller committed
959
		     SUEXEC_ACTION_IGNORE);
Leigh B Stoller's avatar
Leigh B Stoller committed
960
    $webtask->Refresh();
Leigh B Stoller's avatar
Leigh B Stoller committed
961 962

    if ($retval != 0) {
963 964 965 966
        if (!$webtask->exited() || $retval < 0) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            SPITAJAX_ERROR(-11, "Internal error getting manifests");
        }
967
        else {
968
            SPITAJAX_ERROR(1, $webtask->output());
Leigh B Stoller's avatar
Leigh B Stoller committed
969
        }
970
        $webtask->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
971 972
	return;
    }
973
    $webtask->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
974 975 976
    SPITAJAX_RESPONSE("Success");
}

977
#
978
# Ask the backend to reboot or reload a node.
979
#
980
function Do_RebootOrReload($which)
981
{
982
    global $this_user, $instance, $suexec_output;
983
    global $ajax_args, $TBDB_TRUST_GROUPROOT;
984

985
    if (StatusSetupAjax(0)) {
986 987
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
988 989 990 991
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can reboot/reload nodes");
	return;
    }
992 993 994
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];

995 996 997 998 999 1000
    #
    # 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() &&
1001 1002
            $instance->Project()->UserTrust($this_user) <
            $TBDB_TRUST_GROUPROOT) {
1003 1004 1005 1006 1007
            SPITAJAX_ERROR(1, "Not enough permission, ".
                           "experiment is locked down");
            return;
        }
    }
1008

Leigh B Stoller's avatar
Leigh B Stoller committed
1009 1010
    if (!isset($ajax_args["node_ids"])) {
	SPITAJAX_ERROR(1, "Missing node_id list");
1011 1012
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1013 1014 1015 1016 1017 1018 1019
    $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);
1020 1021 1022 1023 1024 1025 1026 1027 1028
    }
    if ($instance->status() != "ready" && $instance->status() != "failed") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }

    #
    # Call out to the backend.
    #
1029
    $webtask = WebTask::CreateAnonymous();
1030
    $retval = SUEXEC("nobody", "nobody",
1031
		     "webmanage_instance -t " . $webtask->task_id() .
Leigh B Stoller's avatar
Leigh B Stoller committed
1032
                     "  $which $uuid $nodelist",
1033
		     SUEXEC_ACTION_IGNORE);
1034
    $webtask->Refresh();
1035 1036

    if ($retval != 0)