status.ajax 43.9 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2016 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 117 118 119 120 121

    foreach ($instance->slivers() as $sliver) {
        if (!$sliver->manifest()) {
            $havemanifests = 0;
        }
        else {
122 123
            if ($sliver->webtask_id() &&
                $webtask = WebTask::Lookup($sliver->webtask_id())) {
124 125 126 127 128
                $sliverstatus = $webtask->TaskValue("sliverstatus");
                if ($sliverstatus) {
                    $blob["sliverstatus"][$sliver->aggregate_urn()] =
                        $sliverstatus;
                }
129 130
            }
        }
131
        if ($sliver->public_url()) {
132 133
            $blob["sliverurls"][] = array("name" => $sliver->aggregate_name(),
                                          "url"  => $sliver->public_url());
134
        }
135
    }
136
    $blob["havemanifests"] = $havemanifests;
137 138 139 140

    # Reflect errors back to the user.
    $webtask = WebTask::LookupByObject($instance->uuid());
    if ($webtask && $webtask->exited()) {
141
        if ($webtask->exitcode() == GENIRESPONSE_INSUFFICIENT_NODES) {
142 143
            $blob["reason"]  = "Not enough free nodes, please try again later.";
            $blob["reason"] .= "\n\n";
144
        }
145
        elseif ($webtask->exitcode() == GENIRESPONSE_INSUFFICIENT_BANDWIDTH) {
146 147
            $blob["reason"]  = "Not enough available bandwidth for a link.\n\n";
        }
148
        elseif ($webtask->exitcode() == GENIRESPONSE_NO_MAPPING) {
149
            $blob["reason"]  = "Your topology could not be mapped to physical ".
Leigh B Stoller's avatar
Leigh B Stoller committed
150 151 152
                "resources. Clicking the 'Sliver' button above will provide ".
                "lots of info, some of which might be useful in figuring out ".
                "why it failed.\n\n";
153
        }
154
        elseif ($webtask->exitcode() == GENIRESPONSE_TIMEDOUT) {
155 156 157
            $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";
158
        }
159
        elseif ($webtask->exitcode() == GENIRESPONSE_BADARGS) {
160 161 162 163 164 165
            #
            # 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";
166
        }
167 168 169 170 171 172 173 174
        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";
        }
175
        else {
176
            $blob["reason"] = "";
177
        }
178
        $blob["reason"] .= htmlentities($webtask->TaskValue("output"));
179
    }
180
    SPITAJAX_RESPONSE($blob);
181 182 183 184 185 186 187
}

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

190
    if (StatusSetupAjax(1)) {
191 192 193
	return;
    }
    $uuid = $instance->uuid();
194 195 196 197 198 199 200 201 202 203
    $webtask_id = WebTask::GenerateID();

    if ($instance->admin_lockdown() || $instance->user_lockdown()) {
        if (! (isset($this_user) &&
               ($instance->creator() == $this_user->uid() || ISADMIN()))) {
            SPITAJAX_ERROR(1, "Not enough permission to terminate; ".
                           "experiment is locked down");
            return;
        }
        $override = substr($uuid, 2, 5);
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        if (! (isset($ajax_args["lockdown_override"]) &&
               $ajax_args["lockdown_override"] == $override)) {
            SPITAJAX_ERROR(1, "Lockdown override is incorrect");
            return;
        }
        $retval = SUEXEC($this_user->uid(), "nobody",
                         "webmanage_instance -t $webtask_id -- ".
                         "  lockdown $uuid clear all",
                         SUEXEC_ACTION_CONTINUE);
        if ($retval) {
            $webtask = WebTask::Lookup($webtask_id);

            if ($webtask && $webtask->exited()) {
                SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
                $webtask->Delete();
            }
            else {
                SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
            }
            return;
        }
    }
227 228 229
    # 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.
230
    $retval = SUEXEC("nobody", "nobody",
231
                     "webmanage_instance terminate $uuid",
232
                     SUEXEC_ACTION_IGNORE);
233 234 235 236 237

    if ($retval == 0) {
	SPITAJAX_RESPONSE("");
	return;
    }
238 239
    SPITAJAX_ERROR(-1, "Your experiment is probably busy, ".
        "please try again later.");
240 241 242 243 244 245 246 247 248
}

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

249
    if (StatusSetupAjax(0)) {
250 251 252
	return;
    }

253 254 255 256 257 258 259 260
    $blob = array();

    foreach ($instance->slivers() as $sliver) {
        if ($sliver->manifest()) {
            $blob[$sliver->aggregate_urn()] = $sliver->manifest();
        }
    }
    SPITAJAX_RESPONSE($blob);
261 262 263 264 265 266 267
}

#
# SSH Auth Object
#
function Do_GetSSHAuthObject()
{
268
    global $instance, $creator, $this_user;
269 270 271 272 273 274 275 276
    global $ajax_args;

    if (!isset($ajax_args["hostport"])) {
	SPITAJAX_ERROR(1, "Missing hostport");
	return 1;
    }
    $hostport = $ajax_args["hostport"];
    
277
    if (StatusSetupAjax(0)) {
278 279
	return;
    }
280
    if (! ((isset($this_user) && $instance->CanDoSSH($this_user)) ||
Leigh B Stoller's avatar
Leigh B Stoller committed
281 282
	   (isset($_COOKIE['quickvm_user']) &&
	    $_COOKIE['quickvm_user'] == $creator->uuid()))) {
283 284
	SPITAJAX_ERROR(1, "Not allowed to ssh; ".
                       "only the creator or a project member");
285 286 287
	return;
    }
    
288
    $nodeid = $ajax_args["nodeid"];
289 290
    $auth   = SSHAuthObject(isset($this_user) ?
                            $this_user->uid() : $creator->uid(), $hostport);
291 292 293 294 295 296 297
    if (!$auth) {
	SPITAJAX_ERROR(1, "Could not create authentication object");
	return;
    }
    SPITAJAX_RESPONSE($auth);
}

298 299 300 301 302 303 304 305 306 307 308 309 310
function Do_RequestExtension()
{
    global $instance, $creator, $this_user, $suexec_output;
    global $ajax_args;
    $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();
311 312
            if (!(ISADMINISTRATOR() ||
                  FeatureEnabled("NewPortalExtend", $this_user, $group))) {
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
                TBERROR("Using old extension code", 0);
                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"] == "") {
	SPITAJAX_ERROR(1, "Missing number of days");
	goto bad;
    }
    $wanted = $ajax_args["howlong"];
    if (! preg_match("/^\d+$/", $wanted)) {
	SPITAJAX_ERROR(1, "Invalid characters in days");
	goto bad;
    }
    if (ISADMIN()) {
	if ($wanted < 1 || $wanted > 365) {
	    SPITAJAX_ERROR(1, "Must be an integer 1 <= days <= 365");
	    goto bad;
	}
	if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
            $reason = $ajax_args["reason"];
        }
    }
    else {
	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() . " -- ".
                     "  extend $uuid $wanted ".
                        (isset($filename) ? $filename : ""),
		     SUEXEC_ACTION_IGNORE);
    $webtask->Refresh();
    if (isset($filename)) {
        unlink($filename);
    }
    if ($retval != 0) {
        if ($webtask->exited()) {
            SPITAJAX_ERROR($webtask->exitcode(), $webtask->TaskValue("output"));

            #
            # This is an important error, tell tbops.
            #
            if ($webtask->exitcode() == GENIRESPONSE_REFUSED) {
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
        }
        elseif ($retval < 0) {
            SPITAJAX_ERROR($retval, "Internal error, cannot proceed.");
            # Notify tbops.
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
        }
        else {
            SPITAJAX_ERROR($retval, $suexec_output);
        }
        $webtask->Delete();
        goto bad;
    }
    # Refresh. 
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
    $new_expires = date("Y-m-d H:i:s T", strtotime($slice->expires()));
    
    $webtask->Delete();
    SPITAJAX_RESPONSE($new_expires);
bad:
delay:
    sleep(1);
}

function Do_DenyExtension()
{
    global $instance, $creator, $this_user, $suexec_output;
    global $ajax_args;

    if (StatusSetupAjax(1)) {
	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;
    }
    if (isset($ajax_args["message"]) && $ajax_args["message"] != "") {
        $message = $ajax_args["message"];
        
        if (!TBvalid_fulltext($message)) {
	    SPITAJAX_ERROR(1, "Illegal characters in message");
	    goto bad;
        }
        $filename = tempnam("/tmp", "extension");
        $fp = fopen($filename, "w");
        fwrite($fp, $message);
        fclose($fp);
    }        
    $webtask = WebTask::CreateAnonymous();
    $retval = SUEXEC("nobody", "nobody",
		     "webmanage_instance -t " . $webtask->task_id() . " -- ".
                     "  denyextension $uuid " .
                        (isset($filename) ? $filename : ""),
		     SUEXEC_ACTION_IGNORE);
    $webtask->Refresh();
    if (isset($filename)) {
        unlink($filename);
    }
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);    
    if ($retval != 0) {
        if ($webtask->exited()) {
            SPITAJAX_ERROR($webtask->exitcode(), $webtask->TaskValue("output"));

            #
            # This is an important error, tell tbops.
            #
            if ($webtask->exitcode() == GENIRESPONSE_REFUSED) {
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
        }
        elseif ($retval < 0) {
            SPITAJAX_ERROR($retval, "Internal error, cannot proceed.");
            # Notify tbops.
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
        }
        else {
            SPITAJAX_ERROR($retval, $suexec_output);
        }
        $webtask->Delete();
        goto bad;
    }
    $webtask->Delete();
    SPITAJAX_RESPONSE("Success");
bad:
    $webtask->Delete();
    sleep(1);
}

479 480 481
#
# Request automatic extension.
#
482
function Do_RequestExtensionOld()
483
{
484
    global $instance, $creator, $this_user, $suexec_output;
485
    global $ajax_args;
486
    global $TBMAIL_OPS, $APTMAIL, $EXTENSIONS, $APTBASE;
487 488
    $autoextend_maximum = TBGetSiteVar("aptui/autoextend_maximum");
    $autoextend_maxage  = TBGetSiteVar("aptui/autoextend_maxage");
489
    $reason  = "";
490
    $message = "";
491
    $needapproval = 0;
492
    $granted = 0;
493 494 495 496 497

    $uuid = $instance->uuid();
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
    if (!slice) {
	SPITAJAX_ERROR(1, "no slice for instance");
498
	goto bad;
499 500
    }
    $expires_time = strtotime($slice->expires());
501
    $created_time = strtotime($instance->created());
Leigh B Stoller's avatar
Leigh B Stoller committed
502 503 504 505 506
    $instance_name = $instance->name();
    # Until old instances are gone.
    if (!$instance_name) {
        list ($a,$b,$instance_name) = Instance::ParseURN($slice->urn());
    }
507 508 509 510 511 512
    #
    # If no physical nodes (only VMs), double the maximums.
    #
    if (!$instance->physnode_count()) {
        $autoextend_maxage  *= 2;
    }
513

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

520 521 522 523
    if (!isset($ajax_args["howlong"]) || $ajax_args["howlong"] == "") {
	SPITAJAX_ERROR(1, "Missing number of days");
	goto bad;
    }
524 525
    $granted = $wanted = $ajax_args["howlong"];
    if (! preg_match("/^\d+$/", $wanted)) {
526 527 528 529
	SPITAJAX_ERROR(1, "Invalid characters in days");
	goto bad;
    }

530
    if (ISADMIN()) {
531
	if ($wanted < 1 || $wanted > 365) {
532
	    SPITAJAX_ERROR(1, "Must be an integer 1 <= days <= 365");
533
	    goto bad;
534
	}
535 536 537 538
        $reason = "Your experiment was extended by the site administrator.\n";
	if (isset($ajax_args["reason"]) && $ajax_args["reason"] != "") {
            $reason .= "\n" . $ajax_args["reason"];
        }
539 540 541 542
    }
    else {
	if (!isset($ajax_args["reason"]) || $ajax_args["reason"] == "") {
	    SPITAJAX_ERROR(1, "Missing reason");
543
	    goto bad;
544 545 546
	}
	$reason  = $ajax_args["reason"];

547 548 549 550 551
        if (!TBvalid_fulltext($reason)) {
	    SPITAJAX_ERROR(1, "Illegal characters in reason");
	    goto bad;
        }

552 553 554 555 556
	#
	# Guest users are treated differently.
	#
	if (!isset($this_user)) {
            # Only extend for 24 hours. More later.
557
            $granted = 1;
558

559
	    if ($expires_time > time() + (3600 * 24 * $granted)) {
560
		SPITAJAX_ERROR(1, "You still have a day left. ".
561 562
			       "Try again tomorrow");
		goto delay;
563 564 565
	    }
	}
	else {
566
            $diff  = $expires_time - time();
Leigh B Stoller's avatar
Leigh B Stoller committed
567
            $cdiff = time() - $created_time;
Leigh B Stoller's avatar
Leigh B Stoller committed
568 569 570 571 572 573 574 575 576 577

            #
            # If admin lockout, we are refusing any more free time.
            #
            if ($instance->extension_lockout()) {
                $needapproval = 1;
                $granted = 0;
                $message = "because you are not allowed any more ".
                    "free extensions";
            }
578
            #
579
            # After maxage, all extension requests require admin approval.
580
            #
Leigh B Stoller's avatar
Leigh B Stoller committed
581
            elseif ($cdiff > (3600 * 24 * $autoextend_maxage)) {
582 583 584 585
                #
                # Well, unless they asked for less then the free grant,
                # which is a nice loophole people will probably notice.
                #
586
                $granted = 2;
587 588 589 590 591 592
                
                if ($wanted > $granted) {
                    $needapproval = 1;
                    $message = "because it was started more then ".
                        "$autoextend_maxage days ago";
                }
593
            }
594 595 596
            #
            # Temporary for GEC23
            #
597 598
            elseif (0 && (time() + ($wanted * 3600 * 24) >
                          strtotime("2015-06-15 12:00:00"))) {
599 600 601 602
                $granted = 1;
                $needapproval = 1;
                $message = "because the testbed is mostly reserved for GEC23";
            }
603
	    #
604 605 606 607 608
	    # Registered users are granted up to the autoextend_maximum
            # automatically. Beyond that, requires approval, but we still
            # give them whatever the free extension is, since we want
            # to give them extra time until the next meeting of the
            # "resource management committee."
609
	    #
610 611 612 613 614 615 616 617 618 619 620 621 622 623
	    elseif ($wanted > $autoextend_maxage) {
                #
                # We have plenty of time left, no extension just a message.
                #
                if ($diff > (3600 * 24 * 7)) {
                    needAdminApproval($wanted, 0, $reason,
                                      "because it was for longer then ".
                                      "$autoextend_maximum days");
                    goto delay;
                }
                $needapproval = 1;
                $granted = $autoextend_maximum;
                $message = "because it was for longer then ".
                    "$autoextend_maximum days";
624
	    }
625 626 627 628 629 630
            else {
                if ($diff > (3600 * 24 * 7)) {
                    SPITAJAX_ERROR(1, "You still have a week left!");
                    goto bad;
                }
            }
631
	    #
632 633 634 635
	    # The most we allow is the autoextend_maximum out, no
	    # matter what they asked for. So, if the autoextend_maximum
	    # is a week and there are five days left and they asked
	    # for seven, we give them two.
636
	    #
637 638 639
            if ($expires_time + ($granted * 3600 * 24) >
                time() + (3600 * 24 * $autoextend_maximum)) {
		$seconds = (3600 * 24 * $autoextend_maximum) - $diff;
640
                $granted = intval($seconds / (3600 * 24));
641
	    }
642
        }
643
    }
644 645
    if ($granted > 0) {
        $seconds = 3600 * 24 * $granted;
646
        $retval = SUEXEC("nobody", "nobody",
647
                         "webmanage_instance extendold $uuid $seconds",
648
                         SUEXEC_ACTION_IGNORE);
649
    }
650 651

    if ($retval == 0) {
652
	# Refresh. 
653
	$slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
Leigh B Stoller's avatar
Leigh B Stoller committed
654 655
	$new_expires = date("Y-m-d H:i:s T", strtotime($slice->expires()));
        $created = date("Y-m-d H:i:s T", strtotime($instance->created()));
656 657
        $before = date("Y-m-d H:i:s T", $expires_time);
        $now = date("Y-m-d H:i:s T", time());
Leigh B Stoller's avatar
Leigh B Stoller committed
658
        list($cluster) = Instance::ParseURN($instance->aggregate_urn());
659

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        #
        # We store each extension request in an ongoing text field.
        #
        $text =
            "Date: $now\n".
            "Wanted: $wanted, Granted: $granted\n".
            "Before: $before\n".
            "After $new_expires\n".
            "Reason:\n".
            $reason . "\n\n".
            "-----------------------------------------------\n";
        $instance->AddExtensionHistory($text);

        if ($needapproval) {
            needAdminApproval($wanted, $granted, $reason, $message);
            if (!$granted)
                goto delay;
            return;
        }
679 680
	SPITAJAX_RESPONSE($new_expires);

681
	$instance->SendEmail($creator->email(),
Leigh B Stoller's avatar
Leigh B Stoller committed
682
	       "Experiment Extension: $instance_name",
683 684 685 686 687
               (ISADMIN() ? $reason :
                "A request to extend your experiment was made and ".
                "granted.\n".
                "Your reason was:\n\n". $reason) .
               "\n\n".
Leigh B Stoller's avatar
Leigh B Stoller committed
688 689 690
               "Your experiment was started on $created\n".
 	       "Your experiment will now expire at $new_expires\n".
               "It is running on $cluster\n\n\n".
691
               "$APTBASE/status.php?uuid=$uuid\n",
692 693
	       "From: $EXTENSIONS\n" .
	       "BCC: $EXTENSIONS");
694 695 696 697 698 699 700 701
        #
        # We do not want to overwrite the reason in the DB if this
        # was an admin extension, we want to keep whatever the user
        # has written previously.
        #
        if (! ISADMIN()) {
            $instance->SetExtensionReason($reason);
        }
702
        else {
703
            $instance->SetExtensionRequested(0);
704
        }
705
        $instance->BumpExtensionCount($granted);
706 707
    }
    elseif ($retval > 0) {
708 709 710 711 712 713
        #
        # This is an important error, tell tbops.
        #
        if ($retval == GENIRESPONSE_REFUSED) {
            SUEXECERROR(SUEXEC_ACTION_CONTINUE);
        }
714
	SPITAJAX_ERROR(1, $suexec_output);
715
	goto bad;
716 717
    }
    else {
718
        SUEXECERROR(SUEXEC_ACTION_CONTINUE);
719
	SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
720
	goto bad;
721
    }
722 723
    return;
bad:
724 725 726 727 728 729 730 731 732 733
delay:
    sleep(1);
}

#
# Helper for above.
#
function needAdminApproval($wanted, $granted, $reason, $message)
{
    global $instance, $creator, $this_user, $suexec_output;
734
    global $EXTENSIONS, $APTBASE;
735 736 737 738 739 740 741 742

    $uuid = $instance->uuid();
    # Subtract out the extra time we added above.
    $howlong = $wanted - $granted;
    $url = "$APTBASE/status.php?uuid=$uuid&extend=$howlong";

    # Refresh. 
    $slice = GeniSlice::Lookup("sa", $instance->slice_uuid());
Leigh B Stoller's avatar
Leigh B Stoller committed
743
    $new_expires = date("Y-m-d H:i:s T",
744
                        strtotime($slice->expires()) + ($howlong * 3600 * 24));
Leigh B Stoller's avatar
Leigh B Stoller committed
745 746
    $created = date("Y-m-d H:i:s T", strtotime($instance->created()));
    list($cluster) = Instance::ParseURN($instance->aggregate_urn());
Leigh B Stoller's avatar
Leigh B Stoller committed
747 748 749 750 751 752

    $instance_name = $instance->name();
    # Until old instances are gone.
    if (!$instance_name) {
        list ($a,$b,$instance_name) = Instance::ParseURN($slice->urn());
    }
753
		    
754
    $instance->SendEmail($EXTENSIONS,
Leigh B Stoller's avatar
Leigh B Stoller committed
755
        "Experiment Extension Request: $instance_name",
756 757
        "A request to extend this experiment was made but requires\n".
        "administrator approval" .
Leigh B Stoller's avatar
Leigh B Stoller committed
758
        ($message ? " $message" : "") . ".\n\n" .
759 760 761
        "The request was for $wanted days, we granted $granted days, ".
        "the reason given is:\n\n".
        $reason . "\n\n".
762
        "This experiment was started on $created\n".
763
        "Granting the request would set the expiration to $new_expires\n".
Leigh B Stoller's avatar
Leigh B Stoller committed
764
        "It is running on $cluster\n".
765
        "\n\n". $url . "\n\n",
766 767 768
        "From: " . $creator->email());

    $instance->SetExtensionReason($reason);
769
    $instance->BumpExtensionCount($granted);
770
    $instance->SetExtensionRequested(1);
771 772 773 774
            
    # XXX 
    SPITAJAX_ERROR(2, "Your request requires admininstrator approval".
                   ($message ? " because $message" : "") . ". " .
Leigh B Stoller's avatar
Leigh B Stoller committed
775 776
                   "You will receive email if/when your ".
                   "request is granted (or denied). Thanks!");
777
    return;
778
}
779

780 781 782 783 784
#
# Request a console URL and pass back to the status page.
#
function Do_ConsoleURL()
{
785
    global $instance, $creator, $this_user, $suexec_output;
786 787
    global $ajax_args;

788
    if (StatusSetupAjax(0)) {
789 790 791
	return;
    }
    if (!isset($this_user)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
792
	SPITAJAX_ERROR(1, "Only registered users can view node consoles");
793 794
	return;
    }
795
    if (!isset($ajax_args["node"])) {
796
	SPITAJAX_ERROR(1, "Missing node argument");
797 798 799 800 801 802 803 804 805
	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;
    }
806
    $webtask_id = WebTask::GenerateID();
807
    $retval = SUEXEC("nobody", "nobody",
808 809
		     "webmanage_instance -t $webtask_id -- consoleurl $uuid " .
		     escapeshellarg($node),
810
		     SUEXEC_ACTION_IGNORE);
811
    $webtask = WebTask::Lookup($webtask_id);
812 813

    if ($retval == 0) {
814 815 816 817 818 819
        $taskdata = $webtask->TaskData();
        $blob = array();
        $blob["url"] = $taskdata["url"];
        if (isset($taskdata["password"])) {
            $blob["password"] = $taskdata["password"];
        }
820 821 822
        if (isset($taskdata["logurl"])) {
            $blob["logurl"] = $taskdata["logurl"];
        }
823
	SPITAJAX_RESPONSE($blob);
824 825
	$webtask->Delete();
	return;
826
    }
827 828 829
    elseif ($retval < 0) {
        SUEXECERROR(SUEXEC_ACTION_CONTINUE);
    }
830
    if ($webtask) {
Leigh B Stoller's avatar
Leigh B Stoller committed
831
	SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
832
	$webtask->Delete();
833
    }
834 835 836
    elseif ($suexec_output != "") {
        SPITAJAX_ERROR(1, $suexec_output);
    }
837 838 839 840 841
    else {
	SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
    }
}

842 843 844 845 846
#
# Fire off a snapshot.
#
function Do_Snapshot()
{
847
    global $this_user, $instance, $suexec_output;
848 849
    global $ajax_args;

850
    if (StatusSetupAjax(1)) {
851 852
	return;
    }
853 854
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can snapshot nodes");
855 856
	return;
    }
857 858 859
    $this_idx = $this_user->uid_idx();
    $uuid = $ajax_args["uuid"];
    
860 861 862 863 864 865 866 867 868 869 870 871
    if ($this_idx != $instance->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission. Maybe Clone instead?");
	return;
    }
    if ($instance->status() != "ready") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }
    #
    # The profile also has to belong to the user, since it is
    # going to be modified to use the new image.
    #
872 873
    $profile = Profile::Lookup($instance->profile_id(),
			       $instance->profile_version());
874 875 876 877 878 879 880 881
    if (!$profile) {
	SPITAJAX_ERROR(1, "Cannot lookup profile for instance");
	return;
    }
    if ($this_idx != $profile->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not your profile to change. Clone first!");
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
882
    $optargs = "";
Leigh B Stoller's avatar
Leigh B Stoller committed
883
    if (isset($ajax_args["node_id"]) && $ajax_args["node_id"] != "") {
Leigh B Stoller's avatar
Leigh B Stoller committed
884 885 886 887 888
        $node_id = $ajax_args["node_id"];
        if (!TBvalid_vnode_id($node_id)) {
            SPITAJAX_ERROR(1, "Bad node id");
            return;
        }
889
        $optargs .= " -n $node_id ";
Leigh B Stoller's avatar
Leigh B Stoller committed
890 891 892 893 894 895

        if (isset($ajax_args["update_profile"]) &&
            $ajax_args["update_profile"]) {
            $optargs .= " -u all ";
        }
    }
896 897 898 899 900 901
    else {
        #
        # Single node profile snapshot, we always update the profile.
        #
        $optargs .= " -u node ";
    }
902 903 904 905
    if (isset($ajax_args["update_prepare"]) &&
        $ajax_args["update_prepare"]) {
        $optargs .= " -U ";
    }
906 907 908 909
    
    #
    # Call out to the backend.
    #
910
    $webtask_id = WebTask::GenerateID();
911
    $retval = SUEXEC($this_user->uid(), "nobody",
Leigh B Stoller's avatar
Leigh B Stoller committed
912
		     "webmanage_instance -t $webtask_id -- ".
913
                     "  snapshot $uuid $optargs",
914
		     SUEXEC_ACTION_IGNORE);
915
    $webtask = WebTask::Lookup($webtask_id);
916 917 918

    if ($retval != 0) {
	if ($retval < 0) {
919
	    SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
920 921 922
	    # Notify tbops.
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	}
923
	elseif ($webtask) {
Leigh B Stoller's avatar
Leigh B Stoller committed
924
	    SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
925
	}
926 927 928
	elseif ($suexec_output != "") {
	    SPITAJAX_ERROR(1, $suexec_output);
        }
929
	else {
930
	    SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
931
	}
932 933 934
	if ($webtask) {
	    $webtask->Delete();
	}
935
	return;
936
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
937
    if ($webtask && $webtask->exited()) {
938 939
	$webtask->Delete();
    }
940 941 942 943 944 945 946 947
    SPITAJAX_RESPONSE("Success");
}

#
# Return snapshot status.
#
function Do_SnapshotStatus()
{
948
    global $this_user, $instance;
949 950
    global $ajax_args;

951
    if (StatusSetupAjax(1)) {
952 953
	return;
    }
954 955
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can snapshot nodes");
956 957
	return;
    }
958 959
    $this_idx = $this_user->uid_idx();

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    if ($this_idx != $instance->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission");
	return;
    }
    $webtask = WebTask::LookupByObject($instance->uuid());
    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
984 985 986
    if (isset($taskdata["copyback_uuid"])) {
        $blob["copyback_uuid"] = $taskdata["copyback_uuid"];
    }
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    $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) {
            $slwebtask = WebTask::Lookup($sliver->webtask_id());
            $sliverstatus = $slwebtask->TaskValue("sliverstatus");
            if ($sliverstatus) {
                foreach ($sliverstatus as $node_id => $node_status) {
                    if ($node_id == $taskdata["client_id"]) {
                        $blob["node_status"] = $node_status["rawstate"];
                        break;
                    }
                }
            }
        }
    }
1008 1009 1010 1011
    if ($webtask->exited()) {
	# Success, but not sure what to report. Come back to this later.
	$blob["exited"]   = $webtask->exited();
	$blob["exitcode"] = $webtask->exitcode();
1012 1013 1014
        if (isset($taskdata["image_name"])) {
            $blob["image_name"] = $taskdata["image_name"];
        }
1015 1016
	$webtask->Delete();
    }
1017 1018 1019
    SPITAJAX_RESPONSE($blob);
}

1020 1021 1022 1023 1024
#
# Ask the backend to refresh sliverstatus
#
function Do_Refresh()
{
1025
    global $this_user, $instance, $suexec_output;
1026 1027
    global $ajax_args;

1028 1029 1030
    #
    # Guest users can do this.
    #
1031
    if (StatusSetupAjax(0)) {
1032 1033
	return;
    }
1034
    $this_idx = $this_user->uid_idx();
1035 1036 1037 1038 1039
    $uuid = $ajax_args["uuid"];
    #
    # Call out to the backend.
    #
    $webtask_id = WebTask::GenerateID();
1040
    $retval = SUEXEC("nobody", "nobody",
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
		     "webmanage_instance -t $webtask_id -- refresh $uuid",
		     SUEXEC_ACTION_IGNORE);
    $webtask = WebTask::Lookup($webtask_id);

    if ($retval != 0) {
	if ($retval < 0) {
	    SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
	    # Notify tbops.
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	}
	elseif ($webtask) {
	    SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
	}
1054 1055 1056
	elseif ($suexec_output != "") {
	    SPITAJAX_ERROR(1, $suexec_output);
        }
1057 1058 1059 1060 1061 1062 1063 1064
	else {
	    SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
	}
	if ($webtask) {
	    $webtask->Delete();
	}
	return;
    }
1065
    SPITAJAX_RESPONSE("Success");
1066 1067 1068
}

#
1069
# Ask the backend to reboot or reload a node.
1070
#
1071
function Do_RebootOrReload($which)
1072
{
1073
    global $this_user, $instance, $suexec_output;
1074 1075
    global $ajax_args;

1076 1077 1078
    if (StatusSetupAjax(1)) {
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1079 1080 1081 1082
    if (!isset($this_user)) {
	SPITAJAX_ERROR(1, "Only registered users can reboot/reload nodes");
	return;
    }
1083
    $this_idx = $this_user->uid_idx();
1084
    $uuid = $ajax_args["uuid"];
1085

Leigh B Stoller's avatar
Leigh B Stoller committed
1086 1087
    if (!isset($ajax_args["node_ids"])) {
	SPITAJAX_ERROR(1, "Missing node_id list");
1088 1089
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1090 1091 1092 1093 1094 1095 1096
    $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);
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    }
    if ($this_idx != $instance->creator_idx() && !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission. Maybe Clone instead?");
	return;
    }
    if ($instance->status() != "ready" && $instance->status() != "failed") {
	SPITAJAX_ERROR(1, "Experiment is currently busy");
	return;
    }

    #
    # Call out to the backend.
    #
    $webtask_id = WebTask::GenerateID();
1111
    $retval = SUEXEC("nobody", "nobody",
1112
		     "webmanage_instance -t $webtask_id -- ".
Leigh B Stoller's avatar
Leigh B Stoller committed
1113
                     "  $which $uuid $nodelist",
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
		     SUEXEC_ACTION_IGNORE);
    $webtask = WebTask::Lookup($webtask_id);

    if ($retval != 0) {
	if ($retval < 0) {
	    SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
	    # Notify tbops.
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	}
	elseif ($webtask) {
	    SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
	}
1126 1127 1128 1129
	elseif ($suexec_output != "") {
	    SPITAJAX_ERROR(1, $suexec_output);
        }
        else {
Leigh B Stoller's avatar
Leigh B Stoller committed
1130
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
	    SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
	}
	if ($webtask) {
	    $webtask->Delete();
	}
	return;
    }
    if ($webtask) {
	$webtask->Delete();
    }
    SPITAJAX_RESPONSE("Success");
}
1143 1144 1145 1146 1147 1148 1149 1150
function Do_Reboot()
{
    Do_RebootOrReload("reboot");
}
function Do_Reload()
{
    Do_RebootOrReload("reload");
}
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
#
# 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.
    #
    $webtask_id = WebTask::GenerateID();
    $retval = SUEXEC("nobody", "nobody",
		     "webmanage_instance -t $webtask_id -- ".
                     "  deletenodes $uuid $nodelist",
		     SUEXEC_ACTION_IGNORE);
    $webtask = WebTask::Lookup($webtask_id);

    if ($retval != 0) {
	if ($retval < 0) {
	    SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
	    # Notify tbops.
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	}
	elseif ($webtask) {
	    SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
	}
	elseif ($suexec_output != "") {
	    SPITAJAX_ERROR(1, $suexec_output);
        }
        else {
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
	}
	if ($webtask) {
	    $webtask->Delete();
	}
	return;
    }
    if ($webtask) {
	$webtask->Delete();
    }
    SPITAJAX_RESPONSE("Success");
}

1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
#
# Decrypt the blocks using the per-instance private key.
#
function Do_DecryptBlocks()
{
    global $this_user, $instance, $suexec_output;
    global $ajax_args;

    if (StatusSetupAjax(1)) {
	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
1286 1287 1288 1289 1290 1291 1292 1293
#
# Set or clear the lockout flag
#
function Do_Lockout()
{
    global $this_user;
    global $ajax_args;

1294 1295 1296 1297
    if (!isset($this_user) || !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission.");
	return;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    $this_idx = $this_user->uid_idx();

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
	return;
    }
    if (!isset($ajax_args["lockout"])) {
	SPITAJAX_ERROR(1, "Missing lockout value");
	return;
    }
    $uuid = $ajax_args["uuid"];
    $instance = Instance::Lookup($uuid);
    if (!$instance) {
	SPITAJAX_ERROR(1, "Unknown instance uuid");
	return;
    }
    $lockout = ($ajax_args["lockout"] ? 1 : 0);
    if (!DBQueryWarn("update apt_instances set extension_adminonly='$lockout' ".
                     "where uuid='$uuid'")) {
	SPITAJAX_ERROR(1, "Database failure.");
	return;
    }
    SPITAJAX_RESPONSE("Success");
}

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
#
# Handle Quarantine request/clear.
#
function Do_Quarantine()
{
    global $this_user;
    global $ajax_args;

    if (!isset($this_user) || !ISADMIN()) {
	SPITAJAX_ERROR(1, "Not enough permission.");
	return;
    }
    $this_idx = $this_user->uid_idx();

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
	return;
    }
    if (!isset($ajax_args["quarantine"])) {
	SPITAJAX_ERROR(1, "Missing quarantine value");
	return;
    }
    $which = ($ajax_args["quarantine"] ? "set" : "clear");
    $uuid = $ajax_args["uuid"];
    $instance = Instance::Lookup($uuid);
    if (!$instance) {
	SPITAJAX_ERROR(1, "Unknown instance uuid");
	return;
    }

    $webtask_id = WebTask::GenerateID();
    $retval = SUEXEC($this_user->uid(), "nobody",
		     "webmanage_instance -t $webtask_id -- panic $uuid $which",
		     SUEXEC_ACTION_IGNORE);
    $webtask = WebTask::Lookup($webtask_id);

    if ($retval != 0) {
	if ($retval < 0) {
	    SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
	    # Notify tbops.
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	}
	elseif ($webtask) {
	    SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
	}
	elseif ($suexec_output != "") {
	    SPITAJAX_ERROR(1, $suexec_output);
        }
        else {
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
	}
	if ($webtask) {
	    $webtask->Delete();
	}
	return;
    }
    if ($webtask) {
	$webtask->Delete();
    }
    SPITAJAX_RESPONSE("Success");
}

1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
function Do_Linktest()
{
    global $instance, $this_user, $ajax_args, $urn_mapping;

    if (StatusSetupAjax(0)) {
	return;
    }
    if (!isset($ajax_args["action"])) {
	SPITAJAX_ERROR(1, "Missing action");
	return;
    }
    $action = $ajax_args["action"];
    $uuid = $ajax_args["uuid"];
    $blob = array();
    $level = 1;

    if (isset($ajax_args["level"])) {
        $level = $ajax_args["level"];
        if (!preg_match("/^\d+$/", $level) || $level < 1 || $level > 4) {
            SPITAJAX_ERROR(1, "Bad level request");
            return;
        }
    }

    if ($action == "start") {
        if ($instance->status() == "linktest") {
            SPITAJAX_ERROR(1, "Linktest already running");
            return;
        }
        $webtask_id = WebTask::GenerateID();
1416
        $retval = SUEXEC("nobody", "nobody",
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
                         "webmanage_instance -t $webtask_id -- ".
                         "linktest $uuid $level",
                         SUEXEC_ACTION_IGNORE);
        $webtask = WebTask::Lookup($webtask_id);

        if ($retval != 0) {
            if ($retval < 0) {
                SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
                # Notify tbops.
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
            elseif ($webtask) {
                SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
            }
            else {
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
                SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
            }
            if ($webtask) {
                $webtask->Delete();
            }
            return;
        }
        # This one does not tell us anything.
        $webtask->Delete();
        # Look at per sliver.
        foreach ($instance->slivers() as $sliver) {
            if ($sliver->webtask_id() &&
                $webtask = WebTask::Lookup($sliver->webtask_id())) {

1447 1448 1449
                if (!($sliver->physnode_count() || $sliver->virtnode_count())) {
                    continue;
                }
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
                $tmp = array();
                $tmp["status"] = $webtask->TaskValue("status");
                if ($webtask->TaskValue("status") == "running") {
                    $tmp["url"] = $webtask->TaskValue("url");
                }
                else {
                    $tmp["results"] = $webtask->TaskValue("results");
                }
                $blob[$urn_mapping[$sliver->aggregate_urn()]] = $tmp;
            }
        }
        SPITAJAX_RESPONSE($blob);
    }
    elseif ($action == "stop") {
        if ($instance->status() != "linktest") {
            SPITAJAX_RESPONSE(0);
            return;
        }
        $webtask_id = WebTask::GenerateID();
1469
        $retval = SUEXEC("nobody", "nobody",
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
                         "webmanage_instance -t $webtask_id -- ".
                         "linktest $uuid -k",
                         SUEXEC_ACTION_IGNORE);
        $webtask = WebTask::Lookup($webtask_id);

        if ($retval != 0) {
            if ($retval < 0) {
                SPITAJAX_ERROR(-11, "Internal error, cannot proceed.");
                # Notify tbops.
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
            }
            elseif ($webtask) {
                SPITAJAX_ERROR(1, $webtask->TaskValue("output"));
            }
            else {
                SUEXECERROR(SUEXEC_ACTION_CONTINUE);
                SPITAJAX_ERROR(-1, "Internal Error. Please try again later");
            }
            if ($webtask) {
                $webtask->Delete();
            }
            return;
        }
        SPITAJAX_RESPONSE(0);
    }
    else {
       SPITAJAX_ERROR(-1, "Improper lintest action"); 
    }
}

1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514