libdb.pm.in 62.3 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2
3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2010 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
6
# All rights reserved.
#
7
8
# 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
9
#
10
11
12
13
# 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.
#
14

15
package libdb;
16
use strict;
17
use Exporter;
18
use SelfLoader;
Mac Newbold's avatar
Mac Newbold committed
19
use vars qw(@ISA @EXPORT);
20
@ISA = qw(Exporter SelfLoader);
21

22
@EXPORT =
23
    qw ( MapNumericUID
24
	 TBSetCancelFlag TBGetCancelFlag
25
	 TBSetNodeEventState TBGetNodeEventState
Timothy Stack's avatar
   
Timothy Stack committed
26
	 TBNodeEventStateUpdated
Chad Barb's avatar
   
Chad Barb committed
27
	 TBSetNodeAllocState TBGetNodeAllocState
28
	 TBSetNodeOpMode TBGetNodeOpMode TBSetNodeNextOpMode
29
	 TBBootWhat TBNodeStateTimeout
30
	 TBAdmin TBNodeAccessCheck 
31
	 TBExptAccessCheck NodeidToExp 
32
	 ExpState
33
	 ExpNodes ExpNodeVnames ExpNodesOldReserved
Leigh B. Stoller's avatar
Leigh B. Stoller committed
34
35
36
37
	 DBDateTime DefaultImageID 
	 TBSetNodeLogEntry
	 MapNodeOSID 
	 TBOSID TBOSMaxConcurrent TBOSCountInstances
38
	 TBResolveNextOSID TBOsidToPid TBOSIDRebootWaittime
39
	 TBOSLoadMaxOkay TBImageLoadMaxOkay TBImageID 
40
	 TBdbfork VnameToNodeid 
41
	 TBIsNodeRemote 
Leigh B Stoller's avatar
Leigh B Stoller committed
42
	 TBIsNodeVirtual TBControlNetIP TBPhysNodeID
43
	 TBNodeUpdateAccountsByPid TBNodeUpdateAccountsByType
44
	 TBNodeUpdateAccountsByUID
45
	 TBExptWorkDir TBExptUserDir
46
47
	 TBIPtoNodeID TBNodeBootReset TBNodeStateWait
	 TBExptSetSwapUID TBExptSetThumbNail
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
	 TBPlabNodeUsername MarkPhysNodeDown
49
50
51
	 TBExptIsElabInElab TBExptIsPlabInElab
	 TBExptPlabInElabPLC TBExptPlabInElabNodes
	 TBBatchUnLockExp TBExptIsBatchExp
Mike Hibler's avatar
Mike Hibler committed
52
53
	 TBExptFirewall TBNodeFirewall TBExptFirewallAndPort
	 TBSetExptFirewallVlan TBClearExptFirewallVlan
54
	 TBNodeConsoleTail TBExptGetSwapoutAction TBExptGetSwapState
Timothy Stack's avatar
   
Timothy Stack committed
55
	 TBNodeSubNodes
56
	 TBNodeAdminOSID TBNodeDiskloadOSID
57
	 TBNodeType TBNodeTypeProcInfo TBNodeTypeBiosWaittime
58
	 TBExptPortRange
Leigh B. Stoller's avatar
Leigh B. Stoller committed
59
	 TBWideareaNodeID TBTipServers
60
	 TBSiteVarExists TBGetSiteVar TBSetSiteVar
61
	 TBActivityReport GatherAssignStats
62
	 TBAvailablePCs
63
         max min 
Mac Newbold's avatar
Mac Newbold committed
64
	 hash_recurse array_recurse hash_recurse2 array_recurse2
65
	 TBExptMinMaxNodes TBExptSecurityLevel TBExptIDX
Leigh B. Stoller's avatar
Leigh B. Stoller committed
66
	 TBExptSetPanicBit TBExptGetPanicBit TBExptClearPanicBit
67
	 TBSetNodeHistory
Timothy Stack's avatar
   
Timothy Stack committed
68
	 TBGetOSBootCmd
69
	 TBRobotLabExpt
70
	 TBExptContainsNodeCT
71
	 );
72

73
use emdb;
74
use emutil;
75
76
use libEmulab;
use EmulabConstants;
Kevin Atkinson's avatar
   
Kevin Atkinson committed
77
use libtblog_simple;
78
use English;
79
use File::Basename;
80
81

# This line has to come before the requires.
82
83
84
@EXPORT = (@emutil::EXPORT, @emdb::EXPORT, @EmulabConstants::EXPORT, @EXPORT);

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

86
# Configure variables
87
88
89
90
91
92
93
94
$TB	     = "@prefix@";
$TBOPS       = "@TBOPSEMAIL@";
$BOSSNODE    = "@BOSSNODE@";
$TESTMODE    = @TESTMODE@;
$TBOPSPID    = "emulab-ops";
$EXPTLOGNAME = "activity.log";
$PROJROOT    = "@PROJROOT_DIR@";

95
96
sub TBdbfork()
{
97
98
99
    require event;
    
    event::EventFork();
100
}
101
102
sub hash_recurse2($%);
sub array_recurse2($%);
103

104
1;
105
@SELFLOADER_DATA@
Leigh B. Stoller's avatar
Leigh B. Stoller committed
106

107
108
# Local lookup for a Node, to avoid dragging in the module.
sub LocalNodeLookup($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
109
{
110
    require Node;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
111

112
    return Node->Lookup($_[0]);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
113
}
114
115
# Local lookup for an Experiment, to avoid dragging in the module.
sub LocalExpLookup(@)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
116
{
117
    require Experiment;
Mac Newbold's avatar
Mac Newbold committed
118

119
    return Experiment->Lookup(@_);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
120
}
121
122
# Local lookup for a Group, to avoid dragging in the module.
sub LocalGroupLookup(@)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
123
{
124
    require Group;
125

126
127
128
129
130
131
    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
132

133
    return NodeType->Lookup(@_);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
134
}
135
136
137
138
# Local lookup for a User, to avoid dragging in the module.
sub LocalUserLookup(@)
{
    require User;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
139

140
141
142
    return User->Lookup(@_);
}
sub LocalUserLookupByUnixId(@)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
143
{
144
    require User;
Mac Newbold's avatar
Mac Newbold committed
145

146
    return User->LookupByUnixId(@_);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
147
148
}

149
150
151
#
# Auth stuff.
#
152
#
153
154
# Test admin status. Ignore argument; we only care if the current user
# has admin privs turned on.
155
#
156
# usage: TBAdmin();
157
158
#        returns 1 if an admin type.
#        returns 0 if a mere user.
Mac Newbold's avatar
Mac Newbold committed
159
#
160
161
sub TBAdmin(;$)
{
162
163
    require User;
    
164
165
166
    my $this_user = User->ThisUser();
    return 0
	if (! defined($this_user));
167

168
    return $this_user->IsAdmin();
169
170
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
171
172
173
174
175
176
#
# 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
177
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
178
179
180
sub TBExptAccessCheck($$$$)
{
    my ($uid, $pid, $eid, $access_type) = @_;
181
182

    #
183
    # Must map to an existing user to be trusted, obviously.
Mac Newbold's avatar
Mac Newbold committed
184
    #
185
    my $target_user = LocalUserLookupByUnixId($uid);
186
187
    return 0
	if (! defined($target_user));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
188

189
    # Ditto the group
190
    my $experiment = LocalExpLookup($pid, $eid);
191
192
    return 0
	if (! defined($experiment));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
193

194
    return $experiment->AccessCheck($target_user, $access_type);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
195
196
197
198
199
200
201
202
}

#
# 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
203
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
204
205
206
207
sub TBNodeAccessCheck($$@)
{
    my ($uid, $access_type) = (shift, shift);
    my @nodelist = @_;
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
215
216
    return 0
	if (! defined($target_user));
    return 1
	if ($target_user->IsAdmin());
217

218
    foreach my $nodeid (@nodelist) {
219
	my $node = LocalNodeLookup($nodeid);
220
221
	return 0
	    if (!defined($node));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
222

223
224
	return 0
	    if (!$node->AccessCheck($target_user, $access_type));
225
226
227
228
    }
    return 1;
}

229
230
231
232
233
234
#
# 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
235
#
236
237
sub ExpState($$)
{
238
    my ($pid, $eid) = @_;
239

240
    my $experiment = LocalExpLookup($pid, $eid);
241
    return 0
242
243
	if (!defined($experiment));
    return $experiment->state();
244
245
}

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#
# 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;
    }
    
265
266
267
268
269
270
271
272
    if (defined($newstate)) {
	require event;
	
	event::EventSendWarn(objtype   => TBDB_TBEVENT_EXPTSTATE,
			     objname   => "$pid/$eid",
			     eventtype => $newstate,
			     expt      => "$pid/$eid",
			     host      => $BOSSNODE);
273
274
275
276
    }
    return 1;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
277
#
278
# Set cancel flag,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
279
#
280
# usage: SetCancelFlag(char *pid, char *eid, char *flag)
281
282
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
Mac Newbold's avatar
Mac Newbold committed
283
#
284
sub TBSetCancelFlag($$$)
285
286
287
288
289
290
291
292
293
294
295
296
297
298
{
    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;
}

299
#
300
# Get cancel flag,
301
#
302
# usage: TBGetCancelFlag(char *pid, char *eid, char **flag)
303
304
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
Mac Newbold's avatar
Mac Newbold committed
305
#
306
sub TBGetCancelFlag($$$)
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
{
    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;
}

322
323
324
#
# Return a list of all the nodes in an experiment.
#
325
# usage: ExpNodes(char *pid, char *eid, [bool islocal])
326
#        returns the list if a valid pid/eid.
327
328
#	 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
329
#
330
sub ExpNodes($$;$$)
331
{
332
    my($pid, $eid, $localonly, $physonly) = @_;
333
334
    my(@row);
    my(@nodes);
335
    my $clause = "";
336

Leigh B. Stoller's avatar
Leigh B. Stoller committed
337
    if (defined($localonly) && $localonly) {
338
339
	$clause .= " and nt.isremotenode=0";
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
340
    if (defined($physonly) && $physonly) {
341
	$clause .= " and nt.isvirtnode=0";
342
    }
343

344
    my $query_result =
345
346
347
348
	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");
349
350
351
352
353
354

    if (! $query_result or
	$query_result->numrows == 0) {
	return ();
    }
    while (@row = $query_result->fetchrow_array()) {
Mac Newbold's avatar
Mac Newbold committed
355
	my $node = $row[0];
356
357
358
359

	#
	# 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
360
	#
361
	if ($node =~ /^([-\w]+)$/) {
362
	    $node = $1;
Mac Newbold's avatar
Mac Newbold committed
363

364
365
366
367
368
	    push(@nodes, $node);
	}
	else {
	    print "*** $0: WARNING: Bad node name: $node.\n";
	}
369
370
371
372
    }
    return @nodes;
}

373
374
375
376
#
# Return a hash of all the nodes in an experiment.  The hash maps pnames
# to vnames.
#
377
# usage: ExpNodeVnames(char *pid, char *eid, [bool islocal], [bool isphys])
378
#        returns the hash if a valid pid/eid.
379
380
#	 If the optional islocal is set, returns only local nodes.
#	 If the optional isphys is set, returns only physical nodes.
381
382
#        Returns 0 if an invalid pid/eid or if an error.
#
383
sub ExpNodeVnames($$;$$)
384
{
385
    my($pid, $eid, $localonly, $physonly) = @_;
386
387
388
389
    my(@row);
    my(%nodes);
    my $clause = "";

390
    if (defined($localonly)) {
391
392
	$clause = "and nt.isremotenode=0";
    }
393
394
395
    if (defined($physonly)) {
	$clause = "and nt.isvirtnode=0";
    }
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
    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;
}

428
#
Mac Newbold's avatar
Mac Newbold committed
429
# Find out what osid a node will boot next time it comes up,
430
431
# Usually (but not always) the currently running OS as well.
#
432
433
434
435
436
437
438
sub TBBootWhat($;$)
{
    my ($node, $debug) = @_;
    $debug = 0
	if (!defined($debug));

    #
439
440
441
    # WARNING!!!
    #
    # DO NOT change this function without making corresponding changes to
442
443
    # pxe/bootinfo_mysql.c.
    #
444
445
    # ALWAYS find exactly the same resulting OSID given the same inputs.
    #
446
447
448
449
450
451
452
453
454
455
456
457
    my $query_result =
	DBQueryWarn("select def_boot_osid, odef.op_mode, ".
		    "       temp_boot_osid, otemp.op_mode, ".
		    "       next_boot_osid, onext.op_mode ".
		    "from nodes as n ".
		    "left join os_info as odef  on odef.osid=def_boot_osid ".
		    "left join os_info as otemp on otemp.osid=temp_boot_osid ".
		    "left join os_info as onext on onext.osid=next_boot_osid ".
		    "where node_id='$node'");

    if (!$query_result || !$query_result->numrows) {
	print("*** Warning: No bootwhat info for $node\n");
458
459
	return 0;
    }
460
461
462
463
464
    my ($def_boot_osid, $def_boot_opmode,
	$temp_boot_osid, $temp_boot_opmode,
	$next_boot_osid, $next_boot_opmode) = $query_result->fetchrow_array();

    #
Mac Newbold's avatar
Mac Newbold committed
465
    # The priority would seem pretty clear.
466
467
    #
    return ($next_boot_osid, $next_boot_opmode)
468
	if (defined($next_boot_osid) && $next_boot_osid ne 0);
469
    return ($temp_boot_osid, $temp_boot_opmode)
470
	if (defined($temp_boot_osid) && $temp_boot_osid ne 0);
471
    return ($def_boot_osid, $def_boot_opmode)
472
	if (defined($def_boot_osid) && $def_boot_osid ne 0);
Mac Newbold's avatar
Mac Newbold committed
473

474
475
    print("*** Warning: node '$node': All boot info was null!\n");
    return undef;
476
477
}

478
#
479
# Map nodeid to its pid/eid/vname. vname is optional.
480
#
481
# usage: NodeidToExp(char *nodeid, \$pid, \$eid, \$vname)
482
483
484
#        returns 1 if the node is reserved.
#        returns 0 if the node is not reserved.
#
485
486
sub NodeidToExp ($$$;$) {
    my($nodeid, $pid, $eid, $vname) = @_;
487
488

    my $query_result =
489
490
	DBQueryWarn("select pid,eid,vname from reserved ".
		    "where node_id='$nodeid'");
491

492
493
    if (! $query_result ||
	! $query_result->num_rows) {
494
495
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
496

497
498
499
    my @row = $query_result->fetchrow_array();
    $$pid = $row[0];
    $$eid = $row[1];
500
501
502
503
504
505
506
507
    if (defined($vname)) {
	if (defined($row[2])) {
	    $$vname = $row[2];
	}
	else {
	    $$vname = undef;
	}
    }
508
509
510
    return 1;
}

511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#
# 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
529

530
531
532
533
534
535
    my @row = $query_result->fetchrow_array();
    $$nodeid = $row[0];
    return 1;
}


Leigh B. Stoller's avatar
Leigh B. Stoller committed
536
#
537
# Get the default ImageID for a particular node.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
538
#
539
540
541
# 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
542
543
#        returns 0 if there are problems.
#
544
sub DefaultImageID ($$) {
545
    my ($nodeid, $imageid) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
546

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

549
    if (! $node) {
550
	$$imageid = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
551
552
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
553

554
555
    if ($node->NodeTypeAttribute("default_imageid", $imageid) ||
	$$imageid eq "") {
556
557
558
559
	$$imageid = undef;
	return 0;
    }
    return 1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
560
561
}

562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#
# Convert user pid/name to internal imageid.
#
# usage: TBImageID(char *pid, char *imagename)
#        returns imageid if its valid.
#        returns 0 if not valid.
#
sub TBImageID ($$) {
    my($pid, $imagename) = @_;

    my $query_result =
	DBQueryFatal("select imageid from images ".
		     "where pid='$pid' and imagename='$imagename'");

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

580
581
582
583
584
585
586
587
588
589
590
    my @row = $query_result->fetchrow_array();
    return $row[0];
}

#
# Convert user pid/name to internal osid.
#
# usage: TBOSID(char *pid, char *isname)
#        returns osid if its valid.
#        returns 0 if not valid.
#
591
592
sub TBOSID($$) {
    my ($pid, $osname) = @_;
593

594
    require OSinfo;
Mac Newbold's avatar
Mac Newbold committed
595

596
597
598
599
    my $osinfo = OSinfo->Lookup($pid, $osname);
    return 0
	if (!defined($osinfo));
    return $osinfo->osid();
600
601
}

602
603
604
605
606
607
608
609
610
611
#
# 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) = @_;

612
    require OSinfo;
613

614
615
616
617
    my $osinfo = OSinfo->Lookup($osid);
    return 0
	if (!defined($osinfo));
    $$ppid = $osinfo->pid();
618
619
620
    return 1;
}

621
622
623
624
625
626
627
628
629
630
#
# 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 ($)
{
631
    my ($osid) = @_;
632

633
    require OSinfo;
Mac Newbold's avatar
Mac Newbold committed
634

635
636
637
638
    my $osinfo = OSinfo->Lookup($osid);
    return 0
	if (!defined($osinfo));
    return $osinfo->max_concurrent();
639
640
641
642
643
}

#
# 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
644
#
645
646
647
648
649
650
651
# usage: TBOSCountInstances(char *osid; char *nodeid ...)
#        returns the number of nodes booting the OSID
#
sub TBOSCountInstances ($;@)
{
    my($osid,@exclude) = @_;

652
    my $nodelist = join(" or ",map("p.node_id='$_'",@exclude));
653
654
655
656
    if (!@exclude) {
	$nodelist = "0";
    }

657
    my $query_result = DBQueryFatal("select distinct p.node_id from partitions " .
Robert Ricci's avatar
Robert Ricci committed
658
	"as p left join reserved as r on p.node_id = r.node_id " .
659
	"where osid='$osid' and !($nodelist) and r.pid != '$TBOPSPID'");
660
661
662
663
664
    my $current_count = $query_result->num_rows();

    return $current_count;
}

665
666
667
668
669
670
#
# 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.
#
671
# usage: TBResolveNextOSID(char *osid, char *pid, char *eid)
672
673
674
# returns: The 'real' OSID that the OSID resolves to, or undef if there is a
#          problem (ie. unknown OSID)
#
675
sub TBResolveNextOSID($;$$)
676
{
677
    my ($osid,$pid,$eid) = @_;
678
    my $experiment;
679

680
    require OSinfo;
681

682
    if (defined($pid) && defined($eid)) {
683
	$experiment = LocalExpLookup($pid, $eid);
684
685
	if (! defined($experiment)) {
	    warn "TBResolveNextOSID: No such experiment $pid/$eid\n";
686
687
	    return undef;
	}
688
689
690
691
692
693
694
695
696
697
    }
    my $osinfo = OSinfo->Lookup($osid);
    if (! defined($osinfo)) {
	warn "TBResolveNextOSID: No such osid $osid\n";
	return undef;
    }
    my $nextosinfo = $osinfo->ResolveNextOSID($experiment);
    return undef
	if (!defined($nextosinfo));
    return $nextosinfo->osid();
698
699
}

700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
#
# 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
748

749
750
751
752
753
754
755
756
757
758
759
760
    my $query_result = DBQueryFatal("select part1_osid, part2_osid, " .
	"part3_osid, part4_osid from images where imageid='$imageid'");

    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()) {
761
	if ($OS && (!TBOSLoadMaxOkay($OS,$node_count,@nodes))) {
762
763
764
765
766
767
768
	    return 0;
	}
    }

    return 1;
}

769
770
771
#
# Insert a Log entry for a node.
#
772
# usage: TBSetNodeLogEntry(char *node, char *uid, char *type, char *message)
773
774
775
776
777
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetNodeLogEntry($$$$)
{
778
    my ($node_id, $dbuid, $type, $message) = @_;
779

780
    my $node = LocalNodeLookup($node_id);
781
782
    return 0
	if (! defined($node));
783

784
    return ($node->InsertNodeLogEntry(LocalUserLookup($dbuid),
785
				      $type, $message) == 0 ? 1 : 0);
786
787
}

788
789
790
791
792
793
794
795
796
797
798
#
# Set event state for a node.
#
# usage: TBSetNodeEventState(char *node, char *state)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetNodeEventState($$)
{
    my ($node, $state) = @_;

799
800
801
802
    #
    # If using the event system, we send out an event for the state daemon to
    # pick up. Otherwise, we just set the state in the database ourselves
    #
803
804
805
806
807
808
    require event;
    
    return event::EventSendFatal(objtype   => TBDB_TBEVENT_NODESTATE,
				 objname   => $node,
				 eventtype => $state,
				 host      => $BOSSNODE);
809
810
811
812
813
814
815
816
817
818
819
820
821
822
}

#
# 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 =
823
	DBQueryFatal("select eventstate from nodes where node_id='$node'");
824
825
826
827
828
829
830
831
832
833
834
835
836
837

    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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
#
# 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;
}

861
#
Mac Newbold's avatar
Mac Newbold committed
862
# Check if a node has timed out in its current state. If it has, it gets
863
864
865
866
867
868
869
870
871
# 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
872

873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
    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
889
890
891
892
893
894
	require event;

	event::EventSendFatal(objtype   => TBDB_TBEVENT_CONTROL,
			      objname   => $node,
			      eventtype => TBDB_TBCONTROL_TIMEOUT,
			      host      => $BOSSNODE);
895
896
897
898
899
	return 1;
    } else {
	# We're good... return 0
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
900
}
901

902
903
904
905
906
907
908
#
# Set operational mode for a node.
#
# usage: TBSetNodeOpMode(char *node, char *mode)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
909
910
# DEPRECATED - stated handles these transitions now. See TBSetNodeNextOpMode
# below.
911
#
912
913
914
915
916
917
918
919
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
    #
920
921
922
923
924
925
    require event;

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

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
#
# 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'");
}

947
948
949
950
951
952
953
954
955
956
957
958
#
# 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 =
959
	DBQueryFatal("select op_mode from nodes where node_id='$node'");
960
961
962
963
964
965
966
967
968
969
970
971
972
973

    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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

#
# 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) = @_;