libdb.pm.in 70.3 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2
#
3
# Copyright (c) 2000-2020 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 B. Stoller's avatar
Leigh B. 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.
Kevin Atkinson's avatar
 
Kevin Atkinson committed
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
Timothy Stack's avatar
 
Timothy Stack committed
43
	 TBNodeEventStateUpdated
Chad Barb's avatar
 
Chad Barb committed
44
	 TBSetNodeAllocState TBGetNodeAllocState
45
	 TBSetNodeOpMode TBGetNodeOpMode TBSetNodeNextOpMode
46
	 TBBootWhat TBNodeStateTimeout
47
	 TBAdmin TBNodeAccessCheck 
48
	 TBExptAccessCheck NodeidToExp 
49
	 ExpState
50
	 ExpNodes ExpNodeVnames ExpNodesOldReserved
Leigh B. Stoller's avatar
Leigh B. Stoller committed
51 52 53
	 DBDateTime DefaultImageID 
	 TBSetNodeLogEntry
	 TBOSID TBOSMaxConcurrent TBOSCountInstances
54
	 TBResolveNextOSID TBOsidToPid TBOSIDRebootWaittime
55
	 TBOSLoadMaxOkay TBImageLoadMaxOkay TBImageID 
56
	 TBdbfork VnameToNodeid 
57
	 TBIsNodeRemote 
Leigh B Stoller's avatar
Leigh B Stoller committed
58
	 TBIsNodeVirtual TBControlNetIP TBPhysNodeID
59
	 TBNodeUpdateAccountsByPid TBNodeUpdateAccountsByType
60
	 TBNodeUpdateAccountsByUID
61
	 TBExptWorkDir TBExptUserDir
62 63
	 TBIPtoNodeID TBNodeBootReset TBNodeStateWait
	 TBExptSetSwapUID TBExptSetThumbNail
Leigh B. Stoller's avatar
Leigh B. Stoller committed
64
	 TBPlabNodeUsername MarkPhysNodeDown
65 66 67
	 TBExptIsElabInElab TBExptIsPlabInElab
	 TBExptPlabInElabPLC TBExptPlabInElabNodes
	 TBBatchUnLockExp TBExptIsBatchExp
68
	 TBExptFirewall TBNodeFirewall TBExptFirewallAndIface
Mike Hibler's avatar
Mike Hibler committed
69
	 TBSetExptFirewallVlan TBClearExptFirewallVlan
70
	 TBNodeConsoleTail TBExptGetSwapoutAction TBExptGetSwapState
Timothy Stack's avatar
 
Timothy Stack committed
71
	 TBNodeSubNodes
Leigh B Stoller's avatar
Leigh B Stoller committed
72
	 TBNodeAdminOSID TBNodeRecoveryOSID TBNodeNFSAdmin TBNodeDiskloadOSID
73
	 TBNodeType TBNodeTypeProcInfo TBNodeTypeBiosWaittime
74
	 TBExptPortRange
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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 B. Stoller's avatar
Leigh B. 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;
Kevin Atkinson's avatar
 
Kevin Atkinson committed
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 B. Stoller's avatar
Leigh B. Stoller committed
125

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

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

138
    return Experiment->Lookup(@_);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
139
}
140 141
# Local lookup for a Group, to avoid dragging in the module.
sub LocalGroupLookup(@)
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
151

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

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

165
    return User->LookupByUnixId(@_);
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
215

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

221
    return $experiment->AccessCheck($target_user, $access_type);
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
304
#
305
# Set cancel flag,
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
364
    if (defined($localonly) && $localonly) {
365 366
	$clause .= " and nt.isremotenode=0";
    }
Leigh B. Stoller's avatar
Leigh B. 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
			"    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";
581 582
		} elsif ($path =~ /recovery/) {
		    $action = "recovery";
583 584 585 586 587
		} else {
		    $action = "nfsboot";
		}
	    } elsif (defined($part)) {
		$action = "diskboot";
588 589 590 591 592 593 594
	    } 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;
595 596 597 598 599 600 601 602 603
	    } else {
		print("*** Warning: invalid $field info for $nodeid, ".
		      "booting to MFS\n");
	    }
	}
    } else {
	$action = "pxewait";
    }

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

612 613 614 615 616 617 618
    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")) {
619 620
	    while (my $line = <FD>) {
		if ($line =~ /^ONTIMEOUT\s+(\S+)/) {
621 622 623 624 625 626 627 628 629 630 631
		    if ($1 eq $action) {
			close(FD);
			return;
		    }
		    last;
		}
	    }
	    close(FD);
	}

	# argh...gotta use a setuid script to install a new pxelinux config!
632
	if (!system("$TB/sbin/pxelinux_makeconf -d -a $action $nodeid")) {
633 634 635 636 637 638 639 640 641 642
	    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;
643 644
}

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

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

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

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

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
#
# 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
696

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


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

714
    my $node = LocalNodeLookup($nodeid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
715

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

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

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

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

746 747 748 749 750 751 752 753 754
#
# 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) = @_;
755
    require OSImage;
756

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

764 765 766 767 768 769 770 771 772 773
#
# 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 ($)
{
774
    my ($osid) = @_;
775
    require OSImage;
776

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

#
# 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
786
#
787 788 789 790 791 792 793
# usage: TBOSCountInstances(char *osid; char *nodeid ...)
#        returns the number of nodes booting the OSID
#
sub TBOSCountInstances ($;@)
{
    my($osid,@exclude) = @_;

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

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

    return $current_count;
}

807 808 809 810 811 812
#
# 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.
#
813
# usage: TBResolveNextOSID(char *osid, char *pid, char *eid)
814 815 816
# returns: The 'real' OSID that the OSID resolves to, or undef if there is a
#          problem (ie. unknown OSID)
#
817
sub TBResolveNextOSID($;$$)
818
{
819
    my ($osid,$pid,$eid) = @_;
820
    my $experiment;
821

822
    require OSImage;
823

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

891 892 893 894 895 896
    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'");
897 898 899 900 901 902 903 904 905 906

    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()) {
907
	if ($OS && (!TBOSLoadMaxOkay($OS,$node_count,@nodes))) {
908 909 910 911 912 913 914
	    return 0;
	}
    }

    return 1;
}

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

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

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

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

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

#
# 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 =
964
	DBQueryFatal("select eventstate from nodes where node_id='$node'");
965 966 967 968 969 970 971 972 973 974 975 976 977 978

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

Timothy Stack's avatar
 
Timothy Stack committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
#
# 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;
}

1002
#
Mac Newbold's avatar
Mac Newbold committed
1003
# Check if a node has timed out in its current state. If it has, it gets
1004 1005 1006 1007 1008 1009 1010 1011 1012
# 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
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    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
1030 1031 1032 1033 1034 1035
	require event;

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

1043 1044 1045 1046 1047 1048 1049
#
# Set operational mode for a node.
#
# usage: TBSetNodeOpMode(char *node, char *mode)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
1050 1051
# DEPRECATED - stated handles these transitions now. See TBSetNodeNextOpMode
# below.
1052
#
1053 1054 1055 1056 1057 1058 1059 1060
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
    #
1061 1062 1063 1064 1065 1066
    require event;

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

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
#
# 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'");
}

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
#
# 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 =
1100
	DBQueryFatal("select op_mode from nodes where node_id='$node'");
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

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

Chad Barb's avatar
 
Chad Barb committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133