dbdefs.php3.in 21.1 KB
Newer Older
1 2
<?php
#
3
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2009 University of Utah and the Flux Group.
5 6
# All rights reserved.
#
7 8
# Database Constants
#
9 10
require("dbcheck.php3");

11
$TBDBNAME       = "@TBDBNAME@";
12
$TBOPSPID	= "emulab-ops";
13
$NODEDEAD_PID   = $TBOPSPID;
14
$NODEDEAD_EID   = "hwdown";
15
$FIRSTUSER      = "elabman";
16 17 18
$NODERELOADING_PID	= $TBOPSPID;
$NODERELOADING_EID	= "reloading";
$NODERELOADPENDING_EID	= "reloadpending";
19

20 21
# All these constants need to go at some point, replaced by data from
# the regex table. 
22 23
$TBDB_UIDLEN    = 8;
$TBDB_PIDLEN    = 12;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
24 25
$TBDB_GIDLEN	= 12;
$TBDB_UNIXGLEN	= 16;
26
$TBDB_NODEIDLEN = 10;
27 28
$TBDB_PHONELEN  = 32;
$TBDB_USRNAMELEN= 64;
29
$TBDB_EMAILLEN  = 64;
30
$TBDB_MMLENGTH  = 64;
31 32
$TBDB_ARCHIVE_TAGLEN = 64;
$TBDB_ARCHIVE_MSGLEN = 2048;
33 34 35 36 37 38 39 40 41

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

42 43
$TBDB_OSID_OSIDLEN         = 35;
$TBDB_OSID_OSNAMELEN       = 20;
44
$TBDB_OSID_VERSLEN         = 12;
45 46
$TBDB_IMAGEID_IMAGEIDLEN   = 45;
$TBDB_IMAGEID_IMAGENAMELEN = 30;
47

48 49 50
#
# User status field.
#
51 52 53 54 55
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");
56
define("TBDB_USERSTATUS_ARCHIVED",	"archived");
57

58 59 60 61 62 63 64 65
#
# Type of new account.
#
define("TBDB_NEWACCOUNT_REGULAR",	0x0);
define("TBDB_NEWACCOUNT_PROJLEADER",	0x1);
define("TBDB_NEWACCOUNT_WIKIONLY",	0x2);
define("TBDB_NEWACCOUNT_WEBONLY",	0x4);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
66 67 68 69 70 71 72 73 74 75 76
#
# 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;

77 78 79 80 81 82 83 84 85
#
# 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
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
#
# 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;
109
$TB_EXPT_UPDATE			= 4;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
110
$TB_EXPT_MIN			= $TB_EXPT_READINFO;
111
$TB_EXPT_MAX			= $TB_EXPT_UPDATE;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
112 113 114 115 116

# Projects.
$TB_PROJECT_READINFO		= 1;
$TB_PROJECT_MAKEGROUP		= 2;
$TB_PROJECT_EDITGROUP		= 3;
Chad Barb's avatar
 
Chad Barb committed
117
$TB_PROJECT_GROUPGRABUSERS      = 4;
Chad Barb's avatar
 
Chad Barb committed
118 119 120 121 122 123 124 125 126 127
$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
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
$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;
$TB_IMAGEID_DESTROY		= 4;
$TB_IMAGEID_MIN			= $TB_IMAGEID_READINFO;
$TB_IMAGEID_MAX			= $TB_IMAGEID_DESTROY;

146
# Experiment states (that matter to us).
147 148
$TB_EXPTSTATE_NEW		= "new"; 
$TB_EXPTSTATE_PRERUN		= "prerunning"; 
149
$TB_EXPTSTATE_SWAPPING		= "swapping";
150
$TB_EXPTSTATE_SWAPPED		= "swapped";
151
$TB_EXPTSTATE_ACTIVATING	= "activating";
152
$TB_EXPTSTATE_ACTIVE		= "active";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
153
$TB_EXPTSTATE_PANICED		= "paniced";
154
$TB_EXPTSTATE_QUEUED		= "queued";
155
$TB_EXPTSTATE_MODIFY_RESWAP	= "modify_reswap";
156

Leigh B. Stoller's avatar
Leigh B. Stoller committed
157 158 159 160 161
# Interfaces roles.
define("TBDB_IFACEROLE_CONTROL",	"ctrl");
define("TBDB_IFACEROLE_EXPERIMENT",	"expt");
define("TBDB_IFACEROLE_JAIL",		"jail");
define("TBDB_IFACEROLE_FAKE",		"fake");
162
define("TBDB_IFACEROLE_GW",		"gw");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
163
define("TBDB_IFACEROLE_OTHER",		"other");
164
define("TBDB_IFACEROLE_OUTER_CONTROL",  "outer_ctrl");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
165

166 167 168
# Node states that the web page cares about.
define("TBDB_NODESTATE_ISUP",		"ISUP");
define("TBDB_NODESTATE_PXEWAIT",	"PXEWAIT");
Timothy Stack's avatar
 
Timothy Stack committed
169 170
define("TBDB_NODESTATE_POWEROFF",	"POWEROFF");
define("TBDB_NODESTATE_ALWAYSUP",	"ALWAYSUP");
171

172 173 174 175 176 177
# 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);

178 179 180 181
# 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
182 183 184
$linktest_levels[2]	= "Plus Static Routing";
$linktest_levels[3]	= "Plus Loss";
$linktest_levels[4]	= "Plus Bandwidth";
185 186
define("TBDB_LINKTEST_MAX", 4);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 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
#
# 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;
}

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
#
# 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;
}

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 300 301 302 303
function TBUidNodeLastLogin($uid)
{
    $query_result =
	DBQueryFatal("select * from uidnodelastlogin where uid='$uid'");

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

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
#
# Return the last login for the users node.
# 
function TBUsersLastLogin($uid)
{
    $query_result =
	DBQueryFatal("select * from userslastlogin where uid='$uid'");

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

319 320 321 322 323 324 325
#
# 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 =
326 327
	DBQueryFatal("select n.*, date_format(n.date,'%c/%e') as shortdate, ".
		     "to_days(now())-to_days(n.date) as daysidle ".
328
	             "from nodeuidlastlogin as n ".
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
		     "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;
}

344
#
345 346 347
# 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.
348 349 350 351
#
function TBFreePCs()
{
    $query_result =
352
	DBQueryFatal("select count(a.node_id) from nodes as a ".
353 354
		     "left join reserved as b on a.node_id=b.node_id ".
		     "left join node_types as nt on a.type=nt.type ".
355 356
		     "left join nodetypeXpid_permissions as p ".
		     "  on a.type=p.type ".
357
		     "where b.node_id is null and a.role='testnode' ".
358
                     "  and a.reserved_pid is null ".
359 360 361 362 363 364 365 366 367 368
		     "  and nt.class = 'pc' and p.pid is null and ".
                     "      (a.eventstate='" . TBDB_NODESTATE_ISUP . "' or ".
                     "       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];
369 370
}

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
#
# 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];
}

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
#
# 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];
}

Chad Barb's avatar
 
Chad Barb committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
#
# 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);

470 471
	$value = $row["value"];
	$defaultvalue = $row["defaultvalue"];
Chad Barb's avatar
 
Chad Barb committed
472 473 474 475
	if (isset($value)) { return $value; }
	if (isset($defaultvalue)) { return $defaultvalue; }
    }
    
476
    TBERROR("Attempted to fetch unknown site variable '$name'!", 1);
Chad Barb's avatar
 
Chad Barb committed
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 530 531 532
#
# 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;
}

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
#
# 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'");
}

560 561 562 563 564 565
#
# Get the build and source version numbers, as for the banner.
#
function TBGetVersionInfo(&$major, &$minor, &$build)
{
    $query_result = 
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	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);
	list($a,$b) = split('\.', $row[0]);
	$a = (isset($a) && $a != "" ? $a : "x");
	$b = (isset($b) && $b != "" ? $b : "y");
	$major = $a;
	$minor = $b;
    }
    else {
	$major = "X";
	$minor = "Y";
590 591 592 593
    }
    return 1;
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
#
# 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;
}

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
#
# 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;
}

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
#
# 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"); }
690 691
    function uid_idx()       { return $this->field("uid_idx"); }
    function gid_idx()       { return $this->field("gid_idx"); }
692 693
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
694 695 696
#
# DB Interface.
#
697 698
$maxtries = 3;
$DBlinkid = 0;
699
while ($maxtries) {
700
    $DBlinkid = mysql_connect("localhost", basename($SCRIPT_NAME));
701 702 703
    if ($DBlinkid) {
	break;
    }
704 705 706 707
    $maxtries--;
    sleep(1);
}
if (! $DBlinkid) {
708 709
    USERERROR("Temporary resource error; ".
	      "please try again in a few minutes", 1);
710 711 712 713
}
if (!mysql_select_db($TBDBNAME)) {
    TBERROR("Could not select DB after connecting!", 1);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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

#
# 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.
#
function DBQuery($query)
{
    global	$TBDBNAME;
    global	$DBErrorString;
741
    global      $DBlinkid;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
742
    
743 744 745 746 747 748 749 750 751 752 753 754 755
    # 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);
    }

756
    $result = mysql_query($query, $DBlinkid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
757 758 759 760 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 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

    if (! $result) {
	$DBErrorString =
	    "  Query: $query\n".
	    "  Error: " . mysql_error();
    }
    return $result;
}

#
# Same as above, but die on error. 
# 
function DBQueryFatal($query)
{
    $result = DBQuery($query);

    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.
# 
function DBQueryWarn($query)
{
    $result = DBQuery($query);

    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)
{
    global	$PHP_SELF, $DBErrorString;
    
    $text = "$message - In $PHP_SELF\n" .
  	    "$DBErrorString\n";

    TBERROR($text, 0);
}

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

820 821
    $text = "$message - In $PHP_SELF\n" .
  	    "$DBErrorString\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
822

823
    TBERROR($text, 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
824
}
825 826 827 828 829 830 831 832 833 834 835 836

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

    return mysql_affected_rows($DBlinkid);
}

837
?>