dbdefs.php3.in 23.6 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2014 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 B. Stoller's avatar
Leigh B. 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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
90 91 92 93 94 95 96 97 98 99 100
#
# 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;

101 102 103 104 105 106 107 108 109
#
# 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");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
#
# 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;
133
$TB_EXPT_UPDATE			= 4;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
134
$TB_EXPT_MIN			= $TB_EXPT_READINFO;
135
$TB_EXPT_MAX			= $TB_EXPT_UPDATE;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
136 137 138 139 140

# Projects.
$TB_PROJECT_READINFO		= 1;
$TB_PROJECT_MAKEGROUP		= 2;
$TB_PROJECT_EDITGROUP		= 3;
141
$TB_PROJECT_GROUPGRABUSERS      = 4;
142 143 144 145 146 147 148 149 150 151
$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 B. Stoller's avatar
Leigh B. Stoller committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165
$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;
166 167
$TB_IMAGEID_EXPORT		= 4;
$TB_IMAGEID_DESTROY		= 5;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
168 169 170
$TB_IMAGEID_MIN			= $TB_IMAGEID_READINFO;
$TB_IMAGEID_MAX			= $TB_IMAGEID_DESTROY;

171 172 173 174 175 176 177 178
# Leases
$LEASE_ACCESS_READINFO		= 1;
$LEASE_ACCESS_READ		= 2;
$LEASE_ACCESS_MODIFY		= 3;
$LEASE_ACCESS_DESTROY		= 4;
$LEASE_ACCESS_MIN		= $LEASE_ACCESS_READINFO;
$LEASE_ACCESS_MAX		= $LEASE_ACCESS_DESTROY;

179
# Experiment states (that matter to us).
180 181
$TB_EXPTSTATE_NEW		= "new"; 
$TB_EXPTSTATE_PRERUN		= "prerunning"; 
182
$TB_EXPTSTATE_SWAPPING		= "swapping";
183
$TB_EXPTSTATE_SWAPPED		= "swapped";
184
$TB_EXPTSTATE_ACTIVATING	= "activating";
185
$TB_EXPTSTATE_ACTIVE		= "active";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
186
$TB_EXPTSTATE_PANICED		= "paniced";
187
$TB_EXPTSTATE_QUEUED		= "queued";
188
$TB_EXPTSTATE_MODIFY_RESWAP	= "modify_reswap";
189

Leigh B. Stoller's avatar
Leigh B. Stoller committed
190 191 192 193 194
# Interfaces roles.
define("TBDB_IFACEROLE_CONTROL",	"ctrl");
define("TBDB_IFACEROLE_EXPERIMENT",	"expt");
define("TBDB_IFACEROLE_JAIL",		"jail");
define("TBDB_IFACEROLE_FAKE",		"fake");
195
define("TBDB_IFACEROLE_GW",		"gw");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
196
define("TBDB_IFACEROLE_OTHER",		"other");
197
define("TBDB_IFACEROLE_OUTER_CONTROL",  "outer_ctrl");
198
define("TBDB_IFACEROLE_MANAGEMENT",	"mngmnt");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
199

200 201 202
# Node states that the web page cares about.
define("TBDB_NODESTATE_ISUP",		"ISUP");
define("TBDB_NODESTATE_PXEWAIT",	"PXEWAIT");
203 204
define("TBDB_NODESTATE_POWEROFF",	"POWEROFF");
define("TBDB_NODESTATE_ALWAYSUP",	"ALWAYSUP");
205

206 207 208 209 210 211
# 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);

212 213 214 215
# Lintest levels.
$linktest_levels	= array();
$linktest_levels[0]	= "Skip Linktest";
$linktest_levels[1]	= "Connectivity and Latency";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
216 217 218
$linktest_levels[2]	= "Plus Static Routing";
$linktest_levels[3]	= "Plus Loss";
$linktest_levels[4]	= "Plus Bandwidth";
219 220
define("TBDB_LINKTEST_MAX", 4);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 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
#
# 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;
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
#
# 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;
}

304
function TBUidNodeLastLogin($uid_idx)
305 306
{
    $query_result =
307
	DBQueryFatal("select * from uidnodelastlogin where uid_idx='$uid_idx'");
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

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

338 339 340
#
# Return the last login for the users node.
# 
341
function TBUsersLastLogin($uid_idx)
342 343
{
    $query_result =
344
	DBQueryFatal("select * from userslastlogin where uid_idx='$uid_idx'");
345 346 347 348 349 350 351 352

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

353 354 355 356 357 358 359
#
# 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 =
360 361
	DBQueryFatal("select n.*, date_format(n.date,'%c/%e') as shortdate, ".
		     "to_days(now())-to_days(n.date) as daysidle ".
362
	             "from nodeuidlastlogin as n ".
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
		     "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;
}

378
#
379 380 381
# 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.
382 383 384 385
#
function TBFreePCs()
{
    $query_result =
386
	DBQueryFatal("select count(a.node_id) from nodes as a ".
387 388
		     "left join reserved as b on a.node_id=b.node_id ".
		     "left join node_types as nt on a.type=nt.type ".
389 390
		     "left join nodetypeXpid_permissions as p ".
		     "  on a.type=p.type ".
391
		     "where b.node_id is null and a.role='testnode' ".
392
                     "  and a.reserved_pid is null ".
393 394
		     "  and nt.class = 'pc' and p.pid is null and ".
                     "      (a.eventstate='" . TBDB_NODESTATE_ISUP . "' or ".
395
                     "       a.eventstate='" . TBDB_NODESTATE_POWEROFF . "' or ".
396 397 398 399 400 401 402 403
                     "       a.eventstate='" . TBDB_NODESTATE_PXEWAIT . "') and".
		     "      (p.pid is null)");
    
    if (mysql_num_rows($query_result) == 0) {
	return 0;
    }
    $row = mysql_fetch_row($query_result);
    return $row[0];
404 405
}

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
#
# 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];
}

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
#
# 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];
}

459 460 461 462 463 464 465 466 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
#
# 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);

505 506
	$value = $row["value"];
	$defaultvalue = $row["defaultvalue"];
507 508 509 510
	if (isset($value)) { return $value; }
	if (isset($defaultvalue)) { return $defaultvalue; }
    }
    
511
    TBERROR("Attempted to fetch unknown site variable '$name'!", 1);
512 513
}

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 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 563 564 565 566 567
#
# 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;
}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
#
# 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'");
}

595 596 597 598 599 600
#
# Get the build and source version numbers, as for the banner.
#
function TBGetVersionInfo(&$major, &$minor, &$build)
{
    $query_result = 
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
	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
616
	list($a,$b) = preg_split('/\./', $row[0]);
617 618 619 620 621 622 623 624
	$a = (isset($a) && $a != "" ? $a : "x");
	$b = (isset($b) && $b != "" ? $b : "y");
	$major = $a;
	$minor = $b;
    }
    else {
	$major = "X";
	$minor = "Y";
625 626 627 628
    }
    return 1;
}

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
#
# 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;
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
#
# 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;
}

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

695 696 697 698 699 700 701 702 703 704 705 706 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
#
# 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"); }
741 742
    function uid_idx()       { return $this->field("uid_idx"); }
    function gid_idx()       { return $this->field("gid_idx"); }
743 744
}

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
#
# Do we have a storage pool?
#
function HaveStoragePool()
{
    global $TBOPSPID;
    
    $experiment = Experiment::LookupByPidEid($TBOPSPID, "storage-pool");
    if ($experiment) {
	return $experiment->PCCount();
    }
    return 0;
}

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
760 761 762
#
# DB Interface.
#
763 764
$maxtries = 3;
$DBlinkid = 0;
765
while ($maxtries) {
766
    $DBlinkid = mysql_connect("localhost", basename($_SERVER["SCRIPT_NAME"]));
767 768 769
    if ($DBlinkid) {
	break;
    }
770 771 772 773
    $maxtries--;
    sleep(1);
}
if (! $DBlinkid) {
774 775
    USERERROR("Temporary resource error; ".
	      "please try again in a few minutes", 1);
776 777 778 779
}
if (!mysql_select_db($TBDBNAME)) {
    TBERROR("Could not select DB after connecting!", 1);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
780 781
$DBlinkids = array();
$DBlinkids[$TBDBNAME] = $DBlinkid;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
782

783 784 785 786 787
#
# Connect to alternate DB.
#
function DBConnect($dbname)
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
788 789 790 791 792
    global $DBlinkids;

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

794
    $linkid = mysql_connect("localhost", basename($_SERVER["SCRIPT_NAME"]), "none", 1);
795 796 797 798 799
    if ($linkid) {
	if (!mysql_select_db($dbname, $linkid)) {
	    return null;
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
800
    $DBlinkids[$dbname] = $linkid;
801 802 803
    return $linkid;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
#
# 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.
#
826
function DBQuery($query, $linkid = NULL)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
827 828 829
{
    global	$TBDBNAME;
    global	$DBErrorString;
830
    global      $DBlinkid;
831 832

    $linkid = is_null($linkid) ? $DBlinkid : $linkid;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
833
    
834 835 836 837 838 839 840 841 842 843 844 845 846
    # 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);
    }

847
    $result = mysql_query($query, $linkid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
848 849 850 851

    if (! $result) {
	$DBErrorString =
	    "  Query: $query\n".
852
	    "  Error: " . mysql_error($linkid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
853 854 855 856 857 858 859
    }
    return $result;
}

#
# Same as above, but die on error. 
# 
860
function DBQueryFatal($query, $linkid = NULL)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
861
{
862
    $result = DBQuery($query, $linkid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
863 864 865 866 867 868 869 870 871 872 873

    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.
# 
874
function DBQueryWarn($query, $linkid = NULL)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
875
{
876
    $result = DBQuery($query, $linkid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893

    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)
{
894
    global	$DBErrorString;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
895
    
896
    $text = "$message - In " . $_SERVER["PHP_SELF"] . "\n" .
Leigh B. Stoller's avatar
Leigh B. Stoller committed
897 898 899 900 901 902 903 904 905 906 907 908
  	    "$DBErrorString\n";

    TBERROR($text, 0);
}

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

911
    $text = "$message - In " . $_SERVER["PHP_SELF"] . "\n" .
912
  	    "$DBErrorString\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
913

914
    TBERROR($text, 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
915
}
916 917 918 919 920

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

925 926 927
    $linkid = is_null($linkid) ? $DBlinkid : $linkid;

    return mysql_affected_rows($linkid);
928 929
}

930
?>