instance_defs.php 29.4 KB
Newer Older
Leigh B Stoller's avatar
Leigh B Stoller committed
1 2
<?php
#
3
# Copyright (c) 2006-2016 University of Utah and the Flux Group.
Leigh B Stoller's avatar
Leigh B 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 51 52 53 54 55 56 57
$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",
          "Error 23",
          "Vlan Unavailable",
          "Insufficient Bandwidth",
          "Insufficient Nodes",
          "Insufficient Memory",
          "No Mapping Possible",
    );
58
define("GENIRESPONSE_BADARGS",   	       1);
59
define("GENIRESPONSE_REFUSED",                 7);
60
define("GENIRESPONSE_TIMEDOUT",                8);
61
define("GENIRESPONSE_SEARCHFAILED",            12);
62 63 64 65 66 67
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);
define("GENIRESPONSE_STITCHER_ERROR",          101);
68

Leigh B Stoller's avatar
Leigh B Stoller committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
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;
	}
87 88 89 90 91 92
	$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 B Stoller's avatar
Leigh B Stoller committed
93 94
    }
    # accessors
95
    function slivers()      { return $this->slivers; }
Leigh B Stoller's avatar
Leigh B Stoller committed
96 97 98 99
    function field($name) {
	return (is_null($this->instance) ? -1 : $this->instance[$name]);
    }
    function uuid()	    { return $this->field('uuid'); }
100
    function name()	    { return $this->field('name'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
101 102 103 104 105
    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'); }
106 107
    function profile_id()   { return $this->field('profile_id'); }
    function profile_version() { return $this->field('profile_version'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
108
    function status()	    { return $this->field('status'); }
109
    function canceled()	    { return $this->field('canceled'); }
110
    function paniced()	    { return $this->field('paniced'); }
111 112
    function pid()	    { return $this->field('pid'); }
    function pid_idx()	    { return $this->field('pid_idx'); }
113 114
    function gid()	    { return $this->field('gid'); }
    function gid_idx()	    { return $this->field('gid_idx'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
115
    function public_url()   { return $this->field('public_url'); }
116
    function logfileid()    { return $this->field('logfileid'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
117
    function manifest()	    { return $this->field('manifest'); }
118 119
    function admin_lockdown() { return $this->field('admin_lockdown'); }
    function user_lockdown(){ return $this->field('user_lockdown'); }
120 121
    function extension_count()   { return $this->field('extension_count'); }
    function extension_days()    { return $this->field('extension_days'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
122
    function extension_reason()  { return $this->field('extension_reason'); }
123
    function extension_history() { return $this->field('extension_history'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
124
    function extension_lockout() { return $this->field('extension_adminonly'); }
125
    function extension_requested(){return $this->field('extension_requested');}
126 127 128
    function extension_denied()  { return $this->field('extension_denied');}
    function extension_denied_reason(){
        return $this->field('extension_denied_reason');}
129 130
    function physnode_count()    { return $this->field('physnode_count'); }
    function virtnode_count()    { return $this->field('virtnode_count'); }
131
    function servername()   { return $this->field('servername'); }
Leigh B Stoller's avatar
Leigh B Stoller committed
132
    function aggregate_urn(){ return $this->field('aggregate_urn'); }
133
    function private_key()  { return $this->field('privkey'); }
134 135 136
    function repourl()	    { return $this->field('repourl'); }
    function reporef()	    { return $this->field('reporef'); }
    function repohash()	    { return $this->field('repohash'); }
137 138 139 140
    function isopenstack()  { return $this->field('isopenstack'); }
    function openstack_utilization() {
        return $this->field('openstack_utilization');
    }
141 142 143 144 145 146
    function IsAPT() {
	return preg_match('/aptlab/', $this->servername());
    }
    function IsCloud() {
	return preg_match('/cloudlab/', $this->servername());
    }
147 148 149
    function IsPNet() {
	return preg_match('/phantomnet/', $this->servername());
    }
150 151 152 153
    function aggregate_name() {
        global $urn_mapping;
        return $urn_mapping[$this->aggregate_urn()];
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    
    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->instance);
    }

    # 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];
183 184 185
 	return Instance::Lookup($uuid);
    }

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    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);
    }

201 202 203 204 205 206 207 208 209 210 211 212 213
    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 B Stoller's avatar
Leigh B Stoller committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
 	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;
    }
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    #
    # Class function to create a new Instance
    #
    function Instantiate($creator, $options, $args, &$errors) {
	global $suexec_output, $suexec_output_array;

	# So we can look up the slice after the backend creates it.
	$uuid = NewUUID();

	#
        # Generate a temporary file and write in the XML goo. 
	#
	$xmlname = tempnam("/tmp", "quickvm");
	if (! $xmlname) {
	    TBERROR("Could not create temporary filename", 0);
	    $errors["error"] = "Transient error(1); please try again later.";
	    return null;
	}
	elseif (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
	    $errors["error"] = "Transient error(2); please try again later.";
	    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);
	}
271 272
	# 
	# With a real user, run as that user. 
273
	#
274 275 276 277 278 279 280 281
        if ($creator) {
            $uid = $creator->uid();
            $pid = $args["pid"];
        }
        else {
            $uid = "nobody";
            $pid = "nobody";
        }
282 283 284
	if (isset($_SERVER['REMOTE_ADDR'])) { 
	    putenv("REMOTE_ADDR=" . $_SERVER['REMOTE_ADDR']);
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
285 286 287
	if (isset($_SERVER['SERVER_NAME'])) { 
	    putenv("SERVER_NAME=" . $_SERVER['SERVER_NAME']);
	}
288
	$retval = SUEXEC($uid, $pid,
289
			 "webcreate_instance $options -u $uuid $xmlname",
290
			 SUEXEC_ACTION_IGNORE);
291
	unlink($xmlname);
292 293 294

	if ($retval != 0) {
	    if ($retval < 0) {
295
		SUEXECERROR(SUEXEC_ACTION_CONTINUE);
296 297 298 299 300 301 302 303 304
		$errors["error"] =
		    "Transient error(3); please try again later.";
	    }
	    else {
		if (count($suexec_output_array)) {
		    $line = $suexec_output_array[0];
		    $errors["error"] = $line;
		}
		else {
305
		    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
		    $errors["error"] =
			"Transient error(4); please try again later.";
		}
	    }
	    return null;
	}
	$instance = Instance::Lookup($uuid);
	if (!$instance) {
	    $errors["error"] = "Transient error(5); please try again later.";
	    return null;
	}
	if (!$creator) {
	    $creator = GeniUser::Lookup("sa", $instance->creator_uuid());
	}
	if (!$creator) {
	    $errors["error"] = "Transient error(6); please try again later.";
	    return null;
	}
	return array($instance, $creator);
    }
326 327 328 329 330 331 332 333 334 335

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

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

	return mysql_num_rows($query_result);
    }
336 337 338 339

    function SendEmail($to, $subject, $msg, $headers) {
	TBMAIL($to, $subject, $msg, $headers);
    }
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

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

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    #
    # 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];
    }

379 380 381 382
    #
    # Return aggregate based on the current user.
    #
    function DefaultAggregateList() {
383
        return Aggregate::DefaultAggregateList();
384
    }
385

Leigh B Stoller's avatar
Leigh B Stoller committed
386 387 388 389 390 391 392 393
    # helper
    function ParseURN($urn)
    {
        if (preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/", $urn, $matches)) {
            return array($matches[1], $matches[2], $matches[3]);
        }
        return array();
    }
394 395 396 397 398 399 400
    function ValidURN($urn)
    {
        if (preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/", $urn)) {
            return true;
        }
        return false;
    }
401 402 403 404 405 406 407 408 409

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

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

412 413 414 415 416 417 418 419 420
    function SetExtensionRequested($value)
    {
	$uuid = $this->uuid();

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

421 422 423 424 425 426 427 428 429
    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'");
430
    }
431 432 433 434 435 436 437 438 439 440

    function BumpExtensionCount($granted)
    {
	$uuid = $this->uuid();

        DBQueryWarn("update apt_instances set ".
                    "  extension_count=extension_count+1, ".
                    "  extension_days=extension_days+${granted} ".
                    "where uuid='$uuid'");
    }
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    #
    # 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;
    }
465 466 467 468 469
    function CanDoSSH($user) {
	if ($this->creator_idx() == $user->uid_idx()) {
	    return 1;
	}
        #
470
        # These are the guest projects.
471
        #
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        $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;
488 489 490
        }
        return 0;
    }
491 492 493 494

    #
    # Determine user current usage.
    #
495
    function CurrentUsage($target) {
496 497 498
        $pcount = 0;
        $phours = 0;

499 500 501 502 503
        if (get_class($target) == "User") {
            $user_idx = $target->idx();
            
            $query_result =
                DBQueryFatal("select sum(physnode_count), ".
504
                         " truncate(sum(physnode_count * ".
505
                         "  ((UNIX_TIMESTAMP(now()) - ".
506
                         "    UNIX_TIMESTAMP(created)) / 3600.0)),2) as phours ".
507 508
                         "  from apt_instances ".
                         "where creator_idx='$user_idx' and physnode_count>0");
509 510 511 512 513 514 515 516 517 518 519 520
        }
        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");
        }
521

522 523 524
        $row = mysql_fetch_array($query_result);
        $pcount = $row[0] ? $row[0] : 0;
        $phours = $row[1] ? $row[1] : 0;
525 526
        return array($pcount, $phours);
    }
527

528 529 530
    #
    # Usage over the last week. Just phours, cause pcount is not very useful.
    #
531
    function WeeksUsage($target) {
532 533
        $weekago  = time() - (3600 * 24 * 7);
        $phours   = 0;
534 535 536 537 538 539 540 541 542 543 544
        $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'";
        }
545 546 547 548 549 550 551

        #
        # This gets existing experiments back one week.
        #
        $query_result =
            DBQueryFatal("select physnode_count,UNIX_TIMESTAMP(created) ".
                         "  from apt_instances ".
552
                         "where $clause and physnode_count>0");
553 554 555 556 557 558 559 560 561 562

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

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

563
            $pcount += $pnodes;
564 565 566 567 568 569 570 571 572 573
            $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 ".
574
                         "where $clause and physnode_count>0 and " .
575 576 577 578 579 580 581 582 583 584 585 586
                         "      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 B Stoller's avatar
Leigh B Stoller committed
587 588 589
            if ($diff < 0)
                $diff = 0;

590
            $pcount += $pnodes;
591 592
            $phours += $pnodes * ($diff / 3600.0);
        }
593
        return array ($pcount, $phours);
594 595 596 597 598
    }

    #
    # Usage over the last months Just phours, cause pcount is not very useful.
    #
599
    function MonthsUsage($target) {
600
        $monthago = time() - (3600 * 24 * 28);
601
        $pcount   = 0;
602
        $phours   = 0;
603 604 605 606 607 608 609 610 611 612
        $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'";
        }
613 614 615 616 617 618 619

        #
        # This gets existing experiments back one week.
        #
        $query_result =
            DBQueryFatal("select physnode_count,UNIX_TIMESTAMP(created) ".
                         "  from apt_instances ".
620
                         "where $clause and physnode_count>0");
621 622 623 624 625 626 627 628 629 630

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

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

631
            $pcount += $pnodes;
632 633 634 635 636 637 638 639 640 641
            $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 ".
642
                         "where $clause and physnode_count>0 and " .
643 644 645 646 647 648 649 650 651 652 653 654
                         "      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 B Stoller's avatar
Leigh B Stoller committed
655 656 657
            if ($diff < 0)
                $diff = 0;

658
            $pcount += $pnodes;
659 660
            $phours += $pnodes * ($diff / 3600.0);
        }
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        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, ".
685 686
                         "    IF(created > DATE_SUB(now(), INTERVAL $days DAY), ".
                         "       created, DATE_SUB(now(), INTERVAL $days DAY)), now())) ".
687 688 689 690 691 692
                         "    as phours ".
                         "   from apt_instances ".
                         "   where physnode_count>0) ".
                         "  union ".
                         "  (select $which,physnode_count,created,destroyed, ".
                         "   physnode_count * (TIMESTAMPDIFF(HOUR, ".
693 694
                         "    IF(created > DATE_SUB(now(), INTERVAL $days DAY), ".
                         "       created, DATE_SUB(now(), INTERVAL $days DAY)), destroyed)) ".
695 696 697
                         "    as phours ".
                         "   from apt_instance_history ".
                         "   where physnode_count>0 and ".
698
                         "         destroyed>DATE_SUB(now(),INTERVAL $days DAY)))".
699 700 701 702 703 704 705 706 707 708 709 710 711 712
                         "   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);
713 714
    }

715
    #
716 717
    # Return Caching Token, either the latest commit hash
    # or the current time for development trees.
718
    #
719 720 721 722 723 724 725
    function CacheToken() {
      if (preg_match("/\/dev\//", $_SERVER["SCRIPT_NAME"]))
      {
        return date('Y-m-d-H:i:s');
      }
      else
      {
726 727 728 729 730 731 732 733 734
          $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];
735
      }
736
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
737
}
738 739 740 741 742 743 744 745 746

class InstanceSliver
{
    var	$sliver;
    
    #
    # Constructor by lookup on unique index.
    #
    function InstanceSliver($instance, $urn) {
747 748 749 750 751
        if (!$instance) {
            TBMAIL("stoller", "undefined instance", $urn);
	    $this->sliver = null;
	    return;
        }
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
	$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'); }
775 776
    function physnode_count() { return $this->field('physnode_count'); }
    function virtnode_count() { return $this->field('virtnode_count'); }
777 778 779 780
    function aggregate_name() {
        global $urn_mapping;
        return $urn_mapping[$this->aggregate_urn()];
    }
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

    # 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. 
        #
796
        $webtask_id = null;
797
        $webtask = WebTask::LookupByObject($instance->uuid());
798 799 800
        if ($webtask) {
            $webtask_id = $webtask->task_id();
        }
801 802 803 804 805 806 807
        $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(),
808
            "webtask_id" => $webtask_id,
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
        );
        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;
    }
}

834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
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);
851 852
        $this->info["reason"]  = trim($this->info["reason"]);
        $this->info["message"] = trim($this->info["message"]);
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
    }
    # 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'); }
    function reason()       { return $this->field('reason'); }
    function message()      { return $this->field('message'); }

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

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
# $amlist, $fedlist, and $status are all output arrays
function CalculateAggregateStatus(&$amlist, &$fedlist, &$status) {
    $am_array = Instance::DefaultAggregateList();
    while (list($ignore, $aggregate) = each($am_array)) {
        $urn = $aggregate->urn();
        $am  = $aggregate->name();
        $amlist[$urn] = $am;
        #
        # 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(),
926
                "VMsAvailable"     => $aggregate->vfree(),
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                "VMsTotal"         => $aggregate->vcount(),
                "health"           => ($aggregate->status() == "up" ? 100 :
                                       ($aggregate->status() == "down" ?
                                        0 : 50)),
                "status"           => ($aggregate->status() != "down" ?
                                       "SUCCESS" : "FAILED"));
        }
    }
}

function SpitAggregateStatus() {
    $amlist     = array();
    $fedlist    = array();
    $status     = array();
    CalculateAggregateStatus($amlist, $fedlist, $status);
    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";
}

Leigh B Stoller's avatar
Leigh B Stoller committed
953
?>