dbdefs.php3.in 31.5 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{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/>.
# 
# }}}
23
#
24 25
# Database Constants
#
26 27
require("dbcheck.php3");

28
$TBDBNAME       = "@TBDBNAME@";
29
$TBOPSPID	= "emulab-ops";
30
$NODEDEAD_PID   = $TBOPSPID;
31
$NODEDEAD_EID   = "hwdown";
32
$FIRSTUSER      = "elabman";
33 34 35
$NODERELOADING_PID	= $TBOPSPID;
$NODERELOADING_EID	= "reloading";
$NODERELOADPENDING_EID	= "reloadpending";
36

37 38
# All these constants need to go at some point, replaced by data from
# the regex table. 
39
$TBDB_UIDLEN    = 8;
40 41 42 43
# These are both shorter then the DB lengths, but since some images croak
# on very long mount point names, we keep them short via this interface.
$TBDB_PIDLEN    = 16;
$TBDB_GIDLEN	= 16;
Leigh Stoller's avatar
Leigh Stoller committed
44
$TBDB_UNIXGLEN	= 16;
45
$TBDB_NODEIDLEN = 10;
46 47
$TBDB_PHONELEN  = 32;
$TBDB_USRNAMELEN= 64;
48
$TBDB_EMAILLEN  = 64;
49
$TBDB_MMLENGTH  = 64;
50 51
$TBDB_ARCHIVE_TAGLEN = 64;
$TBDB_ARCHIVE_MSGLEN = 2048;
52

53 54 55
# Minimum length.
$TBDB_MINPASSPHRASE = 10;

56 57 58 59 60 61 62 63
#
# Current policy is to prefix the EID with the PID. Make sure it is not
# too long for the database. PID is 12, and the max is 32, so the user
# cannot have provided an EID more than 19, since other parts of the system
# may concatenate them together with a hyphen.
#
$TBDB_EIDLEN    = 19;

64 65
$TBDB_OSID_OSIDLEN         = 35;
$TBDB_OSID_OSNAMELEN       = 20;
66
$TBDB_OSID_VERSLEN         = 12;
67 68
$TBDB_IMAGEID_IMAGEIDLEN   = 45;
$TBDB_IMAGEID_IMAGENAMELEN = 30;
69

70 71 72
#
# User status field.
#
73 74 75 76 77
define("TBDB_USERSTATUS_ACTIVE",	"active");
define("TBDB_USERSTATUS_NEWUSER",	"newuser");
define("TBDB_USERSTATUS_UNAPPROVED",	"unapproved");
define("TBDB_USERSTATUS_UNVERIFIED",	"unverified");
define("TBDB_USERSTATUS_FROZEN",	"frozen");
78
define("TBDB_USERSTATUS_ARCHIVED",	"archived");
79
define("TBDB_USERSTATUS_NONLOCAL",	"nonlocal");
80
define("TBDB_USERSTATUS_INACTIVE",	"inactive");
81

82 83 84 85 86 87 88
#
# Type of new account.
#
define("TBDB_NEWACCOUNT_REGULAR",	0x0);
define("TBDB_NEWACCOUNT_PROJLEADER",	0x1);
define("TBDB_NEWACCOUNT_WIKIONLY",	0x2);
define("TBDB_NEWACCOUNT_WEBONLY",	0x4);
89
define("TBDB_NEWACCOUNT_NONLOCAL",	0x8);
90

Leigh Stoller's avatar
Leigh Stoller committed
91 92 93 94 95 96 97 98 99 100 101
#
# Trust. Define the trust level as an increasing value. Then define a
# function to return whether the given trust is high enough.
#
$TBDB_TRUST_NONE		= 0;
$TBDB_TRUST_USER		= 1;
$TBDB_TRUST_LOCALROOT		= 2;
$TBDB_TRUST_GROUPROOT		= 3;
$TBDB_TRUST_PROJROOT		= 4;
$TBDB_TRUST_ADMIN		= 5;

102 103 104 105 106 107 108 109 110
#
# Text strings in the DB for above.
# 
define("TBDB_TRUSTSTRING_NONE",		"none");
define("TBDB_TRUSTSTRING_USER",		"user");
define("TBDB_TRUSTSTRING_LOCALROOT",	"local_root");
define("TBDB_TRUSTSTRING_GROUPROOT",	"group_root");
define("TBDB_TRUSTSTRING_PROJROOT",	"project_root");

111
#
112
# Map to new names in the UI, the old ones are nonsensical.
113 114 115 116 117 118 119 120 121 122
#
$newTrustMap = array("none"         => "none",
                     "user"         => "user",
                     "local_root"   => "root",
                     "group_root"   => "manager",
                     "project_root" => "leader",
                     "root"         => "local_root",
                     "manager"      => "group_root",
                     "leader"       => "project_root");

Leigh Stoller's avatar
Leigh Stoller committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
#
# These are the permission types. Different operations for the varying
# types of things we need to control access to.
#
# Things you can do to a node.
$TB_NODEACCESS_READINFO		= 1;
$TB_NODEACCESS_MODIFYINFO	= 2;
$TB_NODEACCESS_LOADIMAGE	= 3;
$TB_NODEACCESS_REBOOT		= 4;
$TB_NODEACCESS_POWERCYCLE	= 5;
$TB_NODEACCESS_MIN		= $TB_NODEACCESS_READINFO;
$TB_NODEACCESS_MAX		= $TB_NODEACCESS_POWERCYCLE;

# User Info (modinfo web page, etc).
$TB_USERINFO_READINFO		= 1;
$TB_USERINFO_MODIFYINFO		= 2;
$TB_USERINFO_MIN		= $TB_USERINFO_READINFO;
$TB_USERINFO_MAX		= $TB_USERINFO_MODIFYINFO;

# Experiments (also batch experiments).
$TB_EXPT_READINFO		= 1;
$TB_EXPT_MODIFY			= 2;	# Allocate/dealloc nodes
$TB_EXPT_DESTROY		= 3;
146
$TB_EXPT_UPDATE			= 4;
Leigh Stoller's avatar
Leigh Stoller committed
147
$TB_EXPT_MIN			= $TB_EXPT_READINFO;
148
$TB_EXPT_MAX			= $TB_EXPT_UPDATE;
Leigh Stoller's avatar
Leigh Stoller committed
149 150 151 152 153

# Projects.
$TB_PROJECT_READINFO		= 1;
$TB_PROJECT_MAKEGROUP		= 2;
$TB_PROJECT_EDITGROUP		= 3;
154
$TB_PROJECT_GROUPGRABUSERS      = 4;
155 156 157 158 159 160 161 162 163 164
$TB_PROJECT_BESTOWGROUPROOT     = 5;
$TB_PROJECT_DELGROUP		= 6;
$TB_PROJECT_LEADGROUP		= 7;
$TB_PROJECT_ADDUSER		= 8;
$TB_PROJECT_DELUSER             = 9;
$TB_PROJECT_MAKEOSID		= 10;
$TB_PROJECT_DELOSID		= 11;
$TB_PROJECT_MAKEIMAGEID		= 12;
$TB_PROJECT_DELIMAGEID		= 13;
$TB_PROJECT_CREATEEXPT		= 14;
Leigh Stoller's avatar
Leigh Stoller committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178
$TB_PROJECT_MIN			= $TB_PROJECT_READINFO;
$TB_PROJECT_MAX			= $TB_PROJECT_CREATEEXPT;

# OSIDs 
$TB_OSID_READINFO		= 1;
$TB_OSID_MODIFYINFO		= 2;
$TB_OSID_DESTROY		= 3;
$TB_OSID_MIN			= $TB_OSID_READINFO;
$TB_OSID_MAX			= $TB_OSID_DESTROY;

# ImageIDs
$TB_IMAGEID_READINFO		= 1;
$TB_IMAGEID_MODIFYINFO		= 2;
$TB_IMAGEID_ACCESS		= 3;
179 180
$TB_IMAGEID_EXPORT		= 4;
$TB_IMAGEID_DESTROY		= 5;
Leigh Stoller's avatar
Leigh Stoller committed
181 182 183
$TB_IMAGEID_MIN			= $TB_IMAGEID_READINFO;
$TB_IMAGEID_MAX			= $TB_IMAGEID_DESTROY;

184 185
# Leases
$LEASE_ACCESS_READINFO		= 1;
186 187 188 189
$LEASE_ACCESS_MODIFYINFO	= 2;
$LEASE_ACCESS_READ		= 3;
$LEASE_ACCESS_MODIFY		= 4;
$LEASE_ACCESS_DESTROY		= 5;
190 191 192
$LEASE_ACCESS_MIN		= $LEASE_ACCESS_READINFO;
$LEASE_ACCESS_MAX		= $LEASE_ACCESS_DESTROY;

193
# Experiment states (that matter to us).
194 195
$TB_EXPTSTATE_NEW		= "new"; 
$TB_EXPTSTATE_PRERUN		= "prerunning"; 
196
$TB_EXPTSTATE_SWAPPING		= "swapping";
197
$TB_EXPTSTATE_SWAPPED		= "swapped";
198
$TB_EXPTSTATE_ACTIVATING	= "activating";
199
$TB_EXPTSTATE_ACTIVE		= "active";
Leigh Stoller's avatar
Leigh Stoller committed
200
$TB_EXPTSTATE_PANICED		= "paniced";
201
$TB_EXPTSTATE_QUEUED		= "queued";
202
$TB_EXPTSTATE_MODIFY_RESWAP	= "modify_reswap";
203

204 205 206 207 208
# Interfaces roles.
define("TBDB_IFACEROLE_CONTROL",	"ctrl");
define("TBDB_IFACEROLE_EXPERIMENT",	"expt");
define("TBDB_IFACEROLE_JAIL",		"jail");
define("TBDB_IFACEROLE_FAKE",		"fake");
209
define("TBDB_IFACEROLE_GW",		"gw");
210
define("TBDB_IFACEROLE_OTHER",		"other");
211
define("TBDB_IFACEROLE_OUTER_CONTROL",  "outer_ctrl");
212
define("TBDB_IFACEROLE_MANAGEMENT",	"mngmnt");
213

214 215 216
# Node states that the web page cares about.
define("TBDB_NODESTATE_ISUP",		"ISUP");
define("TBDB_NODESTATE_PXEWAIT",	"PXEWAIT");
217 218
define("TBDB_NODESTATE_POWEROFF",	"POWEROFF");
define("TBDB_NODESTATE_ALWAYSUP",	"ALWAYSUP");
219

220 221 222 223 224 225
# User Interface types
define("TBDB_USER_INTERFACE_EMULAB",	"emulab");
define("TBDB_USER_INTERFACE_PLAB",	"plab");
$TBDB_USER_INTERFACE_LIST = array(TBDB_USER_INTERFACE_EMULAB,
				  TBDB_USER_INTERFACE_PLAB);

226 227 228 229
# Lintest levels.
$linktest_levels	= array();
$linktest_levels[0]	= "Skip Linktest";
$linktest_levels[1]	= "Connectivity and Latency";
Leigh Stoller's avatar
Leigh Stoller committed
230 231 232
$linktest_levels[2]	= "Plus Static Routing";
$linktest_levels[3]	= "Plus Loss";
$linktest_levels[4]	= "Plus Bandwidth";
233 234
define("TBDB_LINKTEST_MAX", 4);

Leigh Stoller's avatar
Leigh Stoller committed
235 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
#
# Convert a trust string to the above numeric values.
#
function TBTrustConvert($trust_string)
{
    global $TBDB_TRUST_NONE;
    global $TBDB_TRUST_USER;
    global $TBDB_TRUST_LOCALROOT;
    global $TBDB_TRUST_GROUPROOT;
    global $TBDB_TRUST_PROJROOT;
    global $TBDB_TRUST_ADMIN;
    $trust_value = 0;

    #
    # Convert string to value. Perhaps the DB should have done it this way?
    # 
    if (strcmp($trust_string, "none") == 0) {
	    $trust_value = $TBDB_TRUST_NONE;
    }
    elseif (strcmp($trust_string, "user") == 0) {
	    $trust_value = $TBDB_TRUST_USER;
    }
    elseif (strcmp($trust_string, "local_root") == 0) {
	    $trust_value = $TBDB_TRUST_LOCALROOT;
    }
    elseif (strcmp($trust_string, "group_root") == 0) {
	    $trust_value = $TBDB_TRUST_GROUPROOT;
    }
    elseif (strcmp($trust_string, "project_root") == 0) {
	    $trust_value = $TBDB_TRUST_PROJROOT;
    }
    elseif (strcmp($trust_string, "admin") == 0) {
	    $trust_value = $TBDB_TRUST_ADMIN;
    }
    else {
	    TBERROR("Invalid trust value $trust_string!", 1);
    }

    return $trust_value;
}

#
# Return true if the given trust string is >= to the minimum required.
# The trust value can be either numeric or a string; if a string its
# first converted to the numeric equiv.
#
function TBMinTrust($trust_value, $minimum)
{
    global $TBDB_TRUST_NONE;
    global $TBDB_TRUST_ADMIN;

    if ($minimum < $TBDB_TRUST_NONE || $minimum > $TBDB_TRUST_ADMIN) {
	    TBERROR("Invalid minimum trust $minimum!", 1);
    }

    #
    # Sleazy?
    #
    if (gettype($trust_value) == "string") {
	$trust_value = TBTrustConvert($trust_value);
    }
    
    return $trust_value >= $minimum;
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
#
# Confirm a valid node type
#
# usage TBValidNodeType($type)
#       returns 1 if valid
#       returns 0 if not valid
#
function TBValidNodeType($type)
{
    $query_result =
	DBQueryFatal("select type from node_types where type='$type'");

    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    return 1;
}

318
function TBUidNodeLastLogin($uid_idx)
319 320
{
    $query_result =
321
	DBQueryFatal("select * from uidnodelastlogin where uid_idx='$uid_idx'");
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row   = mysql_fetch_array($query_result);
    return $row;
}

#
# Return the last login for the node, but only after the experiment was
# created (swapped in).
# 
function TBNodeUidLastLogin($node_id)
{
    $query_result =
	DBQueryFatal("select n.* from nodeuidlastlogin as n ".
		     "left join reserved as r on n.node_id=r.node_id ".
		     "left join experiments as e ".
		     " on r.eid=e.eid and r.pid=e.pid ".
		     "where r.node_id='$node_id' and ".
		     "  DATE_ADD(n.date, INTERVAL n.time HOUR_SECOND) >= ".
		     "           e.expt_swapped");

    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row   = mysql_fetch_array($query_result);
    return $row;
}

352 353 354
#
# Return the last login for the users node.
# 
355
function TBUsersLastLogin($uid_idx)
356 357
{
    $query_result =
358
	DBQueryFatal("select * from userslastlogin where uid_idx='$uid_idx'");
359 360 361 362 363 364 365 366

    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row   = mysql_fetch_array($query_result);
    return $row;
}

367 368 369 370 371 372 373
#
# Return the last login for all of the nodes in an experiment, but only
# after the experiment was created (swapped in).
# 
function TBExpUidLastLogins($pid, $eid)
{
    $query_result =
374 375
	DBQueryFatal("select n.*, date_format(n.date,'%c/%e') as shortdate, ".
		     "to_days(now())-to_days(n.date) as daysidle ".
376
	             "from nodeuidlastlogin as n ".
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
		     "left join reserved as r on n.node_id=r.node_id ".
		     "left join experiments as e ".
		     " on r.eid=e.eid and r.pid=e.pid ".
		     "where r.pid='$pid' and r.eid='$eid' and ".
		     "  DATE_ADD(n.date, INTERVAL n.time HOUR_SECOND) >= ".
		     "           e.expt_swapped ".
		     "      order by n.date DESC");

    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row   = mysql_fetch_array($query_result);
    return $row;
}

392
#
393 394 395
# Number of globally free PCs. See ptopgen and libdb for corresponding
# usage of the eventstate. A node is not really considered free for use
# unless it is also in the ISUP/PXEWAIT state.
396
#
397
function TBFreePCs($target = null)
398
{
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    $clause    = "0";
    $findinset = "";
    $pids      = array();
    
    if ($target) {
        if (get_class($target) == "Group") {
            $pid = $target->pid();
            $pids[] = $pid;
            $clauses[] = "p.pid='$pid'";
        }
        else {
            $uid_idx = $target->uid_idx();
            $query_result =
                DBQueryFatal("select distinct pid from group_membership ".
                             "where uid_idx='$uid_idx'");
            if (mysql_num_rows($query_result)) {
                $clauses = array();
                while ($row = mysql_fetch_row($query_result)) {
                    $pid = $row[0];
                    $pids[] = $pid;
                    $clauses[] = "p.pid='$pid'";
                }
            }
        }
        $clause = "p.pid is null or " . join(" or ", $clauses);
        $findinset = "or FIND_IN_SET(a.reserved_pid, '" . join(",", $pids)."')";
    }
    $total = 0;
    
428
    $query_result =
429
	DBQueryFatal("select a.type,count(a.node_id) from nodes as a ".
430 431
		     "left join reserved as b on a.node_id=b.node_id ".
		     "left join node_types as nt on a.type=nt.type ".
432 433 434 435 436 437 438
                     "left join node_type_attributes as attr on ".
                     "     attr.type=a.type and ".
                     "     attr.attrkey='noshowfreenodes' ".
		     "where b.node_id is null and a.role='testnode' and ".
                     "      attr.attrvalue is null and ".
		     "      nt.class = 'pc' and ".
                     "      (a.reserved_pid is null $findinset) and ".
439
                     "      (a.eventstate='" . TBDB_NODESTATE_ISUP . "' or ".
440
                     "       a.eventstate='" . TBDB_NODESTATE_POWEROFF . "' or ".
441 442 443
                     "       a.eventstate='" . TBDB_NODESTATE_ALWAYSUP . "' or ".
                     "       a.eventstate='" . TBDB_NODESTATE_PXEWAIT . "') ".
		     "group by a.type");
444 445 446 447
    
    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
448 449 450 451 452 453 454
    while ($row = mysql_fetch_row($query_result)) {
        $type  = $row[0];
        $count = $row[1];
        
        $policy_result =
            DBQueryFatal("select max(count) from group_policies as p ".
                         "where p.policy='type' and p.auxdata='$type' and ".
455 456
                         "      (p.pid='-' or $clause) ".
                         "having max(count)>=0");
457 458 459 460 461 462 463 464 465 466
        
        if (mysql_num_rows($policy_result)) {
            $row = mysql_fetch_row($policy_result);
            if ($count > $row[0]) {
                $count = $row[0];
            }
        }
        $total += $count;
    }
    return $total;
467 468
}

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
#
# Number of PCs. 
#
function TBTotalPCs()
{
    $total      = 0;
    
    $query_result =
	DBQueryFatal("select a.type,count(a.node_id) from nodes as a ".
		     "left join node_types as nt on a.type=nt.type ".
                     "left join node_type_attributes as attr on ".
                     "     attr.type=a.type and ".
                     "     attr.attrkey='noshowfreenodes' ".
		     "where a.role='testnode' and ".
                     "      attr.attrvalue is null and ".
		     "      nt.class = 'pc' ".
		     "group by a.type");
    
    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    while ($row = mysql_fetch_row($query_result)) {
        $type  = $row[0];
        $count = $row[1];
        $total += $count;
    }
    return $total;
}

#
# Number of total/free shared VMs. 
#
function TBVMCounts(&$total, &$free)
{
    $query_result =
	DBQueryFatal("select n.node_id,aux.count,r.erole from nodes as n ".
                     "left join reserved as r on r.node_id=n.node_id ".
		     "left join node_auxtypes as aux on ".
                     "     aux.node_id=n.node_id and aux.type='pcvm' ".
                     "where r.erole='sharedhost'");

    if (mysql_num_rows($query_result) == 0) {
        $total = 0;
        $free  = 0;
    }
    while ($row = mysql_fetch_row($query_result)) {
        $node_id = $row[0];
        $count  = $row[1];
        if (isset($count)) {
            $total += $count;
            $used_result =
                DBQueryFatal("select count(node_id) from nodes ".
                             "where phys_nodeid='$node_id'");
            $urow = mysql_fetch_row($used_result);
            $ucount = $urow[0];
            $free += $count - $ucount;
        }
    }
    return;
}

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
#
# Number of logged in users
#
function TBLoggedIn()
{
    $query_result =
	DBQueryFatal("select count(distinct uid) from login ".
		     "where timeout > UNIX_TIMESTAMP(now())");

    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row = mysql_fetch_row($query_result);
    return $row[0];
}

#
# Number of active experiments.
#
function TBActiveExperiments()
{
    $query_result =
	DBQueryFatal("select count(*) from experiments where ".
		     "state='active' and pid!='emulab-ops' and ".
		     "pid!='testbed'");
    
    if (mysql_num_rows($query_result) != 1) {
	return 0;
    }
    $row = mysql_fetch_array($query_result);
    return $row[0];
}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
#
# Number of PCs reloading.
#
function TBReloadingPCs()
{
    global $NODERELOADING_PID, $NODERELOADING_EID, $NODERELOADPENDING_EID;

    $query_result =
	DBQueryFatal("select count(*) from reserved ".
		     "where pid='$NODERELOADING_PID' and ".
		     "      (eid='$NODERELOADING_EID' or ".
		     "       eid='$NODERELOADPENDING_EID')");
    
    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row = mysql_fetch_row($query_result);
    return $row[0];
}

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
#
# Check if a site-specific variable exists. 
#
# usage: TBSiteVarExists($name)
#        returns 1 if variable exists;
#        returns 0 otherwise.
#
function TBSiteVarExists($name)
{
    global $lastact_query;

    $name  = addslashes( $name );

    $query_result = 
	DBQueryFatal("select name from sitevariables ".
		     "where name='$name'");

    if (mysql_num_rows($query_result) > 0) {
	return 1;
    } else {
	return 0;
    }
}

#
# Get site-specific variable.
# Get the value of the variable, or the default value if
# the value is undefined (NULL).
#
# usage: TBGetSiteVar($name)
#        returns value if variable is defined;
#        dies otherwise.
#
function TBGetSiteVar($name)
{
    global $lastact_query;

    $name  = addslashes( $name );

    $query_result = 
	DBQueryFatal("select value, defaultvalue from sitevariables ".
		     "where name='$name'");

    if (mysql_num_rows($query_result) > 0) {    
	$row = mysql_fetch_array($query_result);

629 630
	$value = $row["value"];
	$defaultvalue = $row["defaultvalue"];
631 632 633 634
	if (isset($value)) { return $value; }
	if (isset($defaultvalue)) { return $defaultvalue; }
    }
    
635
    TBERROR("Attempted to fetch unknown site variable '$name'!", 1);
636 637
}

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
#
# Set site variable.
#
function SetSiteVar($name, $args, &$errors) {
    global $suexec_output, $suexec_output_array;

    #
    # Generate a temporary file and write in the XML goo.
    #
    $xmlname = tempnam("/tmp", "editsitevars");
    if (! $xmlname) {
	TBERROR("Could not create temporary filename", 0);
	$errors[] = "Transient error(1); please try again later.";
	return null;
    }
    if (! ($fp = fopen($xmlname, "w"))) {
	TBERROR("Could not open temp file $xmlname", 0);
	$errors[] = "Transient error(2); please try again later.";
	return null;
    }

    # Add these. Maybe caller should do this?
    $args["name"] = $name;

    fwrite($fp, "<sitevar>\n");
    foreach ($args as $name => $value) {
	fwrite($fp, "<attribute name=\"$name\">");
	fwrite($fp, "  <value>" . htmlspecialchars($value) . "</value>");
	fwrite($fp, "</attribute>\n");
    }
    fwrite($fp, "</sitevar>\n");
    fclose($fp);
    chmod($xmlname, 0666);

    $retval = SUEXEC("nobody", "nobody", "webeditsitevars $xmlname",
		     SUEXEC_ACTION_IGNORE);

    if ($retval) {
	if ($retval < 0) {
	    $errors[] = "Transient error(3, $retval); please try again later.";
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	}
	else {
	    # unlink($xmlname);
	    if (count($suexec_output_array)) {
		for ($i = 0; $i < count($suexec_output_array); $i++) {
		    $line = $suexec_output_array[$i];
		    if (preg_match("/^([-\w]+):\s*(.*)$/",
				   $line, $matches)) {
			$errors[$matches[1]] = $matches[2];
		    }
		    else
			$errors[] = $line;
		}
	    }
	    else
		$errors[] = "Transient error(4, $retval); please try again later.";
	}
	return null;
    }

    # There are no return value(s) to parse at the end of the output.

    # Unlink this here, so that the file is left behind in case of error.
    # We can then create the sitevar by hand from the xmlfile, if desired.
    unlink($xmlname);
    return true;
}

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
#
# Count available planetlab nodes.
#
# usage: TBPlabAvail()
#        returns the number of free PlanetLab nodes of each type
#        returns an empty array on error
#
function TBPlabAvail() {
    $types = array();
    #
    # We have to do this in two queries, due to the fact that we do pcplabtypes
    # different from the way we do other types (it's on the vnodes, not in the
    # node_autypes for the pnode.)
    #
    # XXX - hardcodes hwdown and emulab-ops
    #
    $tables = "nodes AS n " .
	      "LEFT JOIN widearea_nodeinfo AS w ON n.phys_nodeid = w.node_id " .
              "LEFT JOIN node_auxtypes AS na ON n.node_id = na.node_id " .
	      "LEFT JOIN reserved AS r ON n.phys_nodeid = r.node_id " .
	      "LEFT JOIN node_status AS ns ON n.phys_nodeid = ns.node_id " .
	      "LEFT JOIN node_features AS nf ON n.phys_nodeid = nf.node_id " .
	      "LEFT JOIN node_features AS nf2 ON n.phys_nodeid = nf2.node_id";
    $available = "ns.status='up' AND (nf.feature='+load' AND nf.weight < 1.0) " .
                 "AND (nf2.feature='+disk' and nf2.weight < 1.0) " .
		 "AND !(r.pid = 'emulab-ops' and r.eid = 'hwdown')";

    #
    # Grab pcplab nodes
    #
    $query_result = DBQueryFatal("SELECT count(*), count(distinct w.site) " .
                                 "FROM $tables " .
				 "WHERE (n.type='pcplabphys') ".
				 "    AND($available)");
    if (mysql_num_rows($query_result)) {
	$row = mysql_fetch_row($query_result);
	$types['pcplab'] = array($row[0],$row[1]);
    }

    #
    # Grab the more specific types
    #
    $query_result = DBQueryFatal("SELECT na.type, count(*), " .
				 "count(distinct w.site) FROM $tables " .
				 "WHERE (n.type='pcplabphys') " .
				 "    AND ($available) " .
				 "GROUP BY na.type");
    while ($row = mysql_fetch_row($query_result)) {
	$types[$row[0]] = array($row[1],$row[2]);
    }

    return $types;
}

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
#
# Return firstinit state.
#
function TBGetFirstInitState()
{
    $firstinit = TBGetSiteVar("general/firstinit/state");
    if ($firstinit == "Ready")
	return null;
    return $firstinit;
}
function TBSetFirstInitState($newstate)
{
    $query_result = 
	DBQueryFatal("update sitevariables set value='$newstate' ".
		     "where name='general/firstinit/state'");
}
function TBGetFirstInitPid()
{
    return TBGetSiteVar("general/firstinit/pid");
}
function TBSetFirstInitPid($pid)
{
    $query_result = 
	DBQueryFatal("update sitevariables set value='$pid' ".
		     "where name='general/firstinit/pid'");
}

788 789 790 791 792 793
#
# Get the build and source version numbers, as for the banner.
#
function TBGetVersionInfo(&$major, &$minor, &$build)
{
    $query_result = 
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
	DBQueryFatal("select value from sitevariables ".
		     "where name='general/version/build'");

    if (mysql_num_rows($query_result)) {
	$row = mysql_fetch_row($query_result);
	$build = $row[0];
    }
    else {
	$build = "Unknown";
    }

    $query_result =
	DBQuery("select value from version_info where name='dbrev'");
    if ($query_result && mysql_num_rows($query_result)) {
	$row = mysql_fetch_row($query_result);
Mike Hibler's avatar
Mike Hibler committed
809
	list($a,$b) = preg_split('/\./', $row[0]);
810 811 812 813 814 815 816 817
	$a = (isset($a) && $a != "" ? $a : "x");
	$b = (isset($b) && $b != "" ? $b : "y");
	$major = $a;
	$minor = $b;
    }
    else {
	$major = "X";
	$minor = "Y";
818 819 820 821
    }
    return 1;
}

822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
#
# Get the commit hash.
#
function TBGetCommitHash()
{
    $query_result = 
	DBQueryFatal("select value from version_info ".
		     "where name='commithash'");

    if (mysql_num_rows($query_result)) {
	$row = mysql_fetch_row($query_result);
	return $row[0];
    }
    return null;
}

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
#
# Return a node_tye attribute entry.
#
function NodeTypeAttribute($type, $key, &$value)
{
    $query_result =
	DBQueryFatal("select attrvalue from node_type_attributes ".
		     "where type='$type' and attrkey='$key'");
    
    if (!mysql_num_rows($query_result)) {
	$value = null;
	return 0;
    }

    $row = mysql_fetch_row($query_result);
    $value = $row[0];
    return 1;
}

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
#
# Return a unique index from emulab_indicies for the indicated name.
# Updates the index to be, well, unique.
# Eats flaming death on error.
#
function TBGetUniqueIndex($name)
{
    #
    # Lock the table to avoid conflicts
    #
    DBQueryFatal("lock tables emulab_indicies write");

    $query_result =
	DBQueryFatal("select idx from emulab_indicies ".
		     "where name='$name'");

    $row = mysql_fetch_array($query_result);
    $curidx = $row["idx"];
    if (!isset($curidx)) {
	$curidx = 1;
    }

    $nextidx = $curidx + 1;

    DBQueryFatal("replace into emulab_indicies (name, idx) ".
		 "values ('$name', $nextidx)");
    DBQueryFatal("unlock tables");

    return $curidx;
}

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 927 928 929 930 931 932 933
#
# Trivial wrapup of Logile table so we can use it in url_defs.
# 
class Logfile
{
    var	$logfile;

    #
    # Constructor by lookup on unique index.
    #
    function Logfile($logid) {
	$safe_id = addslashes($logid);

	$query_result =
	    DBQueryWarn("select * from logfiles ".
			"where logid='$safe_id'");

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

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

    # Lookup by ID
    function Lookup($logid) {
	$foo = new Logfile($logid);

	if (!$foo || !$foo->IsValid())
	    return null;

	return $foo;
    }

    # accessors
    function field($name) {
	return (is_null($this->logfile) ? -1 : $this->logfile[$name]);
    }
    function logid()	     { return $this->field("logid"); }
    function filename()	     { return $this->field("filename"); }
    function isopen()        { return $this->field("isopen"); }
934 935
    function uid_idx()       { return $this->field("uid_idx"); }
    function gid_idx()       { return $this->field("gid_idx"); }
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 982 983 984 985 986 987 988 989 990
function FeatureEnabled($feature, $user, $group, $experiment = null)
{
    #
    # See if feature is globally disabled or enabled.
    #
    $query_result =
        DBQueryFatal("select * from emulab_features where feature='$feature'");

    if (!mysql_num_rows($query_result)) {
        return 0;
    }
    $frow = mysql_fetch_array($query_result);
    if ($frow["disabled"]) {
        return 0;
    }
    if ($frow["enabled"]) {
        return 1;
    }
    $enabled = 0;

    if ($user) {
        $uid_idx = $user->idx();
	
	$query_result =
	    DBQueryFatal("select * from user_features ".
                         "where feature='$feature' and uid_idx='$uid_idx'");

	$enabled += mysql_num_rows($query_result);
    }
    if ($group) {
	$pid_idx = $group->pid_idx();
	$gid_idx = $group->gid_idx();
	
	$query_result =
	    DBQueryFatal("select * from group_features ".
                         "where feature='$feature' and ".
                         "      pid_idx='$pid_idx' and gid_idx='$gid_idx'");
        
	$enabled += mysql_num_rows($query_result);
    }
    if ($experiment) {
	$exptidx = $experiment->idx();
	
	$query_result =
	    DBQueryWarn("select * from experiment_features ".
			"where feature='$feature' and ".
			"      exptidx='$exptidx'");

	$enabled += mysql_num_rows($query_result);
    }
    return $enabled;
}

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
#
# Do we have a storage pool?
#
function HaveStoragePool()
{
    global $TBOPSPID;
    
    $experiment = Experiment::LookupByPidEid($TBOPSPID, "storage-pool");
    if ($experiment) {
	return $experiment->PCCount();
    }
    return 0;
}

1005 1006 1007
# Convert local time to GMT date string.
function DateStringGMT($date)
{
1008 1009 1010
    if (is_null($date) || $date == "" || $date == "0000-00-00 00:00:00") {
        return null;
    }
1011 1012 1013
    elseif (is_int($date)) {
        gmdate("Y-m-d\TH:i:s\Z", $date);
    }
1014 1015 1016
    return gmdate("Y-m-d\TH:i:s\Z", strtotime($date));
}

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
# Check to see if a date is actually no date. Really, please do not
# use default dates in the sql file.
function NullDate($date)
{
    if (is_null($date) || $date == "" || $date == "0000-00-00 00:00:00") {
	return null;
    }
    return $date;
}

1027
#
Leigh Stoller's avatar
Leigh Stoller committed
1028 1029 1030
#
# DB Interface.
#
1031 1032
$maxtries = 3;
$DBlinkid = 0;
1033
while ($maxtries) {
1034
    $DBlinkid = mysql_connect("localhost", basename($_SERVER["SCRIPT_NAME"]));
1035 1036 1037
    if ($DBlinkid) {
	break;
    }
1038 1039 1040 1041
    $maxtries--;
    sleep(1);
}
if (! $DBlinkid) {
1042 1043
    USERERROR("Temporary resource error; ".
	      "please try again in a few minutes", 1);
1044 1045 1046 1047
}
if (!mysql_select_db($TBDBNAME)) {
    TBERROR("Could not select DB after connecting!", 1);
}
Leigh Stoller's avatar
Leigh Stoller committed
1048 1049
$DBlinkids = array();
$DBlinkids[$TBDBNAME] = $DBlinkid;
Leigh Stoller's avatar
Leigh Stoller committed
1050

1051 1052 1053 1054 1055
#
# Connect to alternate DB.
#
function DBConnect($dbname)
{
Leigh Stoller's avatar
Leigh Stoller committed
1056 1057 1058 1059 1060
    global $DBlinkids;

    if (array_key_exists($dbname, $DBlinkids)) {
	return $DBlinkids[$dbname];
    }
Leigh Stoller's avatar
Leigh Stoller committed
1061

1062
    $linkid = mysql_connect("localhost", basename($_SERVER["SCRIPT_NAME"]), "none", 1);
1063 1064 1065 1066 1067
    if ($linkid) {
	if (!mysql_select_db($dbname, $linkid)) {
	    return null;
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
1068
    $DBlinkids[$dbname] = $linkid;
1069 1070 1071
    return $linkid;
}

Leigh Stoller's avatar
Leigh Stoller committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
#
# Record last DB error string.
#
$DBErrorString = "";

#
# This mirrors the routine in the PERL code. The point is to avoid
# writing the same thing repeatedly, get consistent error handling,
# and make sure that mail is sent to the testbed list when things go
# wrong!
#
# Argument is a string. Returns the actual query object, so it is up to
# the caller to test it. I would not for one moment view this as
# encapsulation of the DB interface. 
# 
# usage: DBQuery(char *str)
#        returns the query object result.
#
# Sets $DBErrorString is case of error; saving the original query string and
# the error string from the DB module. Use DBFatal (below) to print/email
# that string, and then exit.
#
1094
function DBQuery($query, $linkid = NULL)
Leigh Stoller's avatar
Leigh Stoller committed
1095 1096 1097
{
    global	$TBDBNAME;
    global	$DBErrorString;
1098
    global      $DBlinkid;
1099 1100

    $linkid = is_null($linkid) ? $DBlinkid : $linkid;
Leigh Stoller's avatar
Leigh Stoller committed
1101
    
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    # Support for SQL-injection vulnerability checking.  Labeled probe strings
    # should be caught in page input argument checking before they get here.
    $lbl = strpos($query, "**{");
    if ( $lbl !== FALSE ) {
	$end = strpos($query, "}**") + 3;
	# Look for a preceeding single quote, and see if it's backslashed.
	if ( substr($query, $lbl-1, 1) == "'" ) {
	    $lbl--;
	    if ( substr($query, $lbl-1, 1) == '\\' ) $lbl--;
	}
	USERERROR("Probe label: " . substr($query, $lbl, $end-$lbl), 1);
    }

1115
    $result = mysql_query($query, $linkid);
Leigh Stoller's avatar
Leigh Stoller committed
1116 1117 1118 1119

    if (! $result) {
	$DBErrorString =
	    "  Query: $query\n".
1120
	    "  Error: " . mysql_error($linkid);
Leigh Stoller's avatar
Leigh Stoller committed
1121 1122 1123 1124 1125 1126 1127
    }
    return $result;
}

#
# Same as above, but die on error. 
# 
1128
function DBQueryFatal($query, $linkid = NULL)
Leigh Stoller's avatar
Leigh Stoller committed
1129
{
1130
    $result = DBQuery($query, $linkid);
Leigh Stoller's avatar
Leigh Stoller committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

    if (! $result) {
	DBFatal("DB Query failed");
    }
    return $result;
}

#
# Same as above, but just send email on error. This info is useful
# to the TB system, but the caller has to retain control.
# 
1142
function DBQueryWarn($query, $linkid = NULL)
Leigh Stoller's avatar
Leigh Stoller committed
1143
{
1144
    $result = DBQuery($query, $linkid);
Leigh Stoller's avatar
Leigh Stoller committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

    if (! $result) {
	DBWarn("DB Query failed");
    }
    return $result;
}

#
# Warn and send email after a failed DB query. First argument is the error
# message to send. The contents of $DBErrorString is also sent. We do not
# print this stuff back to the user since we might leak stuff out that we
# should not.
# 
# usage: DBWarn(char *message)
#
function DBWarn($message)
{
1162
    global	$DBErrorString;
Leigh Stoller's avatar
Leigh Stoller committed
1163
    
1164
    $text = "$message - In " . $_SERVER["PHP_SELF"] . "\n" .
Leigh Stoller's avatar
Leigh Stoller committed
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
  	    "$DBErrorString\n";

    TBERROR($text, 0);
}

#
# Same as above, but die after the warning.
# 
# usage: DBFatal(char *message);
#
function DBFatal($message)
{
1177
    global	$DBErrorString;
Leigh Stoller's avatar
Leigh Stoller committed
1178

1179
    $text = "$message - In " . $_SERVER["PHP_SELF"] . "\n" .
1180
  	    "$DBErrorString\n";
Leigh Stoller's avatar
Leigh Stoller committed
1181

1182
    TBERROR($text, 1);
Leigh Stoller's avatar
Leigh Stoller committed
1183
}
1184 1185 1186 1187 1188

#
# Return the number of affected rows, for the last query. Why is this
# not stored in the query result?
# 
1189
function DBAffectedRows($linkid = NULL)
1190 1191 1192
{
    global      $DBlinkid;

1193 1194 1195
    $linkid = is_null($linkid) ? $DBlinkid : $linkid;

    return mysql_affected_rows($linkid);
1196 1197
}

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
#
# Properly escape string for insertion.
# 
function DBQuoteSpecial($stuff, $linkid = NULL)
{
    global      $DBlinkid;

    $linkid = is_null($linkid) ? $DBlinkid : $linkid;

    return mysql_real_escape_string($stuff, $linkid);
}

1210
?>