instance_defs.php 38.8 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
<?php
#
3
# Copyright (c) 2006-2018 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh Stoller committed
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/>.
# 
# }}}
#
#
25
include_once("aggregate_defs.php");
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
$geni_response_codes =
    array("Success",
          "Bad Arguments",
          "Error",
          "Forbidden",
          "Bad Version",
          "Server Error",
          "Too Big",
          "Refused",
          "Timed Out",
          "Database Error",
          "RPC Error",
          "Unavailable",
          "Search Failed",
          "Unsupported",
          "Busy",
          "Expired",
          "In Progress",
          "Already Exists",
          "Error 18",
          "Error 19",
          "Error 20",
          "Error 21",
          "Error 22",
51
          "No space left on device or over quota",
52 53 54 55 56 57
          "Vlan Unavailable",
          "Insufficient Bandwidth",
          "Insufficient Nodes",
          "Insufficient Memory",
          "No Mapping Possible",
    );
58
define("GENIRESPONSE_BADARGS",   	       1);
59
define("GENIRESPONSE_ERROR",       	       2);
60
define("GENIRESPONSE_REFUSED",                 7);
61
define("GENIRESPONSE_TIMEDOUT",                8);
62
define("GENIRESPONSE_RPCERROR",                10);
63
define("GENIRESPONSE_SEARCHFAILED",            12);
64 65
define("GENIRESPONSE_ALREADYEXISTS",           17);
define("GENIRESPONSE_NOSPACE",                 23);
66 67 68 69 70
define("GENIRESPONSE_VLAN_UNAVAILABLE",        24);
define("GENIRESPONSE_INSUFFICIENT_BANDWIDTH",  25);
define("GENIRESPONSE_INSUFFICIENT_NODES",      26);
define("GENIRESPONSE_INSUFFICIENT_MEMORY",     27);
define("GENIRESPONSE_NO_MAPPING",              28);
71 72
define("GENIRESPONSE_NO_CONNECT",              29);
define("GENIRESPONSE_MAPPING_IMPOSSIBLE",      30);
73
define("GENIRESPONSE_STITCHER_ERROR",          101);
74
define("GENIRESPONSE_SETUPFAILURE_BOOTFAILED", 151);
75

Leigh Stoller's avatar
Leigh Stoller committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
class Instance
{
    var	$instance;
    
    #
    # Constructor by lookup on unique index.
    #
    function Instance($uuid) {
	$safe_uuid = addslashes($uuid);

	$query_result =
	    DBQueryWarn("select * from apt_instances ".
			"where uuid='$safe_uuid'");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->instance = null;
	    return;
	}
94 95 96 97 98 99
	$this->instance  = mysql_fetch_array($query_result);
        $this->slivers   = InstanceSliver::LookupForInstance($this);
        if (!count($this->slivers) && $this->aggregate_urn()) {
            $this->slivers =
                array(InstanceSliver::Lookup($this, $this->aggregate_urn()));
        }
Leigh Stoller's avatar
Leigh Stoller committed
100 101
    }
    # accessors
102
    function slivers()      { return $this->slivers; }
Leigh Stoller's avatar
Leigh Stoller committed
103 104 105 106
    function field($name) {
	return (is_null($this->instance) ? -1 : $this->instance[$name]);
    }
    function uuid()	    { return $this->field('uuid'); }
107
    function name()	    { return $this->field('name'); }
Leigh Stoller's avatar
Leigh Stoller committed
108 109 110 111 112
    function slice_uuid()   { return $this->field('slice_uuid'); }
    function creator()	    { return $this->field('creator'); }
    function creator_idx()  { return $this->field('creator_idx'); }
    function creator_uuid() { return $this->field('creator_uuid'); }
    function created()	    { return $this->field('created'); }
113 114
    function profile_id()   { return $this->field('profile_id'); }
    function profile_version() { return $this->field('profile_version'); }
Leigh Stoller's avatar
Leigh Stoller committed
115
    function status()	    { return $this->field('status'); }
116
    function canceled()	    { return $this->field('canceled'); }
117
    function paniced()	    { return $this->field('paniced'); }
118 119
    function pid()	    { return $this->field('pid'); }
    function pid_idx()	    { return $this->field('pid_idx'); }
120 121
    function gid()	    { return $this->field('gid'); }
    function gid_idx()	    { return $this->field('gid_idx'); }
Leigh Stoller's avatar
Leigh Stoller committed
122
    function public_url()   { return $this->field('public_url'); }
123
    function logfileid()    { return $this->field('logfileid'); }
Leigh Stoller's avatar
Leigh Stoller committed
124
    function manifest()	    { return $this->field('manifest'); }
125 126
    function admin_lockdown() { return $this->field('admin_lockdown'); }
    function user_lockdown(){ return $this->field('user_lockdown'); }
127 128
    function extension_count()   { return $this->field('extension_count'); }
    function extension_days()    { return $this->field('extension_days'); }
129
    function extension_hours()   { return $this->field('extension_hours'); }
Leigh Stoller's avatar
Leigh Stoller committed
130
    function extension_reason()  { return $this->field('extension_reason'); }
131
    function extension_history() { return $this->field('extension_history'); }
Leigh Stoller's avatar
Leigh Stoller committed
132
    function extension_lockout() { return $this->field('extension_adminonly'); }
133 134 135
    function extension_disabled(){ return $this->field('extension_disabled'); }
    function extension_disabled_reason(){
        return $this->field('extension_disabled_reason');}
136
    function extension_requested(){return $this->field('extension_requested');}
137 138 139
    function extension_denied()  { return $this->field('extension_denied');}
    function extension_denied_reason(){
        return $this->field('extension_denied_reason');}
140 141
    function physnode_count()    { return $this->field('physnode_count'); }
    function virtnode_count()    { return $this->field('virtnode_count'); }
142
    function servername()   { return $this->field('servername'); }
Leigh Stoller's avatar
Leigh Stoller committed
143
    function aggregate_urn(){ return $this->field('aggregate_urn'); }
144
    function private_key()  { return $this->field('privkey'); }
145
    function webtask_id()   { return $this->field('webtask_id'); }
146 147 148
    function repourl()	    { return $this->field('repourl'); }
    function reporef()	    { return $this->field('reporef'); }
    function repohash()	    { return $this->field('repohash'); }
149
    function admin_notes()  { return $this->field('admin_notes'); }
150 151 152 153
    function isopenstack()  { return $this->field('isopenstack'); }
    function openstack_utilization() {
        return $this->field('openstack_utilization');
    }
154 155 156 157 158 159
    function IsAPT() {
	return preg_match('/aptlab/', $this->servername());
    }
    function IsCloud() {
	return preg_match('/cloudlab/', $this->servername());
    }
160 161 162
    function IsPNet() {
	return preg_match('/phantomnet/', $this->servername());
    }
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    # Grab the webtask. Backwards compat mode, see if there is one associated
    # with the object, use that. Otherwise create a new one.
    function WebTask() {
        if ($this->webtask_id()) {
            return WebTask::Lookup($this->webtask_id());
        }
        $webtask = WebTask::LookupByObject($this->uuid());
        if (!$webtask) {
            $webtask = WebTask::CreateAnonymous();
            if (!$webtask) {
                return null;
            }
        }
        $uuid = $this->uuid();
        $webtask_id = $webtask->task_id();
        DBQueryFatal("update apt_instances set ".
                     "  webtask_id='$webtask_id' ".
                     "where uuid='$uuid'");
        return $webtask;
    }
183 184 185 186
    function aggregate_name() {
        global $urn_mapping;
        return $urn_mapping[$this->aggregate_urn()];
    }
Leigh Stoller's avatar
Leigh Stoller committed
187 188 189 190 191 192
    
    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->instance);
    }

193 194 195 196 197 198 199 200 201 202 203 204
    # URL to the status page.
    function StatusURL() {
        global $APTBASE;

        return $APTBASE . "/status.php?uuid=" . $this->uuid();
    }
    function AdminURL() {
        global $APTBASE;

        return $APTBASE . "/adminextend.php?uuid=" . $this->uuid();
    }

Leigh Stoller's avatar
Leigh Stoller committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    # Lookup up an instance by idx. 
    function Lookup($idx) {
	$foo = new Instance($idx);

	if ($foo->IsValid()) {
            # Insert into cache.
	    return $foo;
	}	
	return null;
    }

    function LookupByCreator($token) {
	$safe_token = addslashes($token);

	$query_result =
	    DBQueryFatal("select uuid from apt_instances ".
			 "where creator_uuid='$safe_token'");

	if (! ($query_result && mysql_num_rows($query_result))) {
	    return null;
	}
	$row = mysql_fetch_row($query_result);
	$uuid = $row[0];
228 229 230
 	return Instance::Lookup($uuid);
    }

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    function LookupBySlice($token) {
	$safe_token = addslashes($token);

	$query_result =
	    DBQueryFatal("select uuid from apt_instances ".
			 "where slice_uuid='$safe_token'");

	if (! ($query_result && mysql_num_rows($query_result))) {
	    return null;
	}
	$row = mysql_fetch_row($query_result);
	$uuid = $row[0];
 	return Instance::Lookup($uuid);
    }

246 247 248 249 250 251 252 253 254 255 256 257 258
    function LookupByName($project, $token) {
	$safe_token = addslashes($token);
        $pid_idx    = $project->pid_idx();

	$query_result =
	    DBQueryFatal("select uuid from apt_instances ".
			 "where pid_idx='$pid_idx' and name='$safe_token'");

	if (! ($query_result && mysql_num_rows($query_result))) {
	    return null;
	}
	$row = mysql_fetch_row($query_result);
	$uuid = $row[0];
Leigh Stoller's avatar
Leigh Stoller committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
 	return Instance::Lookup($uuid);
    }

    #
    # Refresh an instance by reloading from the DB.
    #
    function Refresh() {
	if (! $this->IsValid())
	    return -1;

	$uuid = $this->uuid();

	$query_result =
	    DBQueryWarn("select * from apt_instances where uuid='$uuid'");
    
	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->instance  = NULL;
	    return -1;
	}
	$this->instance = mysql_fetch_array($query_result);
	return 0;
    }
281 282 283 284 285

    # Project of instance.
    function Project() {
        return Project::Lookup($this->pid_idx());
    }
286 287 288 289
    # Group of instance.
    function Group() {
        return Group::Lookup($this->gid_idx());
    }
290
    
291 292 293
    #
    # Class function to create a new Instance
    #
294
    function Instantiate($uuid, $creator, $options, $args, $webtask) {
295 296 297 298 299 300 301 302
	global $suexec_output, $suexec_output_array;

	#
        # Generate a temporary file and write in the XML goo. 
	#
	$xmlname = tempnam("/tmp", "quickvm");
	if (! $xmlname) {
	    TBERROR("Could not create temporary filename", 0);
303 304
            $webtask->output("Internal error creating experiment");
            $webtask->code(GENIRESPONSE_ERROR);
305 306 307 308
	    return null;
	}
	elseif (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
309 310
            $webtask->output("Internal error creating experiment");
            $webtask->code(GENIRESPONSE_ERROR);
311 312 313 314 315 316 317 318 319 320 321 322 323 324
	    return null;
	}
	else {
	    fwrite($fp, "<quickvm>\n");
	    foreach ($args as $name => $value) {
		fwrite($fp, "<attribute name=\"$name\">");
		fwrite($fp, "  <value>" . htmlspecialchars($value) .
		       "</value>");
		fwrite($fp, "</attribute>\n");
	    }
	    fwrite($fp, "</quickvm>\n");
	    fclose($fp);
	    chmod($xmlname, 0666);
	}
325 326
	# 
	# With a real user, run as that user. 
327
	#
328 329 330 331 332 333 334 335
        if ($creator) {
            $uid = $creator->uid();
            $pid = $args["pid"];
        }
        else {
            $uid = "nobody";
            $pid = "nobody";
        }
336 337 338
	if (isset($_SERVER['REMOTE_ADDR'])) { 
	    putenv("REMOTE_ADDR=" . $_SERVER['REMOTE_ADDR']);
	}
Leigh Stoller's avatar
Leigh Stoller committed
339 340 341
	if (isset($_SERVER['SERVER_NAME'])) { 
	    putenv("SERVER_NAME=" . $_SERVER['SERVER_NAME']);
	}
342 343
        $options .= " -t " . $webtask->task_id();
        
344
	$retval = SUEXEC($uid, $pid,
345
			 "webcreate_instance $options -u $uuid $xmlname",
346
			 SUEXEC_ACTION_IGNORE);
347
	unlink($xmlname);
348 349

	if ($retval != 0) {
350 351 352 353
            $webtask->Refresh();

            # Did not get a clean exit.
            if (! $webtask->exited() || $retval < 0) {
354
		SUEXECERROR(SUEXEC_ACTION_CONTINUE);
355 356 357 358 359 360
                $webtask->output("Internal error creating experiment");
                $webtask->code(GENIRESPONSE_ERROR);
                return null;
            }
            # Error in the webtask for the caller.
            return null;
361 362 363
	}
	$instance = Instance::Lookup($uuid);
	if (!$instance) {
364 365 366
	    TBERROR("Could not lookup instance after create: $uuid", 0);
            $webtask->output("Internal error creating experiment");
            $webtask->code(GENIRESPONSE_ERROR);
367 368 369 370
	    return null;
	}
	return array($instance, $creator);
    }
371 372 373 374 375 376 377 378 379 380

    function UserHasInstances($user) {
	$uuid = $user->uuid();

	$query_result =
	    DBQueryFatal("select uuid from apt_instances ".
			 "where creator_uuid='$uuid'");

	return mysql_num_rows($query_result);
    }
381 382 383 384

    function SendEmail($to, $subject, $msg, $headers) {
	TBMAIL($to, $subject, $msg, $headers);
    }
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

    #
    # How many experiments has a guest user created
    #
    function GuestInstanceCount($geniuser) {
        $uid = $geniuser->uid();
        
        $query_result =
            DBQueryFatal("select count(h.uuid) from apt_instance_history as h ".
                         "left join geni.geni_users as u on ".
                         "     u.uuid=h.creator_uuid ".
                         "where h.creator='$uid' and u.email is not null");
        
	$row = mysql_fetch_row($query_result);
	return $row[0];
    }
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    #
    # Number of active experiments a user or project has.
    #
    function CurrentInstanceCount($target) {
        if (get_class($target) == "Project") {
            $pid = $target->pid();
        
            $query_result =
                DBQueryFatal("select count(uuid) from apt_instances as i ".
                             "where i.pid='$pid'");
        }
        else {
            $uid = $target->uid();
        
            $query_result =
                DBQueryFatal("select count(uuid) from apt_instances as i ".
                             "where i.creator='$uid'");
        }
	$row = mysql_fetch_row($query_result);
	return $row[0];
    }

424 425 426 427
    #
    # Return aggregate based on the current user.
    #
    function DefaultAggregateList() {
428
        return Aggregate::DefaultAggregateList();
429
    }
430

Leigh Stoller's avatar
Leigh Stoller committed
431 432 433 434 435 436 437 438
    # helper
    function ParseURN($urn)
    {
        if (preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/", $urn, $matches)) {
            return array($matches[1], $matches[2], $matches[3]);
        }
        return array();
    }
439 440 441 442 443 444 445
    function ValidURN($urn)
    {
        if (preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/", $urn)) {
            return true;
        }
        return false;
    }
446 447 448 449 450 451 452 453 454

    function SetExtensionReason($reason)
    {
	$uuid = $this->uuid();
        $safe_reason = mysql_escape_string($reason);

        DBQueryWarn("update apt_instances set ".
                    "  extension_reason='$safe_reason' ".
                    "where uuid='$uuid'");
455 456
    }

457 458 459 460 461 462 463 464 465 466
    function SetAdminNotes($notes)
    {
	$uuid = $this->uuid();
        $safe_notes = mysql_escape_string($notes);

        DBQueryWarn("update apt_instances set ".
                    "  admin_notes='$safe_notes' ".
                    "where uuid='$uuid'");
    }

467 468 469 470 471 472 473 474 475
    function SetExtensionRequested($value)
    {
	$uuid = $this->uuid();

        DBQueryWarn("update apt_instances set ".
                    "  extension_requested='$value' ".
                    "where uuid='$uuid'");
    }

476 477 478 479 480 481 482 483 484
    function AddExtensionHistory($text)
    {
	$uuid = $this->uuid();
        $safe_text = mysql_escape_string($text);

        DBQueryWarn("update apt_instances set ".
                    "extension_history=CONCAT('$safe_text',".
                    "IFNULL(extension_history,'')) ".
                    "where uuid='$uuid'");
485
    }
486

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    #
    # Permission check; does user have permission to view instance.
    #
    function CanView($user) {
	if ($this->creator_idx() == $user->uid_idx()) {
	    return 1;
	}
	# Otherwise a project membership test.
	$project = Project::Lookup($this->pid_idx());
	if (!$project) {
	    return 0;
	}
	$isapproved = 0;
	if ($project->IsMember($user, $isapproved) && $isapproved) {
	    return 1;
	}
	return 0;
    }
    function CanModify($user) {
	if ($this->creator_idx() == $user->uid_idx()) {
	    return 1;
	}
        return 0;
    }
511 512 513 514 515
    function CanDoSSH($user) {
	if ($this->creator_idx() == $user->uid_idx()) {
	    return 1;
	}
        #
516
        # These are the guest projects.
517
        #
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        $APT_HOLDINGPROJECT   = "aptguests";
        $CLOUD_HOLDINGPROJECT = "CloudLab";
        
        if ($this->pid() == $APT_HOLDINGPROJECT ||
            $this->pid() == $CLOUD_HOLDINGPROJECT) {
            return 0;
        }
        
        # Otherwise a project membership test.
        $project = Project::Lookup($this->pid_idx());
        if (!$project) {
            return 0;
        }
        $isapproved = 0;
        if ($project->IsMember($user, $isapproved) && $isapproved) {
            return 1;
534 535 536
        }
        return 0;
    }
537 538 539 540

    #
    # Determine user current usage.
    #
541
    function CurrentUsage($target) {
542 543 544
        $pcount = 0;
        $phours = 0;

545 546 547 548 549
        if (get_class($target) == "User") {
            $user_idx = $target->idx();
            
            $query_result =
                DBQueryFatal("select sum(physnode_count), ".
550
                         " truncate(sum(physnode_count * ".
551
                         "  ((UNIX_TIMESTAMP(now()) - ".
552
                         "    UNIX_TIMESTAMP(created)) / 3600.0)),2) as phours ".
553 554
                         "  from apt_instances ".
                         "where creator_idx='$user_idx' and physnode_count>0");
555 556 557 558 559 560 561 562 563 564 565 566
        }
        else {
            $pid_idx = $target->pid_idx();

            $query_result =
                DBQueryFatal("select sum(physnode_count), ".
                         " truncate(sum(physnode_count * ".
                         "  ((UNIX_TIMESTAMP(now()) - ".
                         "    UNIX_TIMESTAMP(created)) / 3600.0)),2) as phours ".
                         "  from apt_instances ".
                         "where pid_idx='$pid_idx' and physnode_count>0");
        }
567

568 569 570
        $row = mysql_fetch_array($query_result);
        $pcount = $row[0] ? $row[0] : 0;
        $phours = $row[1] ? $row[1] : 0;
571 572
        return array($pcount, $phours);
    }
573

574 575 576
    #
    # Usage over the last week. Just phours, cause pcount is not very useful.
    #
577
    function WeeksUsage($target) {
578 579
        $weekago  = time() - (3600 * 24 * 7);
        $phours   = 0;
580 581 582 583 584 585 586 587 588 589 590
        $pcount   = 0;
        $clause   = "";

        if (get_class($target) == "User") {
            $user_idx = $target->idx();
            $clause = "creator_idx='$user_idx'";
        }
        else {
            $pid_idx = $target->pid_idx();
            $clause = "pid_idx='$pid_idx'";
        }
591 592 593 594 595 596 597

        #
        # This gets existing experiments back one week.
        #
        $query_result =
            DBQueryFatal("select physnode_count,UNIX_TIMESTAMP(created) ".
                         "  from apt_instances ".
598
                         "where $clause and physnode_count>0");
599 600 601 602 603 604 605 606 607 608

	while ($row = mysql_fetch_array($query_result)) {
            $pnodes   = $row[0];
            $created  = $row[1];

            if ($created < $weekago)
                $diff = (3600 * 24 * 7);
            else
                $diff = time() - $created;

609
            $pcount += $pnodes;
610 611 612 613 614 615 616 617 618 619
            $phours += $pnodes * ($diff / 3600.0);
        }

        #
        # This gets experiments terminated in the last week.
        #
        $query_result =
            DBQueryFatal("select physnode_count,UNIX_TIMESTAMP(created), ".
                         "       UNIX_TIMESTAMP(destroyed) ".
                         "  from apt_instance_history ".
620
                         "where $clause and physnode_count>0 and " .
621 622 623 624 625 626 627 628 629 630 631 632
                         "      destroyed>DATE_SUB(curdate(), INTERVAL 1 WEEK)");

	while ($row = mysql_fetch_array($query_result)) {
            $pnodes    = $row[0];
            $created   = $row[1];
            $destroyed = $row[2];

            if ($created < $weekago)
                $diff = $destroyed - $weekago;
            else
                $diff = $destroyed - $created;

Leigh Stoller's avatar
Leigh Stoller committed
633 634 635
            if ($diff < 0)
                $diff = 0;

636
            $pcount += $pnodes;
637 638
            $phours += $pnodes * ($diff / 3600.0);
        }
639
        return array ($pcount, $phours);
640 641 642 643 644
    }

    #
    # Usage over the last months Just phours, cause pcount is not very useful.
    #
645
    function MonthsUsage($target) {
646
        $monthago = time() - (3600 * 24 * 28);
647
        $pcount   = 0;
648
        $phours   = 0;
649 650 651 652 653 654 655 656 657 658
        $clause   = "";

        if (get_class($target) == "User") {
            $user_idx = $target->idx();
            $clause = "creator_idx='$user_idx'";
        }
        else {
            $pid_idx = $target->pid_idx();
            $clause = "pid_idx='$pid_idx'";
        }
659 660 661 662 663 664 665

        #
        # This gets existing experiments back one week.
        #
        $query_result =
            DBQueryFatal("select physnode_count,UNIX_TIMESTAMP(created) ".
                         "  from apt_instances ".
666
                         "where $clause and physnode_count>0");
667 668 669 670 671 672 673 674 675 676

	while ($row = mysql_fetch_array($query_result)) {
            $pnodes   = $row[0];
            $created  = $row[1];

            if ($created < $monthago)
                $diff = (3600 * 24 * 28);
            else
                $diff = time() - $created;

677
            $pcount += $pnodes;
678 679 680 681 682 683 684 685 686 687
            $phours += $pnodes * ($diff / 3600.0);
        }

        #
        # This gets experiments terminated in the last week.
        #
        $query_result =
            DBQueryFatal("select physnode_count,UNIX_TIMESTAMP(created), ".
                         "       UNIX_TIMESTAMP(destroyed) ".
                         "  from apt_instance_history ".
688
                         "where $clause and physnode_count>0 and " .
689 690 691 692 693 694 695 696 697 698 699 700
                         "      destroyed>DATE_SUB(curdate(), INTERVAL 1 MONTH)");

	while ($row = mysql_fetch_array($query_result)) {
            $pnodes    = $row[0];
            $created   = $row[1];
            $destroyed = $row[2];

            if ($created < $monthago)
                $diff = $destroyed - $monthago;
            else
                $diff = $destroyed - $created;

Leigh Stoller's avatar
Leigh Stoller committed
701 702 703
            if ($diff < 0)
                $diff = 0;

704
            $pcount += $pnodes;
705 706
            $phours += $pnodes * ($diff / 3600.0);
        }
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
        return array($pcount, $phours);
    }

    #
    # Ranking of usage over the last N days. Just by phours, cause pcount
    # is not very useful.
    #
    function Ranking($target, $days) {
        $rank     = null;
        $ranktotal= 0;

        if (get_class($target) == "User") {
            $which = "creator_idx";
            $who   = $target->uid_idx();
        }
        else {
            $which = "pid_idx";
            $who   = $target->pid_idx();
        }
        $query_result =
            DBQueryFatal("select $which,SUM(physnode_count) as physnode_count,".
                         "   SUM(phours) as phours from ".
                         " ((select $which,physnode_count,created,NULL, ".
                         "   physnode_count * (TIMESTAMPDIFF(HOUR, ".
731 732
                         "    IF(created > DATE_SUB(now(), INTERVAL $days DAY), ".
                         "       created, DATE_SUB(now(), INTERVAL $days DAY)), now())) ".
733 734 735 736 737 738
                         "    as phours ".
                         "   from apt_instances ".
                         "   where physnode_count>0) ".
                         "  union ".
                         "  (select $which,physnode_count,created,destroyed, ".
                         "   physnode_count * (TIMESTAMPDIFF(HOUR, ".
739 740
                         "    IF(created > DATE_SUB(now(), INTERVAL $days DAY), ".
                         "       created, DATE_SUB(now(), INTERVAL $days DAY)), destroyed)) ".
741 742 743
                         "    as phours ".
                         "   from apt_instance_history ".
                         "   where physnode_count>0 and ".
744
                         "         destroyed>DATE_SUB(now(),INTERVAL $days DAY)))".
745 746 747 748 749 750 751 752 753 754 755 756 757 758
                         "   as combined ".
                         "group by $which ".
                         "order by phours desc");

        $ranktotal = mysql_num_rows($query_result);
        $count = 1;
	while ($row = mysql_fetch_array($query_result)) {
            if ($who == $row[0]) {
                $rank = $count;
                break;
            }
            $count++;
        }
        return array($rank, $ranktotal);
759 760
    }

761
    #
762 763
    # Return Caching Token, either the latest commit hash
    # or the current time for development trees.
764
    #
765 766 767 768 769 770 771
    function CacheToken() {
      if (preg_match("/\/dev\//", $_SERVER["SCRIPT_NAME"]))
      {
        return date('Y-m-d-H:i:s');
      }
      else
      {
772 773 774 775 776 777 778 779 780
          $query_result =
              DBQueryFatal("select value from version_info ".
                           "where name='commithash'");
          
          if (!$query_result || !mysql_num_rows($query_result)) {
              return date('Y-m-d-H:i:s');
          }
          $row = mysql_fetch_array($query_result);
          return $row[0];
781
      }
782
    }
783 784 785 786 787 788 789 790

    #
    # Return a list of types not to show user.
    #
    function NodeTypePruneList() {
        global $ISEMULAB, $ISCLOUD, $ISAPT, $ISPNET, $ISPOWDER;
        
        $skiptypes = array("dboxvm"    => true,
Leigh Stoller's avatar
Leigh Stoller committed
791
                           "d430k"     => true,
792
                           "d530"      => true,
793 794 795 796 797 798 799 800 801 802 803 804 805 806
                           "pcivy"     => true,
                           "pc2830qx2" => true,
                           "pc2400hp"  => true,
                           "d2100"     => true,
                           "pc2400w"   => true);
                   
        if ($ISEMULAB || $ISCLOUD || $ISAPT) {
            $skiptypes["sdr"]      = true;
            $skiptypes["nuc5300"]  = true;
            $skiptypes["enodeb"]   = true;
            $skiptypes["nuc6260"]  = true;
        }
        return $skiptypes;
    }
Leigh Stoller's avatar
Leigh Stoller committed
807
}
808 809 810 811 812 813 814 815 816

class InstanceSliver
{
    var	$sliver;
    
    #
    # Constructor by lookup on unique index.
    #
    function InstanceSliver($instance, $urn) {
817 818 819 820 821
        if (!$instance) {
            TBMAIL("stoller", "undefined instance", $urn);
	    $this->sliver = null;
	    return;
        }
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
	$uuid = $instance->uuid();

	$query_result =
	    DBQueryWarn("select * from apt_instance_aggregates ".
			"where uuid='$uuid' and aggregate_urn='$urn'");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->sliver = null;
	    return;
	}
	$this->sliver = mysql_fetch_array($query_result);
    }
    # accessors
    function field($name) {
	return (is_null($this->sliver) ? -1 : $this->sliver[$name]);
    }
    function uuid()	    { return $this->field('uuid'); }
    function name()	    { return $this->field('name'); }
    function aggregate_urn(){ return $this->field('aggregate_urn'); }
    function status()	    { return $this->field('status'); }
    function public_url()   { return $this->field('public_url'); }
    function webtask_id()   { return $this->field('webtask_id'); }
    function manifest()	    { return $this->field('manifest'); }
845 846
    function physnode_count() { return $this->field('physnode_count'); }
    function virtnode_count() { return $this->field('virtnode_count'); }
847 848 849 850
    function aggregate_name() {
        global $urn_mapping;
        return $urn_mapping[$this->aggregate_urn()];
    }
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865

    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->sliver);
    }

    function Lookup($instance, $urn) {
	$foo = new InstanceSliver($instance, $urn);

	if ($foo->IsValid()) {
            return $foo;
        }
        #
        # Backwards compat for a while, create a fake one. 
        #
866
        $webtask_id = null;
867
        $webtask = WebTask::LookupByObject($instance->uuid());
868 869 870
        if ($webtask) {
            $webtask_id = $webtask->task_id();
        }
871 872 873 874 875 876 877
        $foo->sliver = array(
            "uuid" => $instance->uuid(),
            "name" => $instance->name(),
            "aggregate_urn" => $instance->aggregate_urn(),
            "status" => $instance->status(),
            "public_url" => $instance->public_url(),
            "manifest" => $instance->manifest(),
878
            "webtask_id" => $webtask_id,
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
        );
        return $foo;
    }

    #
    # Lookup all slivers for an instance
    #
    function LookupForInstance($instance) {
        $result = array();
        $uuid   = $instance->uuid();

        $query_result =
            DBQueryFatal("select aggregate_urn from apt_instance_aggregates ".
                         "where uuid='$uuid'");

	while ($row = mysql_fetch_array($query_result)) {
            $sliver = InstanceSliver::Lookup($instance, $row['aggregate_urn']);
            if ($sliver) {
                $result[] = $sliver;
            }
        }
        return $result;
    }
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927

    #
    # Grab the list of sliver status rows. Turn this into a class at some point.
    #
    function StatusArray() {
        $result = array();
        $uuid   = $this->uuid();
        $urn    = $this->aggregate_urn();

        $query_result =
            DBQueryFatal("select * from apt_instance_sliver_status ".
                         "where uuid='$uuid' and aggregate_urn='$urn'");

	while ($row = mysql_fetch_array($query_result)) {
            if ($row["sliver_data"]) {
                $row["sliver_details"] = json_decode($row["sliver_data"], true);
                
                if ($row["frisbee_data"]) {
                    $frisbeestatus = json_decode($row["frisbee_data"], true);
                    $row["sliver_details"]["frisbeestatus"] = $frisbeestatus;
                }
            }
            $result[] = $row;
        }
        return $result;
    }
928 929
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
class ExtensionInfo
{
    var	$info;
    
    function ExtensionInfo($instance, $idx) {
	$uuid = $instance->uuid();
        $idx  = addslashes($idx);

	$query_result =
	    DBQueryWarn("select * from apt_instance_extension_info ".
			"where uuid='$uuid' and idx='$idx'");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->info = null;
	    return;
	}
	$this->info = mysql_fetch_assoc($query_result);
947 948
        $this->info["reason"]  = trim($this->info["reason"]);
        $this->info["message"] = trim($this->info["message"]);
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973

        #
        # Convert wanted/granted hours to handy 5D14H string.
        #
        $wdays  = intval($this->info["wanted"] / 24.0);
        $whours = $this->info["wanted"] % 24;
        $gdays  = intval($this->info["granted"] / 24.0);
        $ghours = $this->info["granted"] % 24;
        if ($wdays) {
            $wantstring = "${wdays}D" . "${whours}H";
        }
        else {
            $wantstring = "${whours}H";
        }
        if ($gdays) {
            $grantstring = "${gdays}D" . "${ghours}H";
        }
        elseif ($ghours) {
            $grantstring = "${ghours}H";
        }
        else {
            $grantstring = "0";
        }
        $this->info["wantedstring"]  = $wantstring;
        $this->info["grantedstring"] = $grantstring;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    }
    # accessors
    function field($name) {
	return (is_null($this->info) ? -1 : $this->info[$name]);
    }
    function uuid()	    { return $this->field('uuid'); }
    function name()	    { return $this->field('name'); }
    function idx()          { return $this->field('idx'); }
    function tstamp()       { return $this->field('tstamp'); }
    function uid()          { return $this->field('uid'); }
    function uid_idx()      { return $this->field('uid_idx'); }
    function action()       { return $this->field('action'); }
    function wanted()       { return $this->field('wanted'); }
    function granted()      { return $this->field('granted'); }
    function admin()        { return $this->field('admin'); }
989
    function needapproval() { return $this->field('needapproval'); }
990 991
    function reason()       { return $this->field('reason'); }
    function message()      { return $this->field('message'); }
992 993 994 995
    function autoapproved() { return $this->field('autoapproved'); }
    function autoapproved_reason() {
        return $this->field('autoapproved_reason');
    }
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->info);
    }

    function Lookup($instance, $idx) {
	$foo = new ExtensionInfo($instance, $idx);

	if ($foo->IsValid()) {
            return $foo;
        }
        return $foo;
    }

    #
    # Lookup all extensions for an instance
    #
    function LookupForInstance($instance) {
        $result = array();
        $uuid   = $instance->uuid();

        $query_result =
            DBQueryFatal("select idx from apt_instance_extension_info ".
                         "where uuid='$uuid' order by idx desc");

	while ($row = mysql_fetch_array($query_result)) {
            $info = ExtensionInfo::Lookup($instance, $row['idx']);
            if ($info) {
                $result[] = $info;
            }
        }
        return $result;
    }
}

1032
# $amlist, $fedlist, and $status are all output arrays
1033 1034
function CalculateAggregateStatus(&$amlist, &$fedlist, &$status,
                                  $extended = false) {
1035
    global $TBMAINSITE, $DEFAULT_AGGREGATE_URN, $CHECKLOGIN_USER;
1036
    $am_array = Instance::DefaultAggregateList();
1037 1038 1039 1040 1041 1042 1043 1044

    #
    # If not the Cloudlab Portal then we get local status only.
    #
    if (!$TBMAINSITE) {
        $aggregate = $am_array[$DEFAULT_AGGREGATE_URN];
        $urn = $aggregate->urn();
        $am  = $aggregate->name();
1045 1046 1047 1048 1049 1050 1051 1052
        if ($extended) {
            $amlist[$urn] = array("urn"      => $urn,
                                  "name"     => $am,
                                  "nickname" => $aggregate->nickname());
        }
        else {
            $amlist[$urn] = $am;
        }
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        $freevms = $vmcount = 0;
        TBVMCounts($vmcount, $freevms);

        $status[$urn] = array(
            "rawPCsAvailable"  => TBFreePCs($CHECKLOGIN_USER),
            "rawPCsTotal"      => TBTotalPCs(),
            "VMsAvailable"     => $freevms,
            "VMsTotal"         => $vmcount,
            "health"           => 100,
            "status"           => "SUCCESS");
        return;
    }
1065 1066 1067
    while (list($ignore, $aggregate) = each($am_array)) {
        $urn = $aggregate->urn();
        $am  = $aggregate->name();
1068 1069 1070 1071 1072 1073 1074 1075
        if ($extended) {
            $amlist[$urn] = array("urn"      => $urn,
                                  "name"     => $am,
                                  "nickname" => $aggregate->nickname());
        }
        else {
            $amlist[$urn] = $am;
        }
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        #
        # We need to mark federated sites for the cluster dropdown.
        #
        if ($aggregate->isfederate()) {
            $fedlist[] = "'" . $aggregate->name() . "'";
        }
        #
        # generate the status blob.
        #
        if ($aggregate->status()) {
            $status[$urn] = array(
                "rawPCsAvailable"  => $aggregate->pfree(),
                "rawPCsTotal"      => $aggregate->pcount(),
1089
                "VMsAvailable"     => $aggregate->vfree(),
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
                "VMsTotal"         => $aggregate->vcount(),
                "health"           => ($aggregate->status() == "up" ? 100 :
                                       ($aggregate->status() == "down" ?
                                        0 : 50)),
                "status"           => ($aggregate->status() != "down" ?
                                       "SUCCESS" : "FAILED"));
        }
    }
}

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 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
function CalculateWirelessStatus() {
    $result = array();

    $query_result =
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id1) AS c FROM wires AS w " .
		      "LEFT OUTER JOIN reserved AS r1 ON " .
		      "w.node_id1=r1.node_id LEFT OUTER JOIN reserved AS r2 " .
		      "ON w.node_id2=r2.node_id WHERE w.node_id1 LIKE 'nuc%' " .
		      "AND w.node_id2 LIKE 'ue%' AND w.external_wire IS NULL" .
		      "OR w.external_wire=''" );
    $row = mysql_fetch_array( $query_result );
    $radiated1 = $row[ 'c' ];

    $query_result =
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id2) FROM wires AS w " .
		      "LEFT OUTER JOIN reserved AS r1 ON " .
		      "w.node_id1=r1.node_id LEFT OUTER JOIN reserved AS r2 " .
		      "ON w.node_id2=r2.node_id WHERE w.node_id2 LIKE 'nuc%' " .
		      "AND w.node_id1 LIKE 'ue%' AND w.external_wire IS NULL" .
		      "OR w.external_wire=''" );
    $row = mysql_fetch_array( $query_result );
    $radiated2 = $row[ 'c' ];

    $query_result =
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id1) FROM wires AS w " .
		      "LEFT OUTER JOIN reserved AS r1 ON " .
		      "w.node_id1=r1.node_id LEFT OUTER JOIN reserved AS r2 " .
		      "ON w.node_id2=r2.node_id WHERE w.node_id1 LIKE 'nuc%' " .
		      "AND w.node_id2 LIKE 'ue%' AND w.external_wire != ''" );
    $row = mysql_fetch_array( $query_result );
    $controlled1 = $row[ 'c' ];

    $query_result =
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id2) FROM wires AS w " .
		      "LEFT OUTER JOIN reserved AS r1 ON " .
		      "w.node_id1=r1.node_id LEFT OUTER JOIN reserved AS r2 " .
		      "ON w.node_id2=r2.node_id WHERE w.node_id2 LIKE 'nuc%' " .
		      "AND w.node_id1 LIKE 'ue%' AND w.external_wire != ''" );
    $row = mysql_fetch_array( $query_result );
    $controlled2 = $row[ 'c' ];

    return array(
        "radiated" => $radiated1 + $radiated2;
        "controlled" => $controlled1 + $controlled2;
    );
}
    
1147
function SpitAggregateStatus($extended = false) {
1148 1149 1150
    $amlist     = array();
    $fedlist    = array();
    $status     = array();
1151
    CalculateAggregateStatus($amlist, $fedlist, $status, $extended);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    echo "<script type='text/plain' id='amlist-json'>\n";
    echo htmlentities(json_encode($amlist));
    echo "</script>\n";
    echo "<script type='text/plain' id='amstatus-json'>\n";
    echo htmlentities(json_encode($status));
    echo "</script>\n";
    echo "<script type='text/javascript'>\n";
    echo "    window.FEDERATEDLIST  = [". implode(",", $fedlist) . "];\n";
    echo "</script>\n";
}

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
#
# Find usage info for user for the epoch, rather then looking up per
# profile. Much faster.
#
function UserUsageInfo($user) {
    $user_idx    = $user->idx();
    $results     = array();

    $query_result =
        DBQueryFatal("select profile_id,count(profile_id), ".
                     "       max(UNIX_TIMESTAMP(created)) ".
                     "  from apt_instances ".
                     " where creator_idx='$user_idx' ".
                     " group by profile_id");

    while ($row = mysql_fetch_array($query_result)) {
        $profile_id = $row[0];
        $count      = $row[1];
        $lastused   = $row[2];

        $results[$profile_id] = array("count"    => $count,
                                      "lastused" => $lastused);
    }
    $query_result =
        DBQueryFatal("select profile_id,count(profile_id), ".
                     "       max(UNIX_TIMESTAMP(created)) ".
                     "  from apt_instance_history ".
                     " where creator_idx='$user_idx' ".
                     " group by profile_id");

    while ($row = mysql_fetch_array($query_result)) {
        $profile_id = $row[0];
        $count      = $row[1];
        $lastused   = $row[2];

        if (!array_key_exists($profile_id, $results)) {
            $results[$profile_id] = array("count"    => $count,
                                          "lastused" => $lastused);
        }
        else {
            $result = $results[$profile_id];
            $result["count"] += $count;
            if ($lastused > $result["lastused"]) {
                $result["lastused"] = $lastused;
            }
        }
    }
    return $results;
}

Leigh Stoller's avatar
Leigh Stoller committed
1213
?>