instance_defs.php 46.1 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
<?php
#
3
# Copyright (c) 2006-2019 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 115
    function started()	    { return $this->field('started'); }
    function start_at()     { return $this->field('start_at'); }
    function stop_at()      { return $this->field('stop_at'); }
116 117
    function profile_id()   { return $this->field('profile_id'); }
    function profile_version() { return $this->field('profile_version'); }
Leigh Stoller's avatar
Leigh Stoller committed
118
    function status()	    { return $this->field('status'); }
119
    function canceled()	    { return $this->field('canceled'); }
120
    function paniced()	    { return $this->field('paniced'); }
121 122
    function pid()	    { return $this->field('pid'); }
    function pid_idx()	    { return $this->field('pid_idx'); }
123 124
    function gid()	    { return $this->field('gid'); }
    function gid_idx()	    { return $this->field('gid_idx'); }
Leigh Stoller's avatar
Leigh Stoller committed
125
    function public_url()   { return $this->field('public_url'); }
126
    function logfileid()    { return $this->field('logfileid'); }
Leigh Stoller's avatar
Leigh Stoller committed
127
    function manifest()	    { return $this->field('manifest'); }
128 129
    function admin_lockdown() { return $this->field('admin_lockdown'); }
    function user_lockdown(){ return $this->field('user_lockdown'); }
130 131
    function extension_count()   { return $this->field('extension_count'); }
    function extension_days()    { return $this->field('extension_days'); }
132
    function extension_hours()   { return $this->field('extension_hours'); }
Leigh Stoller's avatar
Leigh Stoller committed
133
    function extension_reason()  { return $this->field('extension_reason'); }
134
    function extension_history() { return $this->field('extension_history'); }
Leigh Stoller's avatar
Leigh Stoller committed
135
    function extension_lockout() { return $this->field('extension_adminonly'); }
136 137 138
    function extension_disabled(){ return $this->field('extension_disabled'); }
    function extension_disabled_reason(){
        return $this->field('extension_disabled_reason');}
139
    function extension_requested(){return $this->field('extension_requested');}
140 141 142
    function extension_denied()  { return $this->field('extension_denied');}
    function extension_denied_reason(){
        return $this->field('extension_denied_reason');}
143 144
    function physnode_count()    { return $this->field('physnode_count'); }
    function virtnode_count()    { return $this->field('virtnode_count'); }
145
    function servername()   { return $this->field('servername'); }
Leigh Stoller's avatar
Leigh Stoller committed
146
    function aggregate_urn(){ return $this->field('aggregate_urn'); }
147
    function private_key()  { return $this->field('privkey'); }
148
    function webtask_id()   { return $this->field('webtask_id'); }
149 150 151
    function repourl()	    { return $this->field('repourl'); }
    function reporef()	    { return $this->field('reporef'); }
    function repohash()	    { return $this->field('repohash'); }
152
    function rspec()	    { return $this->field('rspec'); }
153
    function admin_notes()  { return $this->field('admin_notes'); }
154 155 156 157
    function isopenstack()  { return $this->field('isopenstack'); }
    function openstack_utilization() {
        return $this->field('openstack_utilization');
    }
158 159 160 161 162 163
    function IsAPT() {
	return preg_match('/aptlab/', $this->servername());
    }
    function IsCloud() {
	return preg_match('/cloudlab/', $this->servername());
    }
164 165 166
    function IsPNet() {
	return preg_match('/phantomnet/', $this->servername());
    }
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    # 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;
    }
188 189 190 191
    function aggregate_name() {
        global $urn_mapping;
        return $urn_mapping[$this->aggregate_urn()];
    }
Leigh Stoller's avatar
Leigh Stoller committed
192 193 194 195 196 197
    
    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->instance);
    }

198 199 200 201 202 203 204 205 206 207 208 209
    # 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
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    # 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];
233 234 235
 	return Instance::Lookup($uuid);
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    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);
    }

251 252 253 254 255 256 257 258 259 260 261 262 263
    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
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
 	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;
    }
286 287 288 289 290

    # Project of instance.
    function Project() {
        return Project::Lookup($this->pid_idx());
    }
291 292 293 294
    # Group of instance.
    function Group() {
        return Group::Lookup($this->gid_idx());
    }
295
    
296 297 298
    #
    # Class function to create a new Instance
    #
299
    function Instantiate($uuid, $creator, $options, $args, $webtask) {
300 301 302 303 304 305 306 307
	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);
308 309
            $webtask->output("Internal error creating experiment");
            $webtask->code(GENIRESPONSE_ERROR);
310 311 312 313
	    return null;
	}
	elseif (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
314 315
            $webtask->output("Internal error creating experiment");
            $webtask->code(GENIRESPONSE_ERROR);
316 317 318 319 320 321 322 323 324 325 326 327 328 329
	    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);
	}
330 331
	# 
	# With a real user, run as that user. 
332
	#
333 334 335 336 337 338 339 340
        if ($creator) {
            $uid = $creator->uid();
            $pid = $args["pid"];
        }
        else {
            $uid = "nobody";
            $pid = "nobody";
        }
341 342 343
	if (isset($_SERVER['REMOTE_ADDR'])) { 
	    putenv("REMOTE_ADDR=" . $_SERVER['REMOTE_ADDR']);
	}
Leigh Stoller's avatar
Leigh Stoller committed
344 345 346
	if (isset($_SERVER['SERVER_NAME'])) { 
	    putenv("SERVER_NAME=" . $_SERVER['SERVER_NAME']);
	}
347 348
        $options .= " -t " . $webtask->task_id();
        
349
	$retval = SUEXEC($uid, $pid,
350
			 "webcreate_instance $options -u $uuid $xmlname",
351
			 SUEXEC_ACTION_IGNORE);
352
	unlink($xmlname);
353 354

	if ($retval != 0) {
355 356 357 358
            $webtask->Refresh();

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

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

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

	return mysql_num_rows($query_result);
    }
386 387 388 389

    function SendEmail($to, $subject, $msg, $headers) {
	TBMAIL($to, $subject, $msg, $headers);
    }
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

    #
    # 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];
    }
406

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    #
    # 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];
    }

429 430 431
    #
    # Return aggregate based on the current user.
    #
432 433
    function DefaultAggregateList($user = null) {
        return Aggregate::DefaultAggregateList($user);
434
    }
435

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

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

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

462 463 464 465 466 467 468 469 470 471
    function SetAdminNotes($notes)
    {
	$uuid = $this->uuid();
        $safe_notes = mysql_escape_string($notes);

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

472 473 474 475 476 477 478 479 480
    function SetExtensionRequested($value)
    {
	$uuid = $this->uuid();

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

481 482 483 484 485 486 487 488 489
    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'");
490
    }
491

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    #
    # 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;
    }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    function CanTerminate($user) {
	global $TBDB_TRUST_GROUPROOT;

	if ($this->creator_idx() == $user->uid_idx()) {
	    return 1;
	}
	# Otherwise a project membership test.
	$project = Project::Lookup($this->pid_idx());
	if (!$project) {
	    return 0;
	}
        $uid = $user->uid();
        $pid = $project->pid();
        return TBMinTrust(TBGrpTrust($uid, $pid, $pid), $TBDB_TRUST_GROUPROOT);
    }
531 532 533 534 535
    function CanDoSSH($user) {
	if ($this->creator_idx() == $user->uid_idx()) {
	    return 1;
	}
        #
536
        # These are the guest projects.
537
        #
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        $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;
554 555 556
        }
        return 0;
    }
557 558 559 560

    #
    # Determine user current usage.
    #
561
    function CurrentUsage($target) {
562 563 564
        $pcount = 0;
        $phours = 0;

565 566 567 568 569
        if (get_class($target) == "User") {
            $user_idx = $target->idx();
            
            $query_result =
                DBQueryFatal("select sum(physnode_count), ".
570
                         " truncate(sum(physnode_count * ".
571
                         "  ((UNIX_TIMESTAMP(now()) - ".
572
                         "    UNIX_TIMESTAMP(started)) / 3600.0)),2) as phours".
573 574
                         "  from apt_instances ".
                         "where creator_idx='$user_idx' and physnode_count>0");
575 576 577 578 579 580 581 582
        }
        else {
            $pid_idx = $target->pid_idx();

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

588 589 590
        $row = mysql_fetch_array($query_result);
        $pcount = $row[0] ? $row[0] : 0;
        $phours = $row[1] ? $row[1] : 0;
591 592
        return array($pcount, $phours);
    }
593

594 595 596
    #
    # Usage over the last week. Just phours, cause pcount is not very useful.
    #
597
    function WeeksUsage($target) {
598 599
        $weekago  = time() - (3600 * 24 * 7);
        $phours   = 0;
600 601 602 603 604 605 606 607 608 609 610
        $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'";
        }
611 612 613 614 615

        #
        # This gets existing experiments back one week.
        #
        $query_result =
616 617
            DBQueryFatal("select physnode_count, ".
                         "    UNIX_TIMESTAMP(started) as started ".
618
                         "  from apt_instances ".
619
                         "where $clause and physnode_count>0");
620 621

	while ($row = mysql_fetch_array($query_result)) {
622 623
            $pnodes   = $row["physnode_count"];
            $created  = $row["started"];
624 625 626 627 628 629

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

630
            $pcount += $pnodes;
631 632 633 634 635 636 637
            $phours += $pnodes * ($diff / 3600.0);
        }

        #
        # This gets experiments terminated in the last week.
        #
        $query_result =
638 639 640
            DBQueryFatal("select physnode_count,".
                         "       UNIX_TIMESTAMP(started) as started, ".
                         "       UNIX_TIMESTAMP(destroyed) as destroyed ".
641
                         "  from apt_instance_history ".
642
                         "where $clause and physnode_count>0 and " .
643 644 645
                         "      destroyed>DATE_SUB(curdate(), INTERVAL 1 WEEK)");

	while ($row = mysql_fetch_array($query_result)) {
646 647 648
            $pnodes    = $row["physnode_count"];
            $created   = $row["started"];
            $destroyed = $row["destroyed"];
649 650 651 652 653 654

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

Leigh Stoller's avatar
Leigh Stoller committed
655 656 657
            if ($diff < 0)
                $diff = 0;

658
            $pcount += $pnodes;
659 660
            $phours += $pnodes * ($diff / 3600.0);
        }
661
        return array ($pcount, $phours);
662 663 664 665 666
    }

    #
    # Usage over the last months Just phours, cause pcount is not very useful.
    #
667
    function MonthsUsage($target) {
668
        $monthago = time() - (3600 * 24 * 28);
669
        $pcount   = 0;
670
        $phours   = 0;
671 672 673 674 675 676 677 678 679 680
        $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'";
        }
681 682 683 684 685

        #
        # This gets existing experiments back one week.
        #
        $query_result =
686 687
            DBQueryFatal("select physnode_count,".
                         "    UNIX_TIMESTAMP(started) as started ".
688
                         "  from apt_instances ".
689
                         "where $clause and physnode_count>0");
690 691

	while ($row = mysql_fetch_array($query_result)) {
692 693
            $pnodes   = $row["physnode_count"];
            $created  = $row["started"];
694 695 696 697 698 699

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

700
            $pcount += $pnodes;
701 702 703 704 705 706 707
            $phours += $pnodes * ($diff / 3600.0);
        }

        #
        # This gets experiments terminated in the last week.
        #
        $query_result =
708 709 710
            DBQueryFatal("select physnode_count,".
                         "       UNIX_TIMESTAMP(started) as started, ".
                         "       UNIX_TIMESTAMP(destroyed) as destroyed ".
711
                         "  from apt_instance_history ".
712
                         "where $clause and physnode_count>0 and " .
713 714 715
                         "      destroyed>DATE_SUB(curdate(), INTERVAL 1 MONTH)");

	while ($row = mysql_fetch_array($query_result)) {
716 717 718
            $pnodes    = $row["physnode_count"];
            $created   = $row["started"];
            $destroyed = $row["destroyed"];
719 720 721 722 723 724

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

Leigh Stoller's avatar
Leigh Stoller committed
725 726 727
            if ($diff < 0)
                $diff = 0;

728
            $pcount += $pnodes;
729 730
            $phours += $pnodes * ($diff / 3600.0);
        }
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
        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 ".
753
                         " ((select $which,physnode_count,started,NULL, ".
754
                         "   physnode_count * (TIMESTAMPDIFF(HOUR, ".
755 756
                         "    IF(started > DATE_SUB(now(),INTERVAL $days DAY),".
                         "       started, DATE_SUB(now(), INTERVAL $days DAY)), now())) ".
757 758 759 760
                         "    as phours ".
                         "   from apt_instances ".
                         "   where physnode_count>0) ".
                         "  union ".
761
                         "  (select $which,physnode_count,started,destroyed, ".
762
                         "   physnode_count * (TIMESTAMPDIFF(HOUR, ".
763 764
                         "    IF(started > DATE_SUB(now(),INTERVAL $days DAY),".
                         "       started, DATE_SUB(now(), INTERVAL $days DAY)), destroyed)) ".
765 766 767
                         "    as phours ".
                         "   from apt_instance_history ".
                         "   where physnode_count>0 and ".
768
                         "         destroyed>DATE_SUB(now(),INTERVAL $days DAY)))".
769 770 771 772 773 774 775 776 777 778 779 780 781 782
                         "   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);
783 784
    }

785
    #
786 787
    # Return Caching Token, either the latest commit hash
    # or the current time for development trees.
788
    #
789 790 791 792 793 794 795
    function CacheToken() {
      if (preg_match("/\/dev\//", $_SERVER["SCRIPT_NAME"]))
      {
        return date('Y-m-d-H:i:s');
      }
      else
      {
796 797 798 799 800 801 802 803 804
          $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];
805
      }
806
    }
807 808 809 810

    #
    # Return a list of types not to show user.
    #
811
    function NodeTypePruneList($aggregate = null) {
812
        global $ISEMULAB, $ISCLOUD, $ISAPT, $ISPNET, $ISPOWDER, $TBMAINSITE;
813 814 815 816 817 818
        global $DEFAULT_AGGREGATE_URN;
        $aggregate_urn = ($aggregate ? $aggregate->urn() : "");

        #
        # We never want to show these.
        #
819
        $skiptypes = array("dboxvm"    => true,
Leigh Stoller's avatar
Leigh Stoller committed
820
                           "d430k"     => true,
821
                           "d530"      => true,
822 823 824 825
                           "pcivy"     => true,
                           "pc2830qx2" => true,
                           "pc2400hp"  => true,
                           "d2100"     => true,
826
                           "faros_sfp" => true,
827
                           "pc2400w"   => true);
828 829 830 831 832 833 834 835 836

        #
        # If showing nodes from another cluster, then we show them
        # all (not sure how long this rule will last). Otherwise,
        # only the Powder/Phantom portals get to see all these types.
        #
        if ($TBMAINSITE && 
            !($ISPOWDER || $ISPNET) &&
            $aggregate_urn == $DEFAULT_AGGREGATE_URN) {
837 838 839 840
            $skiptypes["sdr"]      = true;
            $skiptypes["nuc5300"]  = true;
            $skiptypes["enodeb"]   = true;
            $skiptypes["nuc6260"]  = true;
841
            $skiptypes["nuc8650"]  = true;
Leigh Stoller's avatar
Leigh Stoller committed
842
            $skiptypes["nuc8559"]  = true;
843 844
            $skiptypes["nuc7100"]  = true;
            $skiptypes["iris030"]  = true;
845 846 847 848
            $skiptypes["d840"]     = true;
            $skiptypes["d740"]     = true;
            $skiptypes["x310"]     = true;
            $skiptypes["n310"]     = true;
849 850 851
        }
        return $skiptypes;
    }
Leigh Stoller's avatar
Leigh Stoller committed
852
}
853

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 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
class InstanceHistory
{
    var	$record;
    var $slivers;
    
    #
    # Constructor by lookup on unique index.
    #
    function InstanceHistory($uuid) {
	$safe_uuid = addslashes($uuid);

	$query_result =
	    DBQueryWarn("select h.*,f.exitmessage,f.exitcode ".
                        "  from apt_instance_history as h ".
                        "left join apt_instance_failures as f ".
                        "     on f.uuid=h.uuid ".
			"where h.uuid='$safe_uuid'");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->record = null;
	    return;
	}
	$this->record  = mysql_fetch_array($query_result);

        #
        # Get the list of aggregate records. Early records do not have one.
        #
	$query_result =
	    DBQueryWarn("select * from apt_instance_aggregate_history ".
			"where uuid='$uuid'");
	if (!$query_result) {
	    $this->record = null;
	    return;
	}
        if (!mysql_num_rows($query_result)) {
            $this->slivers = array(
                array("uuid" => $this->record["uuid"],
                      "name" => $this->record["name"],
                      "aggregate_urn" => $this->record["aggregate_urn"],
                      "status" => $this->record["status"],
                      "public_url" => $this->record["public_url"],
                      "manifest" => $this->record["manifest"],
                ));
        }
        else {
            $this->slivers = array();

            while ($row = mysql_fetch_array($query_result)) {
                $this->slivers[] = $row;
            }
        }
    }
    # accessors
    function slivers()      { return $this->slivers; }
    function field($name) {
	return (is_null($this->record) ? -1 : $this->record[$name]);
    }
    function uuid()	    { return $this->field('uuid'); }
    function name()	    { return $this->field('name'); }
    function profile_id()   { return $this->field('profile_id'); }
    function profile_version() { return $this->field('profile_version'); }
    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 pid()	    { return $this->field('pid'); }
    function pid_idx()	    { return $this->field('pid_idx'); }
    function gid()	    { return $this->field('gid'); }
    function gid_idx()	    { return $this->field('gid_idx'); }
    function aggregate_urn(){ return $this->field('aggregate_urn'); }
    function public_url()   { return $this->field('public_url'); }
    function logfileid()    { return $this->field('logfileid'); }
    function created()	    { return $this->field('created'); }
927 928 929
    function start_at()     { return $this->field('start_at'); }
    function stop_at()      { return $this->field('stop_at'); }
    function started()      { return $this->field('started'); }
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 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 974 975 976 977 978 979 980 981
    function destroyed()    { return $this->field('destroyed'); }
    function expired()      { return $this->field('expired'); }
    function extension_count()   { return $this->field('extension_count'); }
    function extension_days()    { return $this->field('extension_days'); }
    function extension_hours()   { return $this->field('extension_hours'); }
    function physnode_count()    { return $this->field('physnode_count'); }
    function virtnode_count()    { return $this->field('virtnode_count'); }
    function servername()   { return $this->field('servername'); }
    function repourl()	    { return $this->field('repourl'); }
    function reporef()	    { return $this->field('reporef'); }
    function repohash()	    { return $this->field('repohash'); }
    function rspec()	    { return $this->field('rspec'); }
    function script()	    { return $this->field('script'); }
    function params()	    { return $this->field('params'); }
    function manifest()	    { return $this->field('manifest'); }
    function IsAPT() {
	return preg_match('/aptlab/', $this->servername());
    }
    function IsCloud() {
	return preg_match('/cloudlab/', $this->servername());
    }
    function IsPNet() {
	return preg_match('/phantomnet/', $this->servername());
    }
    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->record);
    }
    # Lookup up an instance by uuid
    function Lookup($uuid) {
	$foo = new InstanceHistory($uuid);

	if ($foo->IsValid()) {
            # Insert into cache.
	    return $foo;
	}	
	return null;
    }
    function LookupBySlice($slice_uuid)
    {
	$safe_uuid = addslashes($slice_uuid);

	$query_result =
	    DBQueryWarn("select uuid from apt_instance_history ".
			"where slice_uuid='$safe_uuid'");

	if (!$query_result || !mysql_num_rows($query_result)) {
            return null;
	}
        $row = mysql_fetch_array($query_result);
        return InstanceHistory::Lookup($row[0]);
    }
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
    #
    # 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;
    }
1000 1001
}

1002 1003 1004 1005 1006 1007 1008 1009
class InstanceSliver
{
    var	$sliver;
    
    #
    # Constructor by lookup on unique index.
    #
    function InstanceSliver($instance, $urn) {
1010 1011 1012 1013 1014
        if (!$instance) {
            TBMAIL("stoller", "undefined instance", $urn);
	    $this->sliver = null;
	    return;
        }
1015
	$uuid = $instance->uuid();
Leigh Stoller's avatar
Leigh Stoller committed
1016
        $safe_urn = addslashes($urn);
1017 1018 1019

	$query_result =
	    DBQueryWarn("select * from apt_instance_aggregates ".
Leigh Stoller's avatar
Leigh Stoller committed
1020
			"where uuid='$uuid' and aggregate_urn='$safe_urn'");
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

	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'); }
1039 1040
    function physnode_count() { return $this->field('physnode_count'); }
    function virtnode_count() { return $this->field('virtnode_count'); }
1041 1042 1043 1044
    function aggregate_name() {
        global $urn_mapping;
        return $urn_mapping[$this->aggregate_urn()];
    }
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

    # 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. 
        #
1060
        $webtask_id = null;
1061
        $webtask = WebTask::LookupByObject($instance->uuid());
1062 1063 1064
        if ($webtask) {
            $webtask_id = $webtask->task_id();
        }
1065 1066 1067 1068 1069 1070 1071
        $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(),
1072
            "webtask_id" => $webtask_id,
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        );
        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;
    }
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

    #
    # 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;
    }
1122 1123
}

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
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);
1141 1142
        $this->info["reason"]  = trim($this->info["reason"]);
        $this->info["message"] = trim($this->info["message"]);
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

        #
        # 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;
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    }
    # 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'); }
1183
    function needapproval() { return $this->field('needapproval'); }
1184 1185
    function reason()       { return $this->field('reason'); }
    function message()      { return $this->field('message'); }
1186 1187 1188 1189
    function autoapproved() { return $this->field('autoapproved'); }
    function autoapproved_reason() {
        return $this->field('autoapproved_reason');
    }
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

    # 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;
    }
}

1226
# $amlist, $fedlist, and $status are all output arrays
1227
function CalculateAggregateStatus(&$amlist, &$fedlist, &$status,
1228
                                  $extended = false, $user = null) {
1229
    global $TBMAINSITE, $DEFAULT_AGGREGATE_URN, $CHECKLOGIN_USER;
1230
    $am_array = Instance::DefaultAggregateList($user);
1231 1232 1233 1234 1235 1236 1237 1238

    #
    # 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();
1239 1240 1241 1242 1243 1244 1245 1246
        if ($extended) {
            $amlist[$urn] = array("urn"      => $urn,
                                  "name"     => $am,
                                  "nickname" => $aggregate->nickname());
        }
        else {
            $amlist[$urn] = $am;
        }
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
        $freevms = $vmcount = 0;
        TBVMCounts($vmcount, $freevms);

        $status[$urn] = array(
            "rawPCsAvailable"  => TBFreePCs($CHECKLOGIN_USER),
            "rawPCsTotal"      => TBTotalPCs(),
            "VMsAvailable"     => $freevms,
            "VMsTotal"         => $vmcount,
            "health"           => 100,
            "status"           => "SUCCESS");
        return;
    }
1259 1260 1261
    while (list($ignore, $aggregate) = each($am_array)) {
        $urn = $aggregate->urn();
        $am  = $aggregate->name();
1262 1263 1264 1265 1266 1267 1268 1269
        if ($extended) {
            $amlist[$urn] = array("urn"      => $urn,
                                  "name"     => $am,
                                  "nickname" => $aggregate->nickname());
        }
        else {
            $amlist[$urn] = $am;
        }
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
        #
        # 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(),
1283
                "VMsAvailable"     => $aggregate->vfree(),
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
                "VMsTotal"         => $aggregate->vcount(),
                "health"           => ($aggregate->status() == "up" ? 100 :
                                       ($aggregate->status() == "down" ?
                                        0 : 50)),
                "status"           => ($aggregate->status() != "down" ?
                                       "SUCCESS" : "FAILED"));
        }
    }
}

1294
function CalculateWirelessStatus(&$result) {
1295 1296 1297 1298 1299
    $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%' " .
1300 1301
		      "AND w.node_id2 LIKE 'ue%' AND (w.external_wire IS NULL " .
		      "OR w.external_wire='') AND r1.pid IS NULL AND r2.pid IS NULL" );
1302 1303 1304 1305
    $row = mysql_fetch_array( $query_result );
    $radiated1 = $row[ 'c' ];

    $query_result =
1306
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id2) AS c FROM wires AS w " .
1307 1308 1309
		      "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%' " .
1310 1311
		      "AND w.node_id1 LIKE 'ue%' AND (w.external_wire IS NULL " .
		      "OR w.external_wire='') AND r1.pid IS NULL AND r2.pid IS NULL" );
1312 1313 1314 1315
    $row = mysql_fetch_array( $query_result );
    $radiated2 = $row[ 'c' ];

    $query_result =
1316
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id1) AS c FROM wires AS w " .
1317 1318 1319
		      "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%' " .
1320 1321
		      "AND w.node_id2 LIKE 'ue%' AND w.external_wire != ''" .
		      "AND r1.pid IS NULL AND r2.pid IS NULL" );
1322 1323 1324 1325
    $row = mysql_fetch_array( $query_result );
    $controlled1 = $row[ 'c' ];

    $query_result =
1326
        DBQueryFatal( "SELECT COUNT(DISTINCT w.node_id2) AS c FROM wires AS w " .
1327 1328 1329
		      "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%' " .
1330 1331
		      "AND w.node_id1 LIKE 'ue%' AND w.external_wire != ''" .
		      "AND r1.pid IS NULL AND r2.pid IS NULL" );
1332 1333 1334
    $row = mysql_fetch_array( $query_result );
    $controlled2 = $row[ 'c' ];

1335 1336
    $result["radiated"] = $radiated1 + $radiated2;
    $result["controlled"] = $controlled1 + $controlled2;
1337 1338
}
    
1339
function SpitAggregateStatus($extended = false, $user = null) {
1340 1341 1342
    $amlist     = array();
    $fedlist    = array();
    $status     = array();
1343
    CalculateAggregateStatus($amlist, $fedlist, $status, $extended, $user);
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
    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";
}

1355 1356 1357 1358 1359 1360 1361 1362 1363
#
# 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 =
1364 1365
        DBQueryFatal("select profile_id,count(profile_id) as count, ".
                     "       max(UNIX_TIMESTAMP(started)) as lastused ".
1366 1367 1368 1369 1370
                     "  from apt_instances ".
                     " where creator_idx='$user_idx' ".
                     " group by profile_id");

    while ($row = mysql_fetch_array($query_result)) {
1371 1372 1373
        $profile_id = $row["profile_id"];
        $count      = $row["count"];
        $lastused   = $row["lastused"];
1374 1375 1376 1377 1378

        $results[$profile_id] = array("count"    => $count,
                                      "lastused" => $lastused);
    }
    $query_result =
1379 1380
        DBQueryFatal("select profile_id,count(profile_id) as count, ".
                     "       max(UNIX_TIMESTAMP(started)) as lastused ".
1381 1382 1383 1384 1385
                     "  from apt_instance_history ".
                     " where creator_idx='$user_idx' ".
                     " group by profile_id");

    while ($row = mysql_fetch_array($query_result)) {
1386 1387 1388
        $profile_id = $row["profile_id"];
        $count      = $row["count"];
        $lastused   = $row["lastused"];
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

        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
1405
?>