libdb.pm.in 70.3 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh Stoller's avatar
Leigh Stoller committed
2
#
Leigh Stoller's avatar
Leigh Stoller committed
3
# Copyright (c) 2000-2019 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/>.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
23
#
24 25
# This library mostly contains old stuff that should phased out in
# favor of the per-object libraries in this directory.
26
#
27 28 29 30
# XXX: The notion of "uid" is a tad confused. A unix uid is a number,
#      while in the DB a user uid is a string (equiv to unix login).
#      Needs to be cleaned up.
#
31

32
package libdb;
33
use strict;
34
use Exporter;
35
use SelfLoader;
Mac Newbold's avatar
Mac Newbold committed
36
use vars qw(@ISA @EXPORT);
37
@ISA = qw(Exporter SelfLoader);
38

39
@EXPORT =
40
    qw ( MapNumericUID
41
	 TBSetCancelFlag TBGetCancelFlag
42
	 TBSetNodeEventState TBGetNodeEventState
43
	 TBNodeEventStateUpdated
44
	 TBSetNodeAllocState TBGetNodeAllocState
45
	 TBSetNodeOpMode TBGetNodeOpMode TBSetNodeNextOpMode
46
	 TBBootWhat TBNodeStateTimeout
47
	 TBAdmin TBNodeAccessCheck 
48
	 TBExptAccessCheck NodeidToExp 
49
	 ExpState
50
	 ExpNodes ExpNodeVnames ExpNodesOldReserved
Leigh Stoller's avatar
Leigh Stoller committed
51 52 53
	 DBDateTime DefaultImageID 
	 TBSetNodeLogEntry
	 TBOSID TBOSMaxConcurrent TBOSCountInstances
54
	 TBResolveNextOSID TBOsidToPid TBOSIDRebootWaittime
55
	 TBOSLoadMaxOkay TBImageLoadMaxOkay TBImageID 
56
	 TBdbfork VnameToNodeid 
57
	 TBIsNodeRemote 
58
	 TBIsNodeVirtual TBControlNetIP TBPhysNodeID
59
	 TBNodeUpdateAccountsByPid TBNodeUpdateAccountsByType
60
	 TBNodeUpdateAccountsByUID
61
	 TBExptWorkDir TBExptUserDir
62 63
	 TBIPtoNodeID TBNodeBootReset TBNodeStateWait
	 TBExptSetSwapUID TBExptSetThumbNail
Leigh Stoller's avatar
Leigh Stoller committed
64
	 TBPlabNodeUsername MarkPhysNodeDown
65 66 67
	 TBExptIsElabInElab TBExptIsPlabInElab
	 TBExptPlabInElabPLC TBExptPlabInElabNodes
	 TBBatchUnLockExp TBExptIsBatchExp
68
	 TBExptFirewall TBNodeFirewall TBExptFirewallAndIface
69
	 TBSetExptFirewallVlan TBClearExptFirewallVlan
70
	 TBNodeConsoleTail TBExptGetSwapoutAction TBExptGetSwapState
71
	 TBNodeSubNodes
Leigh Stoller's avatar
Leigh Stoller committed
72
	 TBNodeAdminOSID TBNodeRecoveryOSID TBNodeNFSAdmin TBNodeDiskloadOSID
73
	 TBNodeType TBNodeTypeProcInfo TBNodeTypeBiosWaittime
74
	 TBExptPortRange
75
	 TBWideareaNodeID TBTipServers
76
	 TBSiteVarExists TBGetSiteVar TBSetSiteVar
77
	 TBActivityReport GatherAssignStats
78 79 80
         AddPerExperimentSwitchStack UpdatePerExperimentSwitchStack
         DeletePerExperimentSwitchStack GetPerExperimentSwitchStack
         GetPerExperimentSwitchStackName
81
	 TBAvailablePCs
82
         max min 
Mac Newbold's avatar
Mac Newbold committed
83
	 hash_recurse array_recurse hash_recurse2 array_recurse2
84
	 TBExptMinMaxNodes TBExptSecurityLevel TBExptIDX
Leigh Stoller's avatar
Leigh Stoller committed
85
	 TBExptSetPanicBit TBExptGetPanicBit TBExptClearPanicBit
86
	 TBSetNodeHistory
87
	 TBRobotLabExpt
88
	 TBExptContainsNodeCT
89
	 TBPxelinuxConfig
90
	 );
91

92
use emdb;
93
use emutil;
94 95
use libEmulab;
use EmulabConstants;
96
use libtblog_simple;
97
use English;
98
use File::Basename;
99 100

# This line has to come before the requires.
101 102 103
@EXPORT = (@emutil::EXPORT, @emdb::EXPORT, @EmulabConstants::EXPORT, @EXPORT);

use vars qw($TB $TBOPS $BOSSNODE $TESTMODE $TBOPSPID $EXPTLOGNAME $PROJROOT);
104

105
# Configure variables
106 107 108 109 110 111 112 113
$TB	     = "@prefix@";
$TBOPS       = "@TBOPSEMAIL@";
$BOSSNODE    = "@BOSSNODE@";
$TESTMODE    = @TESTMODE@;
$TBOPSPID    = "emulab-ops";
$EXPTLOGNAME = "activity.log";
$PROJROOT    = "@PROJROOT_DIR@";

114 115
sub TBdbfork()
{
116 117 118
    require event;
    
    event::EventFork();
119
}
120 121
sub hash_recurse2($%);
sub array_recurse2($%);
122

123
1;
124
@SELFLOADER_DATA@
Leigh Stoller's avatar
Leigh Stoller committed
125

126 127
# Local lookup for a Node, to avoid dragging in the module.
sub LocalNodeLookup($)
Leigh Stoller's avatar
Leigh Stoller committed
128
{
129
    require Node;
Leigh Stoller's avatar
Leigh Stoller committed
130

131
    return Node->Lookup($_[0]);
Leigh Stoller's avatar
Leigh Stoller committed
132
}
133 134
# Local lookup for an Experiment, to avoid dragging in the module.
sub LocalExpLookup(@)
Leigh Stoller's avatar
Leigh Stoller committed
135
{
136
    require Experiment;
Mac Newbold's avatar
Mac Newbold committed
137

138
    return Experiment->Lookup(@_);
Leigh Stoller's avatar
Leigh Stoller committed
139
}
140 141
# Local lookup for a Group, to avoid dragging in the module.
sub LocalGroupLookup(@)
Leigh Stoller's avatar
Leigh Stoller committed
142
{
143
    require Group;
144

145 146 147 148 149 150
    return Group->Lookup(@_);
}
# Local lookup for a NodeType, to avoid dragging in the module.
sub LocalNodeTypeLookup(@)
{
    require NodeType;
Leigh Stoller's avatar
Leigh Stoller committed
151

152
    return NodeType->Lookup(@_);
Leigh Stoller's avatar
Leigh Stoller committed
153
}
154 155 156 157
# Local lookup for a User, to avoid dragging in the module.
sub LocalUserLookup(@)
{
    require User;
Leigh Stoller's avatar
Leigh Stoller committed
158

159 160 161
    return User->Lookup(@_);
}
sub LocalUserLookupByUnixId(@)
Leigh Stoller's avatar
Leigh Stoller committed
162
{
163
    require User;
Mac Newbold's avatar
Mac Newbold committed
164

165
    return User->LookupByUnixId(@_);
Leigh Stoller's avatar
Leigh Stoller committed
166 167
}

168 169 170 171 172 173 174 175
# Local lookup for the control net interface
sub LocalInterfaceLookupControl($)
{
    require Interface;

    return Interface->LookupControl($_[0]);
}

176 177 178
#
# Auth stuff.
#
179
#
180 181
# Test admin status. Ignore argument; we only care if the current user
# has admin privs turned on.
182
#
183
# usage: TBAdmin();
184 185
#        returns 1 if an admin type.
#        returns 0 if a mere user.
Mac Newbold's avatar
Mac Newbold committed
186
#
187 188
sub TBAdmin(;$)
{
189 190
    require User;
    
191 192 193
    my $this_user = User->ThisUser();
    return 0
	if (! defined($this_user));
194

195
    return $this_user->IsAdmin();
196 197
}

Leigh Stoller's avatar
Leigh Stoller committed
198 199 200 201 202 203
#
# Experiment permission checks.
#
# Usage: TBExptAccessCheck($uid, $pid, $eid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
Mac Newbold's avatar
Mac Newbold committed
204
#
Leigh Stoller's avatar
Leigh Stoller committed
205 206 207
sub TBExptAccessCheck($$$$)
{
    my ($uid, $pid, $eid, $access_type) = @_;
208 209

    #
210
    # Must map to an existing user to be trusted, obviously.
Mac Newbold's avatar
Mac Newbold committed
211
    #
212
    my $target_user = LocalUserLookupByUnixId($uid);
213 214
    return 0
	if (! defined($target_user));
Leigh Stoller's avatar
Leigh Stoller committed
215

216
    # Ditto the group
217
    my $experiment = LocalExpLookup($pid, $eid);
218 219
    return 0
	if (! defined($experiment));
Leigh Stoller's avatar
Leigh Stoller committed
220

221
    return $experiment->AccessCheck($target_user, $access_type);
Leigh Stoller's avatar
Leigh Stoller committed
222 223 224 225 226 227 228 229
}

#
# Determine if uid can access a node or list of nodes.
#
# Usage: TBNodeAccessCheck($uid, $access_type, $node_id, ...)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
Mac Newbold's avatar
Mac Newbold committed
230
#
Leigh Stoller's avatar
Leigh Stoller committed
231 232 233 234
sub TBNodeAccessCheck($$@)
{
    my ($uid, $access_type) = (shift, shift);
    my @nodelist = @_;
235 236

    #
237
    # Must map to an existing user to be trusted, obviously.
Mac Newbold's avatar
Mac Newbold committed
238
    #
239
    my $target_user = LocalUserLookupByUnixId($uid);
240 241 242 243
    return 0
	if (! defined($target_user));
    return 1
	if ($target_user->IsAdmin());
244

245
    foreach my $nodeid (@nodelist) {
246
	my $node = LocalNodeLookup($nodeid);
247 248
	return 0
	    if (!defined($node));
Leigh Stoller's avatar
Leigh Stoller committed
249

250 251
	return 0
	    if (!$node->AccessCheck($target_user, $access_type));
252 253 254 255
    }
    return 1;
}

256 257 258 259 260 261
#
# Return Experiment state.
#
# usage: ExpState(char *pid, char *eid)
#        returns state if a valid pid/eid.
#        returns 0 if an invalid pid/eid or if an error.
Mac Newbold's avatar
Mac Newbold committed
262
#
263 264
sub ExpState($$)
{
265
    my ($pid, $eid) = @_;
266

267
    my $experiment = LocalExpLookup($pid, $eid);
268
    return 0
269 270
	if (!defined($experiment));
    return $experiment->state();
271 272
}

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
#
# Helper function for batch system.
#
sub TBBatchUnLockExp($$;$)
{
    my($pid, $eid, $newstate) = @_;
    my $BSTATE_UNLOCKED       = BATCHSTATE_UNLOCKED;
    
    my $query_result =
	DBQueryWarn("update experiments set expt_locked=NULL, ".
		    "       batchstate='$BSTATE_UNLOCKED' ".
		    (defined($newstate) ? ",state='$newstate' " : "") .
		    "where eid='$eid' and pid='$pid'");
    
    if (! $query_result ||
	$query_result->numrows == 0) {
	return 0;
    }
    
292 293 294 295 296 297 298 299
    if (defined($newstate)) {
	require event;
	
	event::EventSendWarn(objtype   => TBDB_TBEVENT_EXPTSTATE,
			     objname   => "$pid/$eid",
			     eventtype => $newstate,
			     expt      => "$pid/$eid",
			     host      => $BOSSNODE);
300 301 302 303
    }
    return 1;
}

Leigh Stoller's avatar
Leigh Stoller committed
304
#
305
# Set cancel flag,
Leigh Stoller's avatar
Leigh Stoller committed
306
#
307
# usage: SetCancelFlag(char *pid, char *eid, char *flag)
308 309
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
Mac Newbold's avatar
Mac Newbold committed
310
#
311
sub TBSetCancelFlag($$$)
312 313 314 315 316 317 318 319 320 321 322 323 324 325
{
    my($pid, $eid, $flag) = @_;

    my $query_result =
	DBQueryWarn("update experiments set canceled='$flag' ".
		    "where eid='$eid' and pid='$pid'");

    if (! $query_result ||
	$query_result->numrows == 0) {
	return 0;
    }
    return 1;
}

326
#
327
# Get cancel flag,
328
#
329
# usage: TBGetCancelFlag(char *pid, char *eid, char **flag)
330 331
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
Mac Newbold's avatar
Mac Newbold committed
332
#
333
sub TBGetCancelFlag($$$)
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
{
    my($pid, $eid, $flag) = @_;

    my $query_result =
	DBQueryWarn("select canceled from experiments ".
		    "where eid='$eid' and pid='$pid'");

    if (! $query_result ||
	$query_result->numrows == 0) {
	return 0;
    }
    ($$flag) = $query_result->fetchrow_array();
    return 1;
}

349 350 351
#
# Return a list of all the nodes in an experiment.
#
352
# usage: ExpNodes(char *pid, char *eid, [bool islocal])
353
#        returns the list if a valid pid/eid.
354 355
#	 If the optional flag is set, returns only local nodes.
#        Returns 0 if an invalid pid/eid or if an error.
Mac Newbold's avatar
Mac Newbold committed
356
#
357
sub ExpNodes($$;$$)
358
{
359
    my($pid, $eid, $localonly, $physonly) = @_;
360 361
    my(@row);
    my(@nodes);
362
    my $clause = "";
363

Leigh Stoller's avatar
Leigh Stoller committed
364
    if (defined($localonly) && $localonly) {
365 366
	$clause .= " and nt.isremotenode=0";
    }
Leigh Stoller's avatar
Leigh Stoller committed
367
    if (defined($physonly) && $physonly) {
368
	$clause .= " and nt.isvirtnode=0";
369
    }
370

371
    my $query_result =
372 373 374 375
	DBQueryWarn("select r.node_id from reserved as r ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "left join node_types as nt on nt.type=n.type ".
		    "where r.pid='$pid' and r.eid='$eid' $clause");
376 377 378 379 380 381

    if (! $query_result or
	$query_result->numrows == 0) {
	return ();
    }
    while (@row = $query_result->fetchrow_array()) {
Mac Newbold's avatar
Mac Newbold committed
382
	my $node = $row[0];
383 384 385 386

	#
	# Taint check. I do not understand this sillyness, but if I
	# taint check these node names, I avoid warnings throughout.
Mac Newbold's avatar
Mac Newbold committed
387
	#
388
	if ($node =~ /^([-\w]+)$/) {
389
	    $node = $1;
Mac Newbold's avatar
Mac Newbold committed
390

391 392 393 394 395
	    push(@nodes, $node);
	}
	else {
	    print "*** $0: WARNING: Bad node name: $node.\n";
	}
396 397 398 399
    }
    return @nodes;
}

400 401 402 403
#
# Return a hash of all the nodes in an experiment.  The hash maps pnames
# to vnames.
#
404
# usage: ExpNodeVnames(char *pid, char *eid, [bool islocal], [bool isphys])
405
#        returns the hash if a valid pid/eid.
406 407
#	 If the optional islocal is set, returns only local nodes.
#	 If the optional isphys is set, returns only physical nodes.
408 409
#        Returns 0 if an invalid pid/eid or if an error.
#
410
sub ExpNodeVnames($$;$$)
411
{
412
    my($pid, $eid, $localonly, $physonly) = @_;
413 414 415 416
    my(@row);
    my(%nodes);
    my $clause = "";

417
    if (defined($localonly)) {
418 419
	$clause = "and nt.isremotenode=0";
    }
420 421 422
    if (defined($physonly)) {
	$clause = "and nt.isvirtnode=0";
    }
423 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
    my $query_result =
	DBQueryWarn("select r.node_id,r.vname from reserved as r ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "left join node_types as nt on nt.type=n.type ".
		    "where r.pid='$pid' and r.eid='$eid' $clause");

    if (!$query_result || $query_result->numrows == 0) {
	return ();
    }
    while (@row = $query_result->fetchrow_array()) {
	my $node = $row[0];
	my $vname = $row[1];

	#
	# Taint check. I do not understand this sillyness, but if I
	# taint check these node names, I avoid warnings throughout.
	#
	if ($node =~ /^([-\w]+)$/) {
	    $node = $1;
	    if ($vname =~ /^([-\w]+)$/) {
		$vname = $1;
	    } else {
		$vname = $node;
	    }
	    $nodes{$node} = $vname;
	} else {
	    print "*** $0: WARNING: Bad node name: $node.\n";
	}
    }
    return %nodes;
}

455
#
Mac Newbold's avatar
Mac Newbold committed
456
# Find out what osid a node will boot next time it comes up,
457 458
# Usually (but not always) the currently running OS as well.
#
459
sub TBBootWhat($;$$)
460
{
461
    my ($nodeid, $debug, $wantfield) = @_;
462 463
    $debug = 0
	if (!defined($debug));
464 465
    $wantfield = 0
	if (!defined($wantfield));
466 467

    #
468 469 470
    # WARNING!!!
    #
    # DO NOT change this function without making corresponding changes to
471 472
    # pxe/bootinfo_mysql.c.
    #
473 474
    # ALWAYS find exactly the same resulting OSID given the same inputs.
    #
475
    my $query_result =
476 477 478
	DBQueryWarn("select def_boot_osid, vdef.op_mode, ".
		    "       temp_boot_osid, vtemp.op_mode, ".
		    "       next_boot_osid, vnext.op_mode ".
479 480
		    "from nodes as n ".
		    "left join os_info as odef  on odef.osid=def_boot_osid ".
481 482
		    "left join os_info_versions as vdef on ".
		    "     vdef.osid=odef.osid and vdef.vers=odef.version ".
483
		    "left join os_info as otemp on otemp.osid=temp_boot_osid ".
484 485
		    "left join os_info_versions as vtemp on ".
		    "     vtemp.osid=otemp.osid and vtemp.vers=otemp.version ".
486
		    "left join os_info as onext on onext.osid=next_boot_osid ".
487 488
		    "left join os_info_versions as vnext on ".
		    "     vnext.osid=onext.osid and vnext.vers=onext.version ".
489
		    "where node_id='$nodeid'");
490 491

    if (!$query_result || !$query_result->numrows) {
492
	print("*** Warning: No bootwhat info for $nodeid\n");
493
	return undef;
494
    }
495 496 497 498
    my ($def_boot_osid, $def_boot_opmode,
	$temp_boot_osid, $temp_boot_opmode,
	$next_boot_osid, $next_boot_opmode) = $query_result->fetchrow_array();

499 500 501 502
    my $boot_osid = 0;
    my $boot_opmode = 0;
    my $field = "";

503
    #
Mac Newbold's avatar
Mac Newbold committed
504
    # The priority would seem pretty clear.
505
    #
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    if (defined($next_boot_osid) && $next_boot_osid ne 0) {
	$boot_osid = $next_boot_osid;
	$boot_opmode = $next_boot_opmode;
	$field = "next_boot_osid";
    }
    elsif (defined($temp_boot_osid) && $temp_boot_osid ne 0) {
	$boot_osid = $temp_boot_osid;
	$boot_opmode = $temp_boot_opmode;
	$field = "temp_boot_osid";
    }
    elsif (defined($def_boot_osid) && $def_boot_osid ne 0) {
	$boot_osid = $def_boot_osid;
	$boot_opmode = $def_boot_opmode;
	$field = "def_boot_osid";
    }
521 522 523 524
    #
    # If all info is clear, the node will boot into PXEWAIT.
    # This is not an error.
    #
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    else {
	print("*** Warning: node '$nodeid': All boot info was null!\n");
    }

    # XXX hack for TBpxelinuxConfig below...
    if ($wantfield) {
	return $field;
    }

    return ($boot_osid, $boot_opmode);
}

#
# Note that this is a simplified version of what goes on in bootinfo.
# We are targetting just the Moonshot nodes where the choices are:
#
#   1. boot from THE disk
#   2. boot the frisbee MFS
#   3. boot a "general" MFS
#
# Its not yet clear how PXEWAIT will be handled. The nodes might be
# powered off in that state, or maybe we go into one of the MFSes to
# await further instructions.
#
549
sub TBPxelinuxConfig($;$)
550
{
551
    my ($node,$actionp) = @_;
552 553 554 555 556 557 558 559 560
    my $nodeid = $node->node_id();
    my $action;
    my $verbose = 1;
    my $field;

    if ($node->IsReserved() && ($field = TBBootWhat($nodeid, 0, 1))) {
	$action = "pxefail";

	my $query_result =
561 562
	    DBQueryWarn("SELECT v.path,v.mfs,p.`partition` FROM nodes AS n ".
			"  LEFT JOIN `partitions` AS p ON ".
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
			"    n.node_id=p.node_id AND ".
			"    n.${field}=p.osid ".
			"  LEFT JOIN os_info AS i ON ".
			"    n.${field}=i.osid ".
			"  LEFT JOIN os_info_versions AS v ON ".
			"    i.osid=v.osid AND i.version=v.vers ".
			"  WHERE n.node_id='$nodeid'");

	if (!$query_result || !$query_result->numrows) {
	    print("*** Warning: invalid bootinfo for $nodeid, ".
		  "booting to MFS\n");
	} else {
	    my ($path, $mfs, $part) = $query_result->fetchrow_array();

	    if (defined($path) && defined($mfs)) {
		# XXX how we identify the frisbee MFS
		if ($path =~ /frisbee/) {
		    $action = "mfsboot";
		} else {
		    $action = "nfsboot";
		}
	    } elsif (defined($part)) {
		$action = "diskboot";
586 587 588 589 590 591 592
	    } elsif (!$actionp && $field eq "def_boot_osid") {
		#
		# We are probably calling from OSSelect after changing
		# def_boot_osid but before loading the disk with that image.
		# Just leave it alone.
		#
		return;
593 594 595 596 597 598 599 600 601
	    } else {
		print("*** Warning: invalid $field info for $nodeid, ".
		      "booting to MFS\n");
	    }
	}
    } else {
	$action = "pxewait";
    }

602 603 604 605 606 607 608 609
    #
    # XXX if $actionp is set, we just want to return the action to take
    #
    if ($actionp) {
	$$actionp = $action;
	return;
    }

610 611 612 613 614 615 616
    my $cnet = LocalInterfaceLookupControl($node);
    if ($cnet && $cnet->mac() &&
	$cnet->mac() =~ /^(..)(..)(..)(..)(..)(..)$/) {
	my $nfile = "/tftpboot/pxelinux.cfg/01-$1-$2-$3-$4-$5-$6";

	# already exists, see if it is set correctly
	if (-e "$nfile" && open(FD, "<$nfile")) {
617 618
	    while (my $line = <FD>) {
		if ($line =~ /^ONTIMEOUT\s+(\S+)/) {
619 620 621 622 623 624 625 626 627 628 629
		    if ($1 eq $action) {
			close(FD);
			return;
		    }
		    last;
		}
	    }
	    close(FD);
	}

	# argh...gotta use a setuid script to install a new pxelinux config!
630
	if (!system("$TB/sbin/pxelinux_makeconf -d -a $action $nodeid >>/tmp/pxelinux_makeconf.log 2>&1")) {
631 632 633 634 635 636 637 638 639 640
	    print("$nodeid: set pxelinux boot to '$action'\n");
	    return;
	}

	print("*** Warning: $nodeid: could not update pxelinux config");
    } else {
	print("*** Warning: $nodeid: could not find MAC for cnet iface");
    }
    print (", who knows what it will boot!\n");
    return;
641 642
}

643
#
644
# Map nodeid to its pid/eid/vname. vname is optional.
645
#
646
# usage: NodeidToExp(char *nodeid, \$pid, \$eid, \$vname)
647 648 649
#        returns 1 if the node is reserved.
#        returns 0 if the node is not reserved.
#
650 651
sub NodeidToExp ($$$;$) {
    my($nodeid, $pid, $eid, $vname) = @_;
652 653

    my $query_result =
654 655
	DBQueryWarn("select pid,eid,vname from reserved ".
		    "where node_id='$nodeid'");
656

657 658
    if (! $query_result ||
	! $query_result->num_rows) {
659 660
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
661

662 663 664
    my @row = $query_result->fetchrow_array();
    $$pid = $row[0];
    $$eid = $row[1];
665 666 667 668 669 670 671 672
    if (defined($vname)) {
	if (defined($row[2])) {
	    $$vname = $row[2];
	}
	else {
	    $$vname = undef;
	}
    }
673 674 675
    return 1;
}

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
#
# Map a pid/eid/vname to its real nodename
#
# usage: VnameToNodeid(char *pid, char * eid, char *vname, \$nodeid)
#        returns 1 if the specified pid/eid/vname exists
#        returns 0 if it does not
#
sub VnameToNodeid ($$$$) {
    my($pid, $eid, $vname, $nodeid) = @_;

    my $query_result =
	DBQueryWarn("select node_id from reserved ".
		    "where pid='$pid' and eid='$eid' and vname='$vname'");

    if (! $query_result ||
	! $query_result->num_rows) {
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
694

695 696 697 698 699 700
    my @row = $query_result->fetchrow_array();
    $$nodeid = $row[0];
    return 1;
}


Leigh Stoller's avatar
Leigh Stoller committed
701
#
702
# Get the default ImageID for a particular node.
Leigh Stoller's avatar
Leigh Stoller committed
703
#
704 705 706
# usage: DefaultImageID(char *nodeid, \*imageid)
#        returns 1 if the node is valid and has a default imageid.
#                  Imageid is returned in reference param
Leigh Stoller's avatar
Leigh Stoller committed
707 708
#        returns 0 if there are problems.
#
709
sub DefaultImageID ($$) {
710
    my ($nodeid, $imageid) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
711

712
    my $node = LocalNodeLookup($nodeid);
Leigh Stoller's avatar
Leigh Stoller committed
713

714
    if (! $node) {
715
	$$imageid = undef;
Leigh Stoller's avatar
Leigh Stoller committed
716 717
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
718

719 720
    if ($node->NodeTypeAttribute("default_imageid", $imageid) ||
	$$imageid eq "") {
721 722 723 724
	$$imageid = undef;
	return 0;
    }
    return 1;
Leigh Stoller's avatar
Leigh Stoller committed
725 726
}

727 728 729 730 731 732 733
#
# Convert user pid/name to internal osid.
#
# usage: TBOSID(char *pid, char *isname)
#        returns osid if its valid.
#        returns 0 if not valid.
#
734 735
sub TBOSID($$) {
    my ($pid, $osname) = @_;
736
    require OSImage;
737

738
    my $osimage = OSImage->Lookup($pid, $osname);
739
    return 0
740 741
	if (!defined($osimage));
    return $osimage->osid();
742 743
}

744 745 746 747 748 749 750 751 752
#
# Return pid of an osid (internal name).
#
# usage: TBOsidToPid(char *osid, \$pid)
#        returns 1 if osid is valid; store pid into return arg.
#        returns 0 if osid is not valid.
#
sub TBOsidToPid ($$) {
    my($osid, $ppid) = @_;
753
    require OSImage;
754

755
    my $osimage = OSImage->Lookup($osid);
756
    return 0
757 758
	if (!defined($osimage));
    $$ppid = $osimage->pid();
759 760 761
    return 1;
}

762 763 764 765 766 767 768 769 770 771
#
# Returns the maximum number of concurrent instantiations of an image.
#
# usage: TBOSMaxConcurrent(char *osid)
#        returns >= 1 if there is a maximum number of concurrent instantiations
#        returns undef if there is no limi
#        returns 0 if not valid.
#
sub TBOSMaxConcurrent ($)
{
772
    my ($osid) = @_;
773
    require OSImage;
774

775
    my $osimage = OSImage->Lookup($osid);
776
    return 0
777 778
	if (!defined($osimage));
    return $osimage->max_concurrent();
779 780 781 782 783
}

#
# Returns the number of nodes that are supposedly booting an OS. A list of
# nodes that should be excluded from this count can be given.
Mac Newbold's avatar
Mac Newbold committed
784
#
785 786 787 788 789 790 791
# usage: TBOSCountInstances(char *osid; char *nodeid ...)
#        returns the number of nodes booting the OSID
#
sub TBOSCountInstances ($;@)
{
    my($osid,@exclude) = @_;

792
    my $nodelist = join(" or ",map("p.node_id='$_'",@exclude));
793 794 795 796
    if (!@exclude) {
	$nodelist = "0";
    }

797
    my $query_result = DBQueryFatal("select distinct p.node_id from `partitions` " .
798
	"as p left join reserved as r on p.node_id = r.node_id " .
799
	"where osid='$osid' and !($nodelist) and r.pid != '$TBOPSPID'");
800 801 802 803 804
    my $current_count = $query_result->num_rows();

    return $current_count;
}

805 806 807 808 809 810
#
# Resolve a 'generic' OSID (ie. FBSD-STD) to a real OSID
#
# Note: It's okay to call this function with a 'real' OSID, but it would be
# waseful to do so.
#
811
# usage: TBResolveNextOSID(char *osid, char *pid, char *eid)
812 813 814
# returns: The 'real' OSID that the OSID resolves to, or undef if there is a
#          problem (ie. unknown OSID)
#
815
sub TBResolveNextOSID($;$$)
816
{
817
    my ($osid,$pid,$eid) = @_;
818
    my $experiment;
819

820
    require OSImage;
821

822
    if (defined($pid) && defined($eid)) {
823
	$experiment = LocalExpLookup($pid, $eid);
824 825
	if (! defined($experiment)) {
	    warn "TBResolveNextOSID: No such experiment $pid/$eid\n";
826 827
	    return undef;
	}
828
    }
829 830
    my $osimage = OSImage->Lookup($osid);
    if (! defined($osimage)) {
831 832 833
	warn "TBResolveNextOSID: No such osid $osid\n";
	return undef;
    }
834
    my $nextosimage = $osimage->ResolveNextOSID($experiment);
835
    return undef
836 837
	if (!defined($nextosimage));
    return $nextosimage->osid();
838 839
}

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
#
# Check whether or not it's permissible, given max_concurrent restrictions, to
# load an OSID onto a number of nodes - the nodes themselves can be passed, so
# that they do no count twice (once in the count of current loads, and once in
# the count of potential loads.)
#
# usage: TBOSLoadMaxOkay(char *osid, int node_count; char *nodeid ... )
#        returns 1 if loading the given OS on the given number of nodes would
#            not go over the max_concurrent limit for the OS
#        returns 0 otherwise
#
sub TBOSLoadMaxOkay($$;@)
{
    my($osid,$node_count,@nodes) = @_;

    if (TBAdmin()) {
	return 1;
    }

    my $max_instances = TBOSMaxConcurrent($osid);
    if (!$max_instances) {
	return 1;
    }

    my $current_instances = TBOSCountInstances($osid,@nodes);

    if (($current_instances + $node_count) > $max_instances) {
	return 0;
    } else {
	return 1;
    }
}

#
#
# Check whether or not it's permissible, given max_concurrent restrictions, to
# load an image onto a number of nodes - simply checks all OSIDs on the image.
#
# usage: TBImageLoadMaxOkay(char *imageid, int node_count; char *nodeid ... )
#        returns 1 if loading the given image on the given number of nodes
#        	would not go over the max_concurrent limit for any OS im the
#        	image
#        returns 0 otherwise
#
sub TBImageLoadMaxOkay($$;@)
{
    my($imageid,$node_count,@nodes) = @_;

Mac Newbold's avatar
Mac Newbold committed
888

889 890 891 892 893 894
    my $query_result =
	DBQueryFatal("select v.part1_osid, v.part2_osid, " .
		     "  v.part3_osid, v.part4_osid from images as i ".
		     "left join image_versions as v on ".
		     "     v.imageid=i.imageid and v.version=i.version ".
		     "where i.imageid='$imageid'");
895 896 897 898 899 900 901 902 903 904

    if ($query_result->num_rows() != 1) {
	#
	# XXX - Just pretend everything is OK, something else will presumably
	# have to check the imageid anyway
	#
	return 1;
    }

    foreach my $OS ($query_result->fetchrow()) {
905
	if ($OS && (!TBOSLoadMaxOkay($OS,$node_count,@nodes))) {
906 907 908 909 910 911 912
	    return 0;
	}
    }

    return 1;
}

913 914 915
#
# Insert a Log entry for a node.
#
916
# usage: TBSetNodeLogEntry(char *node, char *uid, char *type, char *message)
917 918 919 920 921
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetNodeLogEntry($$$$)
{
922
    my ($node_id, $dbuid, $type, $message) = @_;
923

924
    my $node = LocalNodeLookup($node_id);
925 926
    return 0
	if (! defined($node));
927

928
    return ($node->InsertNodeLogEntry(LocalUserLookup($dbuid),
929
				      $type, $message) == 0 ? 1 : 0);
930 931
}

932 933 934
#
# Set event state for a node.
#
935
# usage: TBSetNodeEventState(char *node, char *state; int fatal)
936 937 938
#        Returns 1 if okay.
#        Returns 0 if failed.
#
939
sub TBSetNodeEventState($$;$)
940
{
941
    my ($node, $state, $fatal) = @_;
942

943 944
    if (!ref($node)) {
	$node = LocalNodeLookup($node);
945
    }
946 947
    my $rc = $node->SetEventState($state, $fatal);
    return (($rc == 0) ? 1 : 0);
948 949 950 951 952 953 954 955 956 957 958 959 960 961
}

#
# Get event state for a node.
#
# usage: TBGetNodeEventState(char *node, char \*state)
#        Returns 1 if okay (and sets state).
#        Returns 0 if failed.
#
sub TBGetNodeEventState($$)
{
    my ($node, $state) = @_;

    my $query_result =
962
	DBQueryFatal("select eventstate from nodes where node_id='$node'");
963 964 965 966 967 968 969 970 971 972 973 974 975 976

    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
    if (defined($row[0])) {
	$$state = $row[0];
    }
    else {
	$$state = TBDB_NODESTATE_UNKNOWN;
    }
    return 1;
}

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
#
# Check if the event state for a node was updated recently.
#
# usage: TBNodeEventStateUpdated(char *node, int tolerance)
#        Returns 1 if the state was updated.
#        Returns 0 if failed.
#
sub TBNodeEventStateUpdated($$)
{
    my ($node, $tol) = @_;

    my $query_result =
	DBQueryFatal("select UNIX_TIMESTAMP(now()) - state_timestamp < $tol ".
		     "from nodes where node_id='$node'");

    if ($query_result->numrows == 0) {
	return 0;
    }
    my ($under) = $query_result->fetchrow_array();

    return $under;
}

1000
#
Mac Newbold's avatar
Mac Newbold committed
1001
# Check if a node has timed out in its current state. If it has, it gets
1002 1003 1004 1005 1006 1007 1008 1009 1010
# stated involved to handle the situation.
#
# usage: TBNodeStateTimeout(char *node)
#        Returns 1 if it has timed out and stated was notified
#        Returns 0 if it is okay (still within time limits)
#
sub TBNodeStateTimeout($)
{
    my ($node) = @_;
Mac Newbold's avatar
Mac Newbold committed
1011

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    my $notimeout = TBDB_NO_STATE_TIMEOUT;

    my $query_result =
	DBQueryFatal("select now() - state_timestamp > timeout as over, ".
		     "timeout='$notimeout' as none ".
		     "from nodes as n left join state_timeouts as st ".
		     "on n.eventstate=st.state and n.op_mode=st.op_mode ".
		     "where node_id='$node'");

    if ($query_result->numrows == 0) {
	warn("*** TBNodeStateTimeout: Couldn't check node '$node'\n");
	return 0;
    }
    my ($over,$none) = $query_result->fetchrow_array();
    if ($over && !$none) {
	# We're overtime... send an event and return 1
1028 1029 1030 1031 1032 1033
	require event;

	event::EventSendFatal(objtype   => TBDB_TBEVENT_CONTROL,
			      objname   => $node,
			      eventtype => TBDB_TBCONTROL_TIMEOUT,
			      host      => $BOSSNODE);
1034 1035 1036 1037 1038
	return 1;
    } else {
	# We're good... return 0
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
1039
}
1040

1041 1042 1043 1044 1045 1046 1047
#
# Set operational mode for a node.
#
# usage: TBSetNodeOpMode(char *node, char *mode)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
1048 1049
# DEPRECATED - stated handles these transitions now. See TBSetNodeNextOpMode
# below.
1050
#
1051 1052 1053 1054 1055 1056 1057 1058
sub TBSetNodeOpMode($$)
{
    my ($node, $mode) = @_;

    #
    # If using the event system, we send out an event for the state daemon to
    # pick up. Otherwise, we just set the mode in the database ourselves
    #
1059 1060 1061 1062 1063 1064
    require event;

    return event::EventSendFatal(objtype   => TBDB_TBEVENT_NODEOPMODE,
				 objname   => $node,
				 eventtype => $mode,
				 host      => $BOSSNODE);
1065 1066
}

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
#
# Set the next operational mode for a node.
#
# usage: TBSetNodeNextOpMode(char *node, char *mode)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetNodeNextOpMode($$)
{
    my ($node, $mode) = @_;

    #
    # Just set it in the DB. The next time the node changes state, stated will
    # make the transition happen.
    #
    return DBQueryFatal("update nodes set next_op_mode='$mode' " .
	"where node_id='$node'");
}

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
#
# Get operational mode for a node.
#
# usage: TBGetNodeOpMode(char *node, char \*mode)
#        Returns 1 if okay (and sets state).
#        Returns 0 if failed.
#
sub TBGetNodeOpMode($$)
{
    my ($node, $mode) = @_;

    my $query_result =
1098
	DBQueryFatal("select op_mode from nodes where node_id='$node'");
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
    if (defined($row[0])) {
	$$mode = $row[0];
    }
    else {
	$$mode = TBDB_NODEOPMODE_UNKNOWN;
    }
    return 1;
}

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

#
# Set alloc state for a node.
#
# usage: TBSetNodeAllocState(char *node, char *state)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetNodeAllocState($$)
{
    my ($node, $state) = @_;
    my $now = time();
    return DBQueryFatal("update nodes set allocstate='$state', " .
			"allocstate_timestamp=$now where node_id='$node'");
}

#
# Get alloc state for a node.
#
# usage: TBGetNodeAllocState(char *node, char \*state)
#        Returns 1 if okay (and sets state).
#        Returns 0 if failed.
#
sub TBGetNodeAllocState($$)
{
    my ($node, $state) = @_;

    my $query_result =
	DBQueryFatal("select allocstate from nodes where node_id='$node'");

    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
    if (defined($row[0])) {
	$$state = $row[0];
    }
    else {
	$$state = TBDB_ALLOCSTATE_UNKNOWN;
    }
    return 1;
}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
#
# Is a node remote?
#
# usage TBIsNodeRemote(char *node)
#        Returns 1 if yes.
#        Returns 0 if no.
#
sub TBIsNodeRemote($)
{
    my ($nodeid) = @_;

    my $query_result =
1168 1169
	DBQueryFatal("select isremotenode from nodes as n ".
		     "left join node_types as t on t.type=n.type ".
1170 1171 1172 1173 1174
		     "where n.node_id='$nodeid'");

    if (! $query_result->num_rows) {
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
1175

1176
    my @row = $query_result->fetchrow_array();
1177
    return($row[0]);
1178 1179
}

1180
#
1181 1182
# Is a node virtual (or "multiplexed"). Optionally return jailflag and a
# Plab flag.
1183
#
1184
# usage TBIsNodeVirtual(char *node, int *jailed, int *plabbed)
1185 1186 1187
#        Returns 1 if yes.
#        Returns 0 if no.
#
1188
sub TBIsNodeVirtual($;$$)
1189
{
1190
    my ($nodeid, $jailed, $plabbed) = @_;
1191 1192

    my $query_result =
1193 1194
	DBQueryFatal("select isvirtnode,n.jailflag,t.isplabdslice ".
		     "from nodes as n ".
1195
		     "left join node_types as t on t.type=n.type ".
1196 1197 1198 1199 1200
		     "where n.node_id='$nodeid'");

    if (! $query_result->num_rows) {
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
1201

1202
    my @row = $query_result->fetchrow_array();
1203 1204 1205
    if (defined($jailed)) {
	$$jailed = $row[1];
    }
1206 1207 1208
    if (defined($plabbed)) {
	$$plabbed = $row[2];
    }
1209 1210 1211
    return($row[0]);
}

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
#
# Get the username used to log in to a particular vnode allocated on Plab
#
# usage TBPlabNodeUsername(char *node, char \*username)
#        Returns 1 if successful
#        Returns 0 if node is not allocated with Plab
#
sub TBPlabNodeUsername($$)
{
    my ($nodeid, $username) = @_;
Mac Newbold's avatar
Mac Newbold committed
1222

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    my $query_result =
	DBQueryFatal("select slicename from plab_slice_nodes ".
		     "where node_id='$nodeid'");

    if (! $query_result->num_rows) {
	return 0;
    }

    my @row = $query_result->fetchrow_array();
    if (defined($row[0])) {
	$$username = $row[0];
	return 1;
    }
    return 0;
}

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
#
# Mark a Phys node as down. Cannot use next reserve since the pnode is not
# going to go through the free path.
#
# usage: MarkPhysNodeDown(char *nodeid)
#
sub MarkPhysNodeDown($)
{
    my($pnode) = $_[0];
    my($pid, $eid);

    $pid = NODEDEAD_PID;
    $eid = NODEDEAD_EID;
1252 1253 1254 1255 1256 1257
    
    my $exptidx;
    if (!TBExptIDX($pid, $eid, \$exptidx)) {
	print "*** WARNING: No such experiment $pid/$eid!\n";
	return -1;
    }
1258 1259

    DBQueryFatal("update reserved set " .
1260
		 "  exptidx=$exptidx, pid='$pid',eid='$eid',rsrv_time=now() ".
1261 1262
		 "where node_id='$pnode'");

1263
    TBSetNodeHistory($pnode, TB_NODEHISTORY_OP_MOVE, $UID, $pid, $eid);
1264 1265
}

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
#
# Return the IDX for a current experiment. 
#
# usage: TBExptIDX(char $pid, char *gid, int \$idx)
#        returns 1 if okay.
#	 returns 0 if error.
#
sub TBExptIDX($$$)
{
    my($pid, $eid, $idxp) = @_;

    my $query_result =
	DBQueryWarn("select idx from experiments ".
		    "where pid='$pid' and eid='$eid'");

    if (!$query_result || !$query_result->numrows) {
	return 0;
    }
    my ($idx) = $query_result->fetchrow_array;
    $$idxp = $idx;
    return 1;
}

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
#
# Return the log directory name for an experiment. This is where
# we keep copies of the files for later inspection.
#
sub TBExptWorkDir($$)
{
    my($pid, $eid) = @_;

    return TBDB_EXPT_WORKDIR() . "/${pid}/${eid}";
}

#
# Return the user's experiment directory name. This is a path in the /proj
# tree. We keep these separate to avoid NFS issues, and users generally
# messing with things they should not (by accident or otherwise).
#
sub TBExptUserDir($$)
{
    my($pid, $eid) = @_;

Mac Newbold's avatar
Mac Newbold committed
1309
    my $query_result =
1310 1311
	DBQueryFatal("select path from experiments ".
		     "where pid='$pid' and eid='$eid'");
Mac Newbold's avatar
Mac Newbold committed
1312

1313
    my ($path) = $query_result->fetchrow_array;
Mac Newbold's avatar
Mac Newbold committed
1314

1315 1316 1317
    return $path;
}

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
#
# Return the min/max node counts for an experiment.
#
# usage: TBExptMinMaxNodes(char $pid, char *gid, int \$min, int \$max)
#        returns 1 if okay.
#	 returns 0 if error.
#
sub TBExptMinMaxNodes($$$$)
{
    my($pid, $eid, $minp, $maxp) = @_;

    my $query_result =
1330
	DBQueryWarn("select minimum_nodes,maximum_nodes from experiments ".
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
		    "where eid='$eid' and pid='$pid'");

    if (!$query_result || !$query_result->numrows) {
	return 0;
    }
    my ($min, $max) = $query_result->fetchrow_array();

    $$minp = $min
	if (defined($minp));
    $$maxp = $max
	if (defined($maxp));
    return 1;
}

#
# Return the security level for an experiment.
#
# usage: TBExptSecurityLevel(char $pid, char *gid, int \$level)
#        returns 1 if okay.
#	 returns 0 if error.
#
sub TBExptSecurityLevel($$$)
{
    my($pid, $eid, $levelp) = @_;

    my $query_result =
	DBQueryWarn("select security_level from experiments ".
		    "where eid='$eid' and pid='$pid'");

    if (!$query_result || !$query_result->numrows) {
	return 0;
    }
    my ($level) = $query_result->fetchrow_array();

    $$levelp = $level
	if (defined($levelp));
    return 1;
}

1370 1371 1372 1373 1374 1375 1376 1377 1378
#
# Check if a site-specific variable exists.
#
# usage: TBSiteVarExists($name)
#        returns 1 if variable exists;
#        returns 0 otherwise.
#
sub TBSiteVarExists($)
{
1379
    return libEmulab::SiteVarExists($_[0]);
1380 1381 1382 1383 1384 1385 1386
}

#
# Get site-specific variable.
# Get the value of the variable, or the default value if
# the value is undefined (NULL).
#
1387 1388 1389 1390
# usage: TBGetSiteVar($name, char \*rptr )
#        Without rptr: returns value if variable is defined; dies otherwise.
#        With rptr:    returns value in $rptr if variable is defined; returns
#                      zero otherwise, or any failure.
1391
#
1392
sub TBGetSiteVar($;$)
1393
{
1394
    my ($name, $rptr) = @_;
1395

1396
    return libEmulab::GetSiteVar($name, $rptr);
1397 1398
}

1399 1400 1401 1402 1403 1404 1405 1406 1407
#
# Set a sitevar. Assumed to be a real sitevar.
#
# usage: TBSetSiteVar($name, $value)
#
sub TBSetSiteVar($$)
{
    my ($name, $value) = @_;

1408
    return libEmulab::SetSiteVar($name, $value);
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
}

#
# Get pid,eid of current experiment using the robot lab. This is just
# plain silly for now.
#
sub TBRobotLabExpt($$)
{
    my ($ppid, $peid) = @_;
    
    my $query_result =
	DBQueryWarn("select r.pid,r.eid from reserved as r ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "left join node_types as nt on nt.type=n.type ".
		    "where nt.class='robot' and r.pid!='$TBOPSPID'");

    return 0
	if (!$query_result || !$query_result->numrows);

    my ($pid, $eid) = $query_result->fetchrow_array();
    $$ppid = $pid;
    $$peid = $eid;
    return 1;
}

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
#
# is a certain type/class node present?
# args: pid, eid, valid type/class
# 
sub TBExptContainsNodeCT($$$) 
{
    my ($pid,$eid,$ntc) = @_;

    # find out if this is a valid class or type...
    my $dbq = DBQueryWarn("select v.pid,v.eid,v.type from virt_nodes as v " .
			  "left join node_types as nt on v.type=nt.type " .
			  "where v.pid='$pid' and v.eid='$eid' and " .
			  "(nt.class='$ntc' or nt.type='$ntc')");

    return 0 
	if (!$dbq || !$dbq->numrows());

    return 1;
}

1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
#
# Return the list of subnodes for the given node.
#
sub TBNodeSubNodes($)
{
    my ($node) = @_;
    my (@row);
    my (@nodes);

    my $result = DBQueryFatal("SELECT n.node_id FROM nodes AS n " .
			      "LEFT JOIN node_types " .
			      "    AS nt ON n.type = nt.type " .
Leigh Stoller's avatar
Leigh Stoller committed
1466 1467
			      "WHERE n.phys_nodeid='$node' and ".
			      "      nt.issubnode!=0");
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    
    if (! $result or $result->numrows == 0) {
	return ();
    }
    while (@row = $result->fetchrow_array()) {
	my $node = $row[0];

	#
	# Taint check. I do not understand this sillyness, but if I
	# taint check these node names, I avoid warnings throughout.
	#
	if ($node =~ /^([-\w]+)$/) {
	    $node = $1;

	    push(@nodes, $node);
	}
	else {
	    print "*** $0: WARNING: Bad node name: $node.\n";
	}
    }
    return @nodes;
}

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
#
# Return a node's type and class, in a two-element array
# If the caller asked for a scalar, give them only the type
# Returns undef if the node doesn't exist
#
sub TBNodeType($)
{
    my ($node) = @_;
    my $result = DBQueryFatal("SELECT n.type, class FROM nodes AS n " .
			      "LEFT JOIN node_types " .
			      "    AS nt ON n.type = nt.type " .
			      "WHERE n.node_id='$node'");
    if ($result->num_rows() != 1) {
	return undef;
    }
    
    my ($type, $class) = $result->fetchrow();
    if (!$class) {
	return undef;
    }

    if (wantarray) {
	return ($type, $class);
    } else {
	return $type;
    }
}

1519 1520
sub TBNodeAdminOSID($)
{
1521
    my ($nodeid) = @_;
1522

1523
    my $node = LocalNodeLookup($nodeid);
1524 1525
    if ($node) {
	return $node->adminmfs_osid();
1526
    }
1527
    return 0;
1528 1529
}

Leigh Stoller's avatar
Leigh Stoller committed
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
sub TBNodeRecoveryOSID($)
{
    my ($nodeid) = @_;

    my $node = LocalNodeLookup($nodeid);
    if ($node) {
	return $node->recoverymfs_osid();
    }
    return 0;
}

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
#
# Returns 1 if node uses NFS-based admin MFS, 0 ow.
#
sub TBNodeNFSAdmin($)
{
    my ($nodeid) = @_;

    my $node = LocalNodeLookup($nodeid);
    if ($node) {
	require OSImage;

	return OSImage->Lookup($node->adminmfs_osid())->IsNfsMfs();
    }
    return 0;
}

1557 1558
sub TBNodeDiskloadOSID($)
{
1559
    my ($nodeid) = @_;
1560

1561
    my $node = LocalNodeLookup($nodeid);
1562 1563
    if ($node) {
	return $node->diskloadmfs_osid();
1564
    }
1565
    return 0;
1566 1567
}

1568 1569 1570 1571 1572 1573 1574
#
# Return a node's type CPU type and speed, in a two-element array
# Returns undef if the type can't be found
#
sub TBNodeTypeProcInfo($)
{
    my ($type) = @_;
1575

1576
    my $typeinfo = LocalNodeTypeLookup($type);
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

    return undef
	if (!defined($typeinfo));

    my ($processor, $frequency);

    return undef
	if ($typeinfo->processor(\$processor) ||
	    $typeinfo->frequency(\$frequency));

    return ($processor, $frequency);
1588 1589
}

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
#
# Return a node's type bios waittime.
#        returns >= 1 if there is a waittime
#        returns undef if there is no waittime
#        returns 0 if not valid.
#
sub TBNodeTypeBiosWaittime($)
{
    my ($type) = @_;

1600
    my $typeinfo = LocalNodeTypeLookup($type);
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

    return 0
	if (!defined($typeinfo));

    my $bios_waittime;

    return 0
	if ($typeinfo->bios_waittime(\$bios_waittime));

    return $bios_waittime;
1611 1612
}

1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
#
# Restores backed up virtual state of pid/eid from directory in /tmp.
#
sub TBExptSetSwapUID($$$)
{
    my ($pid, $eid, $uid) = @_;

    return DBQueryWarn("update experiments set expt_swap_uid='$uid' ".
		       "where pid='$pid' and eid='$eid'");
}

1624 1625
#
# Set the thumbnail for an experiment. Comes in as a binary string, which
1626 1627
# must be quoted before DB insertion. Returns 1 if the thumbnail was
# succesfully updated, 0 if it was not.
1628 1629 1630 1631 1632 1633 1634 1635
#
sub TBExptSetThumbNail($$$)
{
    my ($pid, $eid, $bindata) = @_;

    $bindata = DBQuoteSpecial($bindata);

    # Need the resource ID first.
Mac Newbold's avatar
Mac Newbold committed
1636
    my $query_result =
1637 1638 1639
	DBQueryFatal("select rsrcidx from experiments as e ".
		     "left join experiment_stats as s on e.idx=s.exptidx ".
		     "where e.pid='$pid' and e.eid='$eid'");
1640 1641 1642
    if ($query_result->num_rows() != 1) {
	return 0;
    }
1643 1644
    my ($rsrcidx) = $query_result->fetchrow_array();

Mac Newbold's avatar
Mac Newbold committed
1645
    # Now do the insert.
1646 1647 1648 1649 1650 1651
    DBQueryFatal("update experiment_resources set thumbnail=$bindata ".
		 "where idx=$rsrcidx");
    #
    # Since the above is a QueryFatal, if it failed, we won't even get here
    #
    return 1;
1652 1653
}

1654 1655 1656
#
# Get the port range for an experiment.
#
1657
# usage TBExptPortRange(char *pid, char *eid, int \*low, int \*high)
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
#	Return 1 if success.
#	Return 0 if error.
#
sub TBExptPortRange($$$$)
{
    my ($pid, $eid, $high, $low) = @_;

    my $query_result =
	DBQueryFatal("select low,high from ipport_ranges ".
		     "where pid='$pid' and eid='$eid'");

    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
    $$low  = $row[0];
    $$high = $row[1];
    return 1;
}

1678
#
1679 1680 1681
# Get elabinelab info for an experiment. An experiment with a zero elabinelab
# flag, but a non-null elabinelab_eid means its an experiment that is linked
# to an elabinelab experiment cause of its security level.
1682
#