libdb.pm.in 46.3 KB
Newer Older
1
2
#!/usr/bin/perl -w

Leigh B. Stoller's avatar
Leigh B. Stoller committed
3
4
5
6
7
8
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2002 University of Utah and the Flux Group.
# All rights reserved.
#

9
#
10
11
# A library of useful DB stuff. Mostly things that get done a lot.
# Saves typing.
12
13
14
15
16
#
# 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.
#
17

18
19
20
21
package libdb;
use Exporter;
@ISA = "Exporter";
@EXPORT =
22
23
24
    qw ( NODERELOADING_PID NODERELOADING_EID NODEDEAD_PID NODEDEAD_EID
	 NODEBOOTSTATUS_OKAY NODEBOOTSTATUS_FAILED NODEBOOTSTATUS_UNKNOWN
	 NODESTARTSTATUS_NOSTATUS PROJMEMBERTRUST_NONE PROJMEMBERTRUST_USER
Leigh B. Stoller's avatar
Leigh B. Stoller committed
25
26
27
28
29
30
31
	 PROJMEMBERTRUST_ROOT PROJMEMBERTRUST_GROUPROOT
	 PROJMEMBERTRUST_PROJROOT

	 TBTrustConvert TBMinTrust TBGrpTrust TBProjTrust

	 TB_NODEACCESS_READINFO TB_NODEACCESS_MODIFYINFO
	 TB_NODEACCESS_LOADIMAGE TB_NODEACCESS_REBOOT
32
33
	 TB_NODEACCESS_POWERCYCLE TB_NODEACCESS_MODIFYVLANS
	 TB_NODEACCESS_MIN TB_NODEACCESS_MAX
Leigh B. Stoller's avatar
Leigh B. Stoller committed
34
35
36
37

	 TB_USERINFO_READINFO TB_USERINFO_MODIFYINFO
	 TB_USERINFO_MIN TB_USERINFO_MAX

38
39
	 USERSTATUS_ACTIVE USERSTATUS_FROZEN
	 USERSTATUS_UNAPPROVED USERSTATUS_UNVERIFIED USERSTATUS_NEWUSER
40

Leigh B. Stoller's avatar
Leigh B. Stoller committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
	 TB_EXPT_READINFO TB_EXPT_MODIFY TB_EXPT_DESTROY
	 TB_EXPT_MIN TB_EXPT_MAX

	 TB_PROJECT_READINFO TB_PROJECT_MAKEGROUP
	 TB_PROJECT_EDITGROUP TB_PROJECT_DELGROUP
	 TB_PROJECT_LEADGROUP TB_PROJECT_ADDUSER
	 TB_PROJECT_DELUSER TB_PROJECT_MAKEOSID
	 TB_PROJECT_DELOSID TB_PROJECT_MAKEIMAGEID TB_PROJECT_DELIMAGEID
	 TB_PROJECT_CREATEEXPT TB_PROJECT_MIN TB_PROJECT_MAX

	 TB_OSID_READINFO TB_OSID_CREATE
	 TB_OSID_DESTROY TB_OSID_MIN TB_OSID_MAX

	 TB_IMAGEID_READINFO TB_IMAGEID_MODIFYINFO
	 TB_IMAGEID_CREATE TB_IMAGEID_DESTROY
	 TB_IMAGEID_ACCESS TB_IMAGEID_MIN TB_IMAGEID_MAX
	 
	 DBLIMIT_NSFILESIZE NODERELOADPENDING_EID
59

60
61
	 EXPTSTATE_NEW EXPTSTATE_PRERUN EXPTSTATE_SWAPPED EXPTSTATE_SWAPPING
	 EXPTSTATE_ACTIVATING EXPTSTATE_ACTIVE EXPTSTATE_TESTING
62
	 EXPTSTATE_TERMINATING EXPTSTATE_TERMINATED EXPTSTATE_UPDATING
63

64
65
	 BATCHSTATE_POSTED BATCHSTATE_RUNNING BATCHSTATE_TERMINATING
	 BATCHSTATE_ACTIVATING
Leigh B. Stoller's avatar
Leigh B. Stoller committed
66
67
	 TBBatchState TBSetBatchState

68
69
70
	 TB_NODELOGTYPE_MISC TB_NODELOGTYPES TB_DEFAULT_NODELOGTYPE 

	 TB_DEFAULT_RELOADTYPE TB_RELOADTYPE_FRISBEE TB_RELOADTYPE_NETDISK
71

72
73
	 TB_EXPTPRIORITY_LOW TB_EXPTPRIORITY_HIGH

74
	 TB_ASSIGN_TOOFEWNODES TB_OPSPID
75

76
77
78
79
80
81
82
83
84
	 TBDB_TBEVENT_NODESTATE TBDB_TBEVENT_NODEOPMODE
	 TBDB_TBEVENT_ISUP TBDB_TBEVENT_REBOOTING TBDB_TBEVENT_REBOOTED
	 TBDB_TBEVENT_NORMAL TBDB_TBEVENT_DELAYING TBDB_TBEVENT_UNKNOWNOS
	 TBDB_TBEVENT_RELOADING
	 TBDB_NODESTATE_ISUP TBDB_NODESTATE_REBOOTING TBDB_NODESTATE_REBOOTED
	 TBDB_NODESTATE_UNKNOWN
	 TBDB_NODEOPMODE_NORMAL TBDB_NODEOPMODE_DELAYING
	 TBDB_NODEOPMODE_UNKNOWNOS TBDB_NODEOPMODE_RELOADING
	 TBDB_NODEOPMODE_UNKNOWN
85
	 TBSetNodeEventState TBGetNodeEventState
86
	 TBSetNodeOpMode TBGetNodeOpMode
87

Leigh B. Stoller's avatar
Leigh B. Stoller committed
88
89
	 TBAdmin TBProjAccessCheck TBNodeAccessCheck TBOSIDAccessCheck
	 TBImageIDAccessCheck TBExptAccessCheck ExpLeader MarkNodeDown
90
	 SetNodeBootStatus OSFeatureSupported IsShelved NodeidToExp
91
	 UserDBInfo DBQuery DBQueryFatal DBQueryWarn DBWarn DBFatal
92
	 DBQuoteSpecial UNIX2DBUID ExpState SetExpState ProjLeader
Leigh B. Stoller's avatar
Leigh B. Stoller committed
93
	 ExpNodes DBDateTime DefaultImageID GroupLeader TBGroupUnixInfo
94
	 TBValidNodeLogType TBValidNodeName TBSetNodeLogEntry
95
	 TBSetSchedReload MapNodeOSID TBLockExp TBUnLockExp TBSetExpSwapTime
96
	 TBUnixGroupList TBOSID TBImageID TBdbfork VnameToNodeid TBExpLocked
97
	 TBIsNodeRemote TBExptSetLogFile TBExptClearLogFile TBExptGetLogFile
98
	 TBIsNodeVirtual TBControlNetIP TBPhysNodeID
99
	 TBExptOpenLogFile TBExptCloseLogFile TBExptCreateLogFile
100
101
102

	 TBDB_WIDEAREA_LOCALNODE
	 TBWideareaNodeID
103
	 );
104

105
# Must come after package declaration!
106
use lib '@prefix@/lib';
107
use English;
108
use File::Basename;
109
use POSIX qw(strftime);
110
111
require Mysql;

112
113
114
# Configure variables
my $TB		= "@prefix@";
my $DBNAME	= "@TBDBNAME@";
115
my $TBOPS       = "@TBOPSEMAIL@";
116
117
my $EVENTSYS    = "@EVENTSYS@";
my $BOSSNODE    = "@BOSSNODE@";
118
my $TBOPSPID	= "emulab-ops";
119

120
121
122
123
124
if ($EVENTSYS) {
    require event;
    import event;
}

125
#
126
127
# Set up for querying the database. Note that fork causes a reconnect
# to the DB in the child. 
128
129
130
131
132
133
#
my $DB;

sub TBDBConnect()
{
    my $maxtries = 5;
134
135
136
137
138
139

    #
    # Construct a 'username' from the name of this script and the user who
    # ran it. This is for accounting purposes.
    #
    my $scriptname;
140
141
142
143
144
    my $prog="";
    if ($0 =~ /^([a-z0-9\-\/\.\_]*)$/) { $prog = $1; }
    if ($prog) {
	$scriptname = basename($prog);
    }
145
146
147
148
149
150
151
152
153
    if (!$scriptname) {
	$scriptname = "unknown";
    }
    my $name = getpwuid($UID);
    if (!$name) {
	$name = "uid$UID";
    }
    my $dbuser = "$scriptname:$name";

154
155
    
    while ($maxtries && !defined($DB)) {
156
	$DB = Mysql->connect("localhost", $DBNAME, $dbuser, "none");
157
158
159
160
161
162
163
164
165
	$maxtries--;
	sleep(1);
    }
    if (!defined($DB)) {
	die("Cannot connect to DB after several attempts!\n");
    }
    $DB->{'dbh'}->{'PrintError'} = 0;    
}
TBDBConnect();
166

167
168
169
sub TBdbfork()
{
    undef($DB);
170
    TBDBConnect();
171
172
}

173
174
175
176
177
#
# Record last DB error string.
#
my $DBErrorString = "";

178
179
180
181
182
#
# Define exported "constants". Basically, these are just perl subroutines
# that look like constants cause you do not need to call a perl subroutine
# with parens. That is, FOO and FOO() are the same thing.
#
183
sub NODERELOADING_PID()		{ "emulab-ops"; }
184
sub NODERELOADING_EID()		{ "reloading"; }
185
sub NODERELOADPENDING_EID()	{ "reloadpending"; }
186
187
188
189
190
191
192
193
sub NODEDEAD_PID()		{ "emulab-ops"; }
sub NODEDEAD_EID()		{ "hwdown"; }

sub NODEBOOTSTATUS_OKAY()	{ "okay" ; }
sub NODEBOOTSTATUS_FAILED()	{ "failed"; }
sub NODEBOOTSTATUS_UNKNOWN()	{ "unknown"; }
sub NODESTARTSTATUS_NOSTATUS()	{ "none"; }

194
195
196
197
198
199
200
201
202
sub EXPTSTATE_NEW()		{ "new"; }
sub EXPTSTATE_PRERUN()		{ "prerunning"; }
sub EXPTSTATE_SWAPPED()		{ "swapped"; }
sub EXPTSTATE_SWAPPING()	{ "swapping"; }
sub EXPTSTATE_ACTIVATING()	{ "activating"; }
sub EXPTSTATE_ACTIVE()		{ "active"; }
sub EXPTSTATE_TESTING()		{ "testing"; }
sub EXPTSTATE_TERMINATING()	{ "terminating"; }
sub EXPTSTATE_TERMINATED()	{ "ended"; }
203
sub EXPTSTATE_UPDATING()	{ "updating"; }
204

Leigh B. Stoller's avatar
Leigh B. Stoller committed
205
206
207
208
209
sub BATCHSTATE_POSTED()		{ "posted"; }
sub BATCHSTATE_ACTIVATING()	{ "activating"; }
sub BATCHSTATE_RUNNING()	{ "active"; }
sub BATCHSTATE_TERMINATING()	{ "terminating"; }

210
211
sub USERSTATUS_ACTIVE()		{ "active"; }
sub USERSTATUS_FROZEN()		{ "frozen"; }
212
213
214
sub USERSTATUS_UNAPPROVED()	{ "unapproved"; }
sub USERSTATUS_UNVERIFIED()	{ "unverified"; }
sub USERSTATUS_NEWUSER()	{ "newuser"; }
215

216
217
218
219
220
221
#
# We want valid project membership to be non-zero for easy membership
# testing. Specific trust levels are encoded thusly.
# 
sub PROJMEMBERTRUST_NONE()	{ 0; }
sub PROJMEMBERTRUST_USER()	{ 1; }
222
sub PROJMEMBERTRUST_ROOT()	{ 2; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
sub PROJMEMBERTRUST_LOCALROOT()	{ 2; }
sub PROJMEMBERTRUST_GROUPROOT()	{ 3; }
sub PROJMEMBERTRUST_PROJROOT()	{ 4; }
sub PROJMEMBERTRUST_ADMIN()	{ 5; }

#
# Access types. Duplicated in the web interface. Make changes there too!
# 
# Things you can do to a node.
sub TB_NODEACCESS_READINFO()	{ 1; }
sub TB_NODEACCESS_MODIFYINFO()	{ 2; }
sub TB_NODEACCESS_LOADIMAGE()	{ 3; }
sub TB_NODEACCESS_REBOOT()	{ 4; }
sub TB_NODEACCESS_POWERCYCLE()	{ 5; }
237
sub TB_NODEACCESS_MODIFYVLANS()	{ 6; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
238
sub TB_NODEACCESS_MIN()		{ TB_NODEACCESS_READINFO; }
239
sub TB_NODEACCESS_MAX()		{ TB_NODEACCESS_MODIFYVLANS; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

# User Info (modinfo web page, etc).
sub TB_USERINFO_READINFO()	{ 1; }
sub TB_USERINFO_MODIFYINFO()	{ 2; }
sub TB_USERINFO_MIN()		{ TB_USERINFO_READINFO; }
sub TB_USERINFO_MAX()		{ TB_USERINFO_MODIFYINFO; }

# Experiments (also batch experiments).
sub TB_EXPT_READINFO()		{ 1; }
sub TB_EXPT_MODIFY()		{ 2; }
sub TB_EXPT_DESTROY()		{ 3; }
sub TB_EXPT_MIN()		{ TB_EXPT_READINFO; }
sub TB_EXPT_MAX()		{ TB_EXPT_DESTROY; }

# Projects.
sub TB_PROJECT_READINFO()	{ 1; }
sub TB_PROJECT_MAKEGROUP()	{ 2; }
sub TB_PROJECT_EDITGROUP()	{ 3; }
sub TB_PROJECT_DELGROUP()	{ 4; }
sub TB_PROJECT_LEADGROUP()	{ 5; }
sub TB_PROJECT_ADDUSER()	{ 6; }
sub TB_PROJECT_DELUSER()	{ 7; }
sub TB_PROJECT_MAKEOSID		{ 8; }
sub TB_PROJECT_DELOSID		{ 9; }
sub TB_PROJECT_MAKEIMAGEID	{ 10; }
sub TB_PROJECT_DELIMAGEID	{ 11; }
sub TB_PROJECT_CREATEEXPT	{ 12; }
sub TB_PROJECT_MIN()		{ TB_PROJECT_READINFO; }
sub TB_PROJECT_MAX()		{ TB_PROJECT_CREATEEXPT; }

# OSIDs 
sub TB_OSID_READINFO()		{ 1; }
sub TB_OSID_CREATE()		{ 2; }
sub TB_OSID_DESTROY()		{ 3; }
sub TB_OSID_MIN()		{ TB_OSID_READINFO; }
sub TB_OSID_MAX()		{ TB_OSID_DESTROY; }

# ImageIDs
sub TB_IMAGEID_READINFO()	{ 1; }
sub TB_IMAGEID_MODIFYINFO()	{ 2; }
sub TB_IMAGEID_CREATE()		{ 3; }
sub TB_IMAGEID_DESTROY()	{ 4; }
sub TB_IMAGEID_ACCESS()		{ 5; }
sub TB_IMAGEID_MIN()		{ TB_IMAGEID_READINFO; }
sub TB_IMAGEID_MAX()		{ TB_IMAGEID_ACCESS; }
285

286
# Node Log Types
287
288
289
290
291
292
293
sub TB_NODELOGTYPE_MISC		{ "misc"; }
sub TB_NODELOGTYPES()		{ ( TB_NODELOGTYPE_MISC ) ; }
sub TB_DEFAULT_NODELOGTYPE()	{ TB_NODELOGTYPE_MISC; }

# Reload Types.
sub TB_RELOADTYPE_NETDISK()	{ "netdisk"; }
sub TB_RELOADTYPE_FRISBEE()	{ "frisbee"; }
294
sub TB_DEFAULT_RELOADTYPE()	{ TB_RELOADTYPE_FRISBEE; }
295

296
297
298
299
300
301
302
# Experiment priorities.
sub TB_EXPTPRIORITY_LOW()	{ 0; }
sub TB_EXPTPRIORITY_HIGH()	{ 20; }

# Assign exit status for too few nodes.
sub TB_ASSIGN_TOOFEWNODES()	{ 2; }

303
304
305
# System PID.
sub TB_OPSPID()			{ $TBOPSPID; }

306
#
307
308
309
310
311
312
313
# Events we may want to send
#
sub TBDB_TBEVENT_NODESTATE	{ "TBNODESTATE"; }
sub TBDB_TBEVENT_NODEOPMODE	{ "TBNODEOPMODE"; }

#
# TBNODESTATE Events
314
315
#
sub TBDB_TBEVENT_ISUP()		{ "ISUP"; }
316
317
318
319
320
321
322
323
324
325
sub TBDB_TBEVENT_REBOOTED()	{ "REBOOTED"; }
sub TBDB_TBEVENT_REBOOTING()	{ "REBOOTING"; }

#
# TBNODEOPMODE Events
#
sub TBDB_TBEVENT_NORMAL()	{ "NORMAL"; }
sub TBDB_TBEVENT_DELAYING()	{ "DELAYING"; }
sub TBDB_TBEVENT_UNKNOWNOS()	{ "UNKNOWNOS"; }
sub TBDB_TBEVENT_RELOADING()	{ "RELOADING"; }
326
327
328
329

#
# For nodes, we use this set of events.
#
330
sub TBDB_NODESTATE_ISUP()	{ TBDB_TBEVENT_ISUP; }
331
332
sub TBDB_NODESTATE_REBOOTED()	{ TBDB_TBEVENT_REBOOTED; }
sub TBDB_NODESTATE_REBOOTING()	{ TBDB_TBEVENT_REBOOTING; }
333
334
sub TBDB_NODESTATE_UNKNOWN()	{ "UNKNOWN"; };

335
336
337
338
339
340
sub TBDB_NODEOPMODE_NORMAL	{ TBDB_TBEVENT_NORMAL; }
sub TBDB_NODEOPMODE_DELAYING	{ TBDB_TBEVENT_DELAYING; }
sub TBDB_NODEOPMODE_UNKNOWNOS	{ TBDB_TBEVENT_UNKNOWNOS; }
sub TBDB_NODEOPMODE_RELOADING	{ TBDB_TBEVENT_RELOADING; }
sub TBDB_NODEOPMODE_UNKNOWN	{ "UNKNOWN"; }

341
342
343
344
345
346
#
# Node name we use in the widearea_* tables to represent a generic local node.
# All local nodes are considered to have the same network characteristcs.
#
sub TBDB_WIDEAREA_LOCALNODE     { "boss"; }

347
348
349
350
351
#
# We should list all of the DB limits.
#
sub DBLIMIT_NSFILESIZE()	{ (1024 * 16); }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#
# Auth stuff.
#

#
# Convert a trust string to the above numeric values.
#
sub TBTrustConvert($)
{
    my($trust_string) = @_;
    my $trust_value = 0;

    #
    # Convert string to value. Perhaps the DB should have done it this way?
    # 
    if ($trust_string eq "none") {
	$trust_value = PROJMEMBERTRUST_NONE;
    }
    elsif ($trust_string eq "user") {
	$trust_value = PROJMEMBERTRUST_USER;
    }
    elsif ($trust_string eq "local_root") {
	$trust_value = PROJMEMBERTRUST_LOCALROOT;
    }
    elsif ($trust_string eq "group_root") {
	$trust_value = PROJMEMBERTRUST_GROUPROOT;
    }
    elsif ($trust_string eq "project_root") {
	$trust_value = PROJMEMBERTRUST_PROJROOT;
    }
    elsif ($trust_string eq "admin") {
	$trust_value = PROJMEMBERTRUST_ADMIN;
    }
    else {
	    die("*** Invalid trust value $trust_string!");
    }

    return $trust_value;
}

#
# Return true if the given trust string is >= to the minimum required.
# The trust value can be either numeric or a string; if a string its
# first converted to the numeric equiv.
#
sub TBMinTrust($$)
{
    my ($trust_value, $minimum) = @_;

    if ($minimum < PROJMEMBERTRUST_NONE ||
	$minimum > PROJMEMBERTRUST_ADMIN) {
	    die("*** Invalid minimum trust $minimum!");
    }

    #
    # Sleazy? How do you do a typeof in perl?
    #
    if (length($trust_value) != 1) {
	$trust_value = TBTrustConvert($trust_value);
    }
    
    return $trust_value >= $minimum;
}

#
# Determine the trust level for a uid/pid/gid. That is, each uid will have
# a different trust level depending on the project/group in question.
# Return that trust level as one of the numeric values above. 
# 
# usage: TBGrpTrust($dbuid, $pid, $gid)
#        returns numeric trust value if a group member.
#        returns PROJMEMBERTRUST_NONE if not a group member.
# 
sub TBGrpTrust($$$)
{
    my ($uid, $pid, $gid) = @_;

    #
    # No group, then use the default group.
    #
    if (! $gid) {
	$gid = $pid;
    }

    my $query_result =
	DBQueryFatal("select trust from group_membership ".
		     "where uid='$uid' and pid='$pid' and gid='$gid'");

    #
    # No membership is the same as no trust. True? Maybe an error instead?
    #
    if ($query_result->numrows == 0) {
	return PROJMEMBERTRUST_NONE;
    }

    my @row = $query_result->fetchrow_array();
    $trust_string = $row[0];

    return TBTrustConvert($trust_string);
}

#
# Determine the project trust level for a uid/pid. This is the trust level
# for the default group in the project.
#
# usage: TBProjTrust($dbuid, $pid)
#        returns numeric trust value if a project member.
#        returns PROJMEMBERTRUST_NONE if not a project member.
# 
sub TBProjTrust($$)
{
    my ($uid, $pid) = @_;
    
    return TBGrpTrust($uid, $pid, $pid);
}

468
#
469
470
# Test admin status. Optional argument is the UID or Name to test. If not
# provided, then test the current UID.
471
#
472
473
474
# XXX Argument is *either* a numeric UID, or a string name.
#
# usage: TBAdmin([int or char* uid]);
475
476
477
478
479
480
#        returns 1 if an admin type.
#        returns 0 if a mere user.
# 
sub TBAdmin(;$)
{
    my($uid) = @_;
481
    my($name);
482

483
484
485
486
    #
    # No one is considered an admin unless they have the magic environment
    # variable set (so that you have to be a bit more explict about wanting
    # admin privs.) Use the withadminprivs script to get this variable set.
487
488
    # Also check with HTTP_ at the front of the name, since this is required
    # to get it through suexec from the web scripts.
489
    #
490
    if (!($ENV{WITH_TB_ADMIN_PRIVS} || $ENV{HTTP_WITH_TB_ADMIN_PRIVS})) {
491
492
493
	return 0;
    }

494
495
496
497
    if (!defined($uid)) {
	$uid = $UID;
    }

498
499
500
501
502
503
504
505
506
507
    #
    # Test if numeric. Map to name if it is.
    # 
    if ($uid =~ /^[0-9]+$/) {
	($name) = getpwuid($uid)
	    or die "$uid not in passwd file\n";
    }
    else {
	$name = $uid;
    }
508
509

    my $query_result =
510
	DBQueryFatal("select admin from users where uid='$name'");
511
512
513
514
515
516
517
518
519

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

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
520
521
# Project permission checks. The group id (gid) can be undef, in which case
# the pid is used (ie: a default group check is made).
522
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
523
524
525
526
527
# Usage: TBProjAccessCheck($uid, $pid, $gid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
# 
sub TBProjAccessCheck($$$$)
528
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
529
530
    my ($uid, $pid, $gid, $access_type) = @_;
    my $mintrust;
531

Leigh B. Stoller's avatar
Leigh B. Stoller committed
532
533
534
    if ($access_type < TB_PROJECT_MIN ||
	$access_type > TB_PROJECT_MAX) {
	die("*** Invalid access type: $access_type!");
535
536
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
537
538
539
540
541
    #
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
542
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
543
544
545
546
547
548
549
    $uid = MapNumericUID($uid);

    #
    # No group, then use the default group.
    #
    if (! defined($gid)) {
	$gid = $pid;
550
551
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    if ($access_type == TB_PROJECT_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    elsif ($access_type == TB_PROJECT_CREATEEXPT) {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }
    else {
	die("*** Unexpected access type: $access_type!");
    }

    return TBMinTrust(TBGrpTrust($uid, $pid, $gid), $mintrust);
}

#
# Experiment permission checks.
#
# Usage: TBExptAccessCheck($uid, $pid, $eid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
# 
sub TBExptAccessCheck($$$$)
{
    my ($uid, $pid, $eid, $access_type) = @_;
    my $mintrust;

    if ($access_type < TB_EXPT_MIN ||
	$access_type > TB_EXPT_MAX) {
	die("*** Invalid access type: $access_type!");
580
581
582
    }

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
583
584
585
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
586
587
	return 1;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
588
    $uid = MapNumericUID($uid);
589

Leigh B. Stoller's avatar
Leigh B. Stoller committed
590
    my $query_result =
591
	DBQueryFatal("SELECT gid,expt_head_uid FROM experiments WHERE ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
592
593
594
595
596
597
		     "eid='$eid' and pid='$pid'");
    
    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
598
599
    my $gid     = $row[0];
    my $creator = $row[1];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
600

601
602
603
604
605
606
607
608
609
610
611
    #
    # An experiment may be destroyed by the experiment creator or the
    # project/group leader.
    # 
    if ($access_type == TB_EXPT_DESTROY) {
	if ($uid eq $creator) {
	    return 1;
	}
	$mintrust = PROJMEMBERTRUST_GROUPROOT;
    }
    elsif ($access_type == TB_EXPT_READINFO) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    return TBMinTrust(TBGrpTrust($uid, $pid, $gid), $mintrust);
}

#
# 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.
# 
sub TBNodeAccessCheck($$@)
{
    my ($uid, $access_type) = (shift, shift);
    my @nodelist = @_;
    my $mintrust;

    if ($access_type < TB_NODEACCESS_MIN ||
	$access_type > TB_NODEACCESS_MAX) {
	die("*** Invalid access type: $access_type!");
    }
638
639

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
    }
    $uid = MapNumericUID($uid);
 
    if ($access_type == TB_NODEACCESS_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    foreach my $node (@nodelist) {
655
	my $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
656
657
658
659
660
661
	    DBQueryFatal("select trust from reserved as n ".
			 "left join experiments as e on ".
			 "     e.pid=n.pid and e.eid=n.eid ".
			 "left join group_membership as g on ".
			 "     g.pid=e.pid and g.gid=e.gid ".
			 "where g.uid='$uid' and n.node_id='$node'");
662

663
	if ($query_result->numrows == 0) {
664
665
	    return 0;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
666
667
668
669
670
	my @row = $query_result->fetchrow_array();

	if (! TBMinTrust($row[0], $mintrust)) {
	    return 0;
	}
671
672
673
674
675
    }
    return 1;
}

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
676
# Access checks for an OSID. Tests for tbadmin.
677
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
678
679
680
# Usage: TBOSIDAccessCheck($uid, $osid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
681
# 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
682
sub TBOSIDAccessCheck($$$)
683
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
684
685
    my ($uid, $osid, $access_type) = @_;
    my $mintrust;
686

Leigh B. Stoller's avatar
Leigh B. Stoller committed
687
688
    if ($access_type < TB_OSID_MIN || $access_type > TB_OSID_MAX) {
	die("*** Invalid access type $access_type!");
689
690
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
691
692
693
694
695
696
697
    #
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
    }
    $uid = MapNumericUID($uid);
698

Leigh B. Stoller's avatar
Leigh B. Stoller committed
699
700
701
702
    #
    # No GIDs yet.
    #
    my $query_result =
703
	DBQueryFatal("SELECT pid,shared FROM os_info WHERE osid='$osid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
704
    
705
    if ($query_result->numrows == 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
706
	return 0;
707
    }
708
    my @row = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
709
    my $pid = $row[0];
710
    my $shared = $row[1];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
711
712
713
714

    #
    # Global OSIDs can be read by anyone.
    # 
715
    if ($shared) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
748
	if ($access_type == TB_OSID_READINFO) {
	    return 1;
	}
	return 0;
    }
    
    #
    # Otherwise must have proper trust in the project.
    # 
    if ($access_type == TB_OSID_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    return TBMinTrust(TBProjTrust($uid, $pid), $mintrust);
}

#
# Access checks for an ImageID
#
# Usage: TBImageIDAccessCheck($uid, $imageid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
# 
sub TBImageIDAccessCheck($$$)
{
    my ($uid, $imageid, $access_type) = @_;
    my $mintrust;

    if ($access_type < TB_IMAGEID_MIN || $access_type > TB_IMAGEID_MAX) {
	die("*** Invalid access type $access_type!");
749
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
750
751
752
753
754
755

    #
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
756
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
757
758
759
760
761
762
    $uid = MapNumericUID($uid);

    #
    # No GIDs yet.
    #
    my $query_result =
763
	DBQueryFatal("SELECT pid,shared FROM images WHERE imageid='$imageid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
764
765
766
    
    if ($query_result->numrows == 0) {
	return 0;
767
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
768
769
    my @row = $query_result->fetchrow_array();
    my $pid = $row[0];
770
    my $shared = $row[1];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
771

772
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
773
774
    # Global ImageIDs can be read by anyone.
    # 
775
    if ($shared) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
776
777
778
779
780
781
	if ($access_type == TB_IMAGEID_READINFO) {
	    return 1;
	}
	return 0;
    }

782
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
783
784
785
786
787
788
789
790
791
792
    # Otherwise must have proper trust in the project.
    # 
    if ($access_type == TB_IMAGEID_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    return TBMinTrust(TBProjTrust($uid, $pid), $mintrust);
793
794
}

795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
#
# Return Project leader. First argument pid.
#
# usage: ProjLeader(char *pid)
#        returns char *leader if a valid pid.
#        returns 0 if an invalid pid.
# 
sub ProjLeader($)
{
    my($pid) = @_;

    my $query_result =
	DBQueryFatal("select head_uid from projects where pid='$pid'");

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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
#
# Return Group leader. 
#
# usage: GroupLeader(char *pid, char *gid)
#        returns char *leader if a valid pid.
#        returns 0 if an invalid pid.
# 
sub GroupLeader($$)
{
    my($pid, $gid) = @_;

    my $query_result =
	DBQueryFatal("select leader from groups where ".
		     "pid='$pid' and gid='$gid'");

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

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

840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
#
# Return Experiment leader. First argument pid. Second argument is eid.
#
# usage: ExpLeader(char *pid, char *eid)
#        returns char *leader if a valid pid/eid.
#        returns 0 if an invalid pid/eid.
# 
sub ExpLeader($$)
{
    my($pid, $eid) = @_;

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

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

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

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
890
891
892
893
894
895
896
897
898
899
900
901
#
# 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.
# 
sub ExpState($$)
{
    my($pid, $eid) = @_;

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

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

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

#
# Set Experiment state.
#
# usage: SetExpState(char *pid, char *eid, char *state)
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub SetExpState($$$)
{
    my($pid, $eid, $state) = @_;

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

902
    if (! $query_result) {
903
904
905
906
907
	return 0;
    }
    return 1;
}

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
#
# Set the swap in/out time for an experiment.
#
# usage: TBSetExpSwapTime(char *pid, char *eid)
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub TBSetExpSwapTime($$)
{
    my($pid, $eid) = @_;

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

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

930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
#
# Lock Experiment.
#
# usage: TBLockExp(char *pid, char *eid)
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub TBLockExp($$)
{
    my($pid, $eid) = @_;

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

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

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
#
# Test if Experiment is locked
#
# usage: TBExpLocked(char *pid, char *eid)
#        returns 1 if locked.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub TBExpLocked($$)
{
    my($pid, $eid) = @_;

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

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

978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
#
# UnLock Experiment.
#
# usage: TBUnLockExp(char *pid, char *eid)
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub TBUnLockExp($$)
{
    my($pid, $eid) = @_;

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

    if (! $query_result ||
994
995
996
997
998
999
	$query_result->numrows == 0) {
	return 0;
    }
    return 1;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
#
# Return BatchMode state.
#
# usage: TBBatchState(char *pid, char *eid)
#        returns state if a valid pid/eid.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub TBBatchState($$)
{
    my($pid, $eid) = @_;

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

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

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

#
# Set BatctMode state.
#
# usage: SetBatchState(char *pid, char *eid, char *state)
#        returns 1 if okay.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub TBSetBatchState($$$)
{
    my($pid, $eid, $state) = @_;

    my $query_result =
	DBQueryWarn("update experiments set batchstate='$state',batchmode=1 ".
		    "where eid='$eid' and pid='$pid'");

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

1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
#
# Return a list of all the nodes in an experiment.
#
# usage: ExpNodes(char *pid, char *eid)
#        returns the list if a valid pid/eid.
#        returns 0 if an invalid pid/eid or if an error.
# 
sub ExpNodes($$)
{
    my($pid, $eid) = @_;
    my(@row);
    my(@nodes);

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

    if (! $query_result or
	$query_result->numrows == 0) {
	return ();
    }
    while (@row = $query_result->fetchrow_array()) {
1068
1069
1070
1071
1072
1073
	$node = $row[0];

	#
	# Taint check. I do not understand this sillyness, but if I
	# taint check these node names, I avoid warnings throughout.
	# 
1074
	if ($node =~ /^([-\w]+)$/) {
1075
1076
1077
1078
1079
1080
1081
	    $node = $1;
	    
	    push(@nodes, $node);
	}
	else {
	    print "*** $0: WARNING: Bad node name: $node.\n";
	}
1082
1083
1084
1085
    }
    return @nodes;
}

1086
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1087
1088
1089
# Mark a node as down. We schedule a next reservation for it so that it
# remains in the users experiment through the termination so that there
# are no permission errors (say, from snmpit).
1090
1091
1092
1093
1094
1095
#
# usage: MarkNodeDown(char *nodeid)
#
sub MarkNodeDown($)
{
    my($node) = $_[0];
1096
1097
    my($pid, $eid);

1098
1099
    $pid = NODEDEAD_PID;
    $eid = NODEDEAD_EID;
1100
1101

    my $query_result =
1102
	DBQueryFatal("replace into next_reserve " .
1103
1104
		     "(node_id, pid, eid) " .
		     "values ('$node', '$pid', '$eid')");    
1105
1106
1107
1108
1109
1110

    if ($query_result->num_rows < 1) {
	DBWarn("WARNING: Could not mark $node down");
    }
}

1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
#
# Set the boot status for a node.
#
# usage: SetNodeBootStatus(char *status)
#
sub SetNodeBootStatus($$)
{
    my($node, $bstat) = @_;

    DBQueryFatal("update nodes set bootstatus='$bstat' ".
		 "where node_id='$node'");
}

1124
1125
1126
1127
1128
1129
#
# Check if a particular feature is supported by an OSID. 
#
# usage: OSFeatureSupported(char *osid, char *feature)
#        returns 1 if supported, 0 if not.
#
1130
sub OSFeatureSupported($$) {
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
    my($osid, $feature) = @_;

    my $query_result =
	DBQueryFatal("select osfeatures from os_info where osid='$osid'");

    # Invalid OSID?
    if ($query_result->numrows < 1) {
	return 0;
    }
    
    foreach my $osfeature (split(',', $query_result->fetchrow_array())) {
	if ($feature eq $osfeature) {
	    return 1;
	}
    }
    return 0;
}

1149
1150
1151
1152
1153
1154
#
# Ah, what a hack! I'm tired of seeing regexs for sharks scattered around
# the code. Anyway, this checks to see if a node is a shelf, and fills
# in the shelf/node, return 1 if it is. The shelf/node arguments are
# optional, if all you want to do is see if its a shelf type thing.
#
1155
# usage: IsShelved(char *nodeid, [\$shelf], [\$node])
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
#        returns 1 if the node is a shelf type thing. Optionally fills in info.
#        returns 0 if the node is just a normal kind of node.
#
sub IsShelved ($;$$) {
    my($nodeid, $shelf, $node) = @_;

    if ($nodeid =~ /sh(\d+)-(\d+)/) {
	if (defined($shelf)) {
	    $$shelf = $1;
	}
	if (defined($node)) {
	    $$node = $2;
	}
	return 1;
    }
    return 0;
}

1174
#
1175
# Map nodeid to its pid/eid/vname. vname is optional.
1176
#
1177
# usage: NodeidToExp(char *nodeid, \$pid, \$eid, \$vname)
1178
1179
1180
#        returns 1 if the node is reserved.
#        returns 0 if the node is not reserved.
#
1181
1182
sub NodeidToExp ($$$;$) {
    my($nodeid, $pid, $eid, $vname) = @_;
1183
1184

    my $query_result =
1185
1186
	DBQueryWarn("select pid,eid,vname from reserved ".
		    "where node_id='$nodeid'");
1187

1188
1189
    if (! $query_result ||
	! $query_result->num_rows) {
1190
1191
1192
1193
1194
1195
	return 0;
    }
    
    my @row = $query_result->fetchrow_array();
    $$pid = $row[0];
    $$eid = $row[1];
1196
1197
1198
1199
1200
1201
1202
1203
    if (defined($vname)) {
	if (defined($row[2])) {
	    $$vname = $row[2];
	}
	else {
	    $$vname = undef;
	}
    }
1204
1205
1206
    return 1;
}

1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
#
# 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;
    }
    
    my @row = $query_result->fetchrow_array();
    $$nodeid = $row[0];
    return 1;
}


Leigh B. Stoller's avatar
Leigh B. Stoller committed
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
#
# Get the default ImageID for a particular node, from the node_types table.
#
# usage: DefaultImageID(char *nodeid)
#        returns imageid if the node is valid and has a default imageid.
#        returns 0 if there are problems.
#
sub DefaultImageID ($) {
    my($nodeid) = @_;

    my $query_result =
	DBQueryFatal("select imageid from node_types as t ".
		     "left join nodes as n on t.type=n.type ".
		     "where n.node_id='$nodeid'");

    if (! $query_result->num_rows) {
	return 0;
    }
    
    my @row = $query_result->fetchrow_array();
    return $row[0];
}

1255
1256
1257
1258
1259
1260
1261
1262
1263
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
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
#
# 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;
    }
    
    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.
#
sub TBOSID ($$) {
    my($pid, $osname) = @_;

    my $query_result =
	DBQueryFatal("select osid from os_info ".
		     "where pid='$pid' and osname='$osname'");

    if (! $query_result->num_rows) {
	return 0;
    }
    
    my @row = $query_result->fetchrow_array();
    return $row[0];
}

1299
#
1300
# Map login (db uid) to a user_name and user_email.
1301
#
1302
# usage: UserDBInfo(char *dbuid, \$name, \$email)
1303
1304
1305
#        returns 1 if the UID is okay.
#        returns 0 if the UID is bogus.
#
1306
1307
sub UserDBInfo ($$$) {
    my($dbuid, $username, $useremail) = @_;
1308

1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
    my $query_result =
	DBQueryFatal("select usr_name,usr_email from users ".
		     "where uid='$dbuid'");

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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
#
# Map pid,gid to its unix_gid and unix_name.
#
# usage: TBGroupUnixInfo(char $pid, char *gid, \$unix_gid, \$unix_name)
#        returns 1 if okay.
#        returns 0 if bogus.
#
sub TBGroupUnixInfo ($$$$) {
    my($pid, $gid, $unix_gid, $unix_name) = @_;

    my $query_result =
	DBQueryFatal("select unix_gid,unix_name from groups ".
		     "where pid='$pid' and gid='$gid'");

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

    my @row = $query_result->fetchrow_array();
    $$unix_gid  = $row[0];
    $$unix_name = $row[1];
    return 1;
}

1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
#
# Return a list of the additional Unix groups a user is in.
#
# usage: TBUnixGroupList(char $dbuid)
#        returns list if there is one.
#        returns () if failed or no list.
#
sub TBUnixGroupList ($) {
    my($dbuid) = @_;
    my @glist = ();

    my $query_result =
	DBQueryFatal("select gid from unixgroup_membership ".
		     "where uid='$dbuid'");

    if ($query_result->num_rows == 0) {
	return ();
    }
    
    while (@row = $query_result->fetchrow_array()) {
	push(@glist, $row[0]);
    }
    return @glist;
}

1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
#
# Map UID to DB UID (login). Does a DB check to make sure user is known to
# the DB (user obviously has a regular account), and that account will
# always match what the DB says. Redundant, I know. But consider it a
# sanity (or consistency) check. 
#
# usage: UNIX2DBUID(int uid, \$login)
#        returns 1 if the UID is okay.
#        returns 0 if the UID is bogus.
#
sub UNIX2DBUID ($$) {
    my($unix_uid, $userlogin) = @_;
1384
1385

    my $query_result =
1386
	DBQueryFatal("select uid from users where unix_uid='$unix_uid'");
1387
1388
1389
1390
1391

    if ($query_result->num_rows < 1) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1392
1393
1394
1395
1396
1397
1398
1399
1400

    my ($pwname) = getpwuid($unix_uid) or
	die("*** $unix_uid is not in the password file!");

    if ($row[0] ne $pwname) {
	warn("*** WARNING: $pwname does not match $row[0]\n");
	return 0;
    }

1401
1402
1403
1404
    $$userlogin = $row[0];
    return 1;
}

1405
1406
1407
1408
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
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
#
# Validate a node log type.
#
# usage: TBValidNodeLogType(char *type)
#        Returns 1 if the type string is valid.
#        Returns 0 if not.
#
sub TBValidNodeLogType($)
{
    my($type) = @_;

    foreach my $actype ( TB_NODELOGTYPES ) {
	if ($actype eq $type) {
	    return 1;
	}
    }

    return 0;
}

#
# Insert a Log entry for a node.
#
# usage: TBSetNodeLogEntry(char *node, char *type, char *message)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetNodeLogEntry($$$$)
{
    my($node, $dbuid, $type, $message) = @_;

    if (! TBValidNodeName($node) || !TBValidNodeLogType($type)) {
	return 0;
    }
    return DBQueryWarn("insert into nodelog ".
		       "values ".
                       "('$node', NULL, '$type', '$dbuid', $message, now())");
}

#
# Validate a node name.
#
# usage: TBValidNodeName(char *name)
#        Returns 1 if the node is valid.
#        Returns 0 if not.
#
sub TBValidNodeName($)
{
    my($node) = @_;

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

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

1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
#
# Set the scheduled_reloads for a node. Type is optional and defaults to
# testbed default load type. See above.
#
# usage: TBSetSchedReload(char *node, char *imageid, [char *reload_type])
#        Returns 1 if okay.
#        Returns 0 if failed.
#
sub TBSetSchedReload($$;$)
{
    my ($node, $imageid, $type) = @_;

    if (!defined($type)) {
	$type = TB_DEFAULT_RELOADTYPE;
    }

    if (DBQueryWarn("replace into scheduled_reloads ".
		    "(node_id, image_id, reload_type) values ".
		    "('$node', '$imageid', '$type')")) {
	return 1;
    }
    return 0;
}

1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
#
# 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) = @_;

1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
    #
    # 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
    #
    if ($EVENTSYS) {
	return EventSendFatal(objtype   => TBDB_TBEVENT_NODESTATE,
			      objname   => $node,
			      eventtype => $state,
			      host      => $BOSSNODE);
    } else {
	my $now = time();
	return DBQueryFatal("update nodes set eventstate='$state', " .
			    "state_timestamp=$now where node_id='$node'");
    }
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
}

#
# 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 =
1527
	DBQueryFatal("select eventstate from nodes where node_id='$node'");
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541

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

1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
#
# Set operational mode for a node.
#
# usage: TBSetNodeOpMode(char *node, char *mode)
#        Returns 1 if okay.
#        Returns 0 if failed.
#
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
    #
    if ($EVENTSYS) {
	return EventSendFatal(objtype   => TBDB_TBEVENT_NODEOPMODE,
			      objname   => $node,
			      eventtype => $mode,
			      host      => $BOSSNODE);
    } else {
	my $now = time();
	return DBQueryFatal("update nodes set op_mode='$mode', " .
			    "op_mode_timestamp=$now where node_id='$node'");
    }
}

#
# 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 =
	DBQueryFatal("select eventstate from nodes where node_id='$node'");

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

1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
#
# Is a node remote?
#
# usage TBIsNodeRemote(char *node)
#        Returns 1 if yes.
#        Returns 0 if no.
#
sub TBIsNodeRemote($)
{
    my ($nodeid) = @_;

    my $query_result =
1608
	DBQueryFatal("select isremotenode from node_types as t ".
1609
1610
1611
1612
1613
1614
1615
1616
		     "left join nodes as n on t.type=n.type ".
		     "where n.node_id='$nodeid'");

    if (! $query_result->num_rows) {
	return 0;
    }
    
    my @row = $query_result->fetchrow_array();
1617
    return($row[0]);
1618
1619
}

1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
#
# Is a node virtual (or "multiplexed"). 
#
# usage TBIsNodeVirtual(char *node)
#        Returns 1 if yes.
#        Returns 0 if no.
#
sub TBIsNodeVirtual($)
{
    my ($nodeid) = @_;

    my $query_result =
	DBQueryFatal("select isvirtnode from node_types as t ".
		     "left join nodes as n on t.type=n.type ".
		     "where n.node_id='$nodeid'");

    if (! $query_result->num_rows) {
	return 0;
    }
    
    my @row = $query_result->fetchrow_array();
    return($row[0]);
}

1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
#
# Set/Clear the current logfile for an experiment. The idea is to provide
# a way to look at what is going on from the web interface!
#
# usage TBExptSetLogFile(char *pid, char *eid, char *logname)
#
sub TBExptSetLogFile($$$)
{
    my ($pid, $eid, $logname) = @_;
    
    DBQueryFatal("update experiments set logfile='$logname' ".
		 "where pid='$pid' and eid='$eid'");
}

sub TBExptClearLogFile($$)
{
    my ($pid, $eid) = @_;
    
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
    DBQueryFatal("update experiments set logfile=NULL,logfile_open=0 ".
		 "where pid='$pid' and eid='$eid'");
}

#
# Flag the logfile as either open or closed. This allows the spew code
# to determine when the log is no longer being appended to. Is there a
# system oriented way to do this?
# 
# usage TBExptOpenLogFile(char *pid, char *eid)
# usage TBExptCloseLogFile(char *pid, char *eid)
#
sub TBExptOpenLogFile($$)
{
    my ($pid, $eid) = @_;
    
    DBQueryFatal("update experiments set logfile_open=1 ".
		 "where pid='$pid' and eid='$eid'");
}

sub TBExptCloseLogFile($$)
{
    my ($pid, $eid) = @_;
    
    DBQueryFatal("update experiments set logfile_open=0 ".
1687
1688
1689
1690
1691
1692
		 "where pid='$pid' and eid='$eid'");
}

#
# Get the current logfile for an experiment. 
#
1693
# usage TBExptGetLogFile(char *pid, char *eid, char \*logname, int \isopen)
1694
1695
1696
#	Return 1 if there is a valid logname, and sets logname.
#	Return 0 if no logfile or error.
#
1697
sub TBExptGetLogFile($$$$)
1698
{
1699
    my ($pid, $eid, $logname, $isopen) = @_;
1700
1701
    
    my $query_result =
1702
	DBQueryFatal("select logfile,logfile_open from experiments ".
1703
1704
1705
1706
1707
1708
1709
1710
		     "where pid='$pid' and eid='$eid'");

    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
    if (defined($row[0])) {
	$$logname = $row[0];
1711
	$$isopen  = $row[1];
1712
1713
1714
1715
1716
	return 1;
    }
    return 0;
}

1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
#
# Create a temp logfile name for an experiment, create it, and untaint it!
# Note that we create the file in /tmp initially, mostly as a convenience,
# and then move it into the experiment directory later. 
#
sub TBExptCreateLogFile($$$)
{
    my($pid, $eid, $prefix) = @_;
    my $logname;
    
    $logname = `mktemp /tmp/${prefix}-${pid}-${eid}.XXXXXX`;

    if ($logname =~ /^([-\@\w\.\/]+)$/) {
	$logname = $1;
    }
    else {
	die("*** $0:\n".
	    "    Bad data in logfile name: $logname");
    }

    chmod(0640, $logname) or
	die("*** $0:\n".
	    "    Could not chmod $logname to 0640: $!\n");

    return $logname;
}

1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
#
# Get the control network IP for a node (underlying physical node!).
#
# usage TBControlNetIP(char *nodeid, char \*ip)
#	Return 1 if success.
#	Return 0 if error.
#
sub TBControlNetIP($$)
{
    my ($nodeid, $pip) = @_;

    my $query_result =
	DBQueryFatal("select IP from nodes as n2 ".
		     "left join nodes as n1 on n1.node_id=n2.phys_nodeid ".
		     "left join node_types as nt on n1.type=nt.type ".
		     "left join interfaces as i on ".
		     "i.node_id=n1.node_id and i.iface=nt.control_iface ".
		     "where n2.node_id='$nodeid'");

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

#
# Get the underlying physical node. Might be the same as the node if its
# not a virtual node.
#
# usage TBPhysNodeID(char *nodeid, char \*phys_nodeid)
#	Return 1 if success.
#	Return 0 if error.
#
sub TBPhysNodeID($$)
{
    my ($nodeid, $pphys) = @_;

    my $query_result =
	DBQueryFatal("select phys_nodeid from nodes ".
		     "where node_id='$nodeid'");

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

1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
#
# From the physical node name, get the name that the should be used in the
# widearea_* tables
#
# usage TBWideareaNodeID(char *nodeid, char \*widearea_nodeid)
#	Return 1 if success.
#	Return 0 if error. (Currently, not possible)
#
sub TBWideareaNodeID($$)
{
    my ($nodeid, $pwide) = @_;

    if (TBIsNodeRemote($nodeid)) {
	$$pwide = $nodeid;
    } else {
	$$pwide = TBDB_WIDEAREA_LOCALNODE;
    }

    return 1;
}


1823
1824
1825
#
# Issue a DB query. Argument is a string. Returns the actual query object, so
# it is up to the caller to test it. I would not for one moment view this
1826
1827
# as encapsulation of the DB interface. I'm just tired of typing the same
# silly stuff over and over. 
1828
1829
1830
1831
# 
# usage: DBQuery(char *str)
#        returns the query object result.
#
1832
1833
1834
1835
# Sets $DBErrorString is case of error; saving the original query string and
# the error string from the DB module. Use DBFatal (below) to print/email
# that string, and then exit.
#
1836
1837
1838
1839
1840
1841
1842
1843
sub DBQuery($)
{
    my($query) = $_[0];
    my($result);

    $result = $DB->query($query);

    if (! $result) {
1844
1845
	$DBErrorString =
	    "  Query: $query\n".
1846
	    "  Error: " . $DB->errstr;
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
    }
    return $result;
}

#
# Same as above, but die on error. 
# 
sub DBQueryFatal($)
{
    my($query) = $_[0];
    my($result);

    $result = DBQuery($query);

    if (! $result) {
1862
	DBFatal("DB Query failed");
1863
1864
1865
1866
    }
    return $result;
}

1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
#
# Same as above, but just send email on error. This info is useful
# to the TB system, but the caller has to retain control.
# 
sub DBQueryWarn($)
{
    my($query) = $_[0];
    my($result);

    $result = DBQuery($query);

    if (! $result) {
	DBWarn("DB Query failed");
    }
    return $result;
}

1884
#
1885
# Warn and send email after a failed DB query. First argument is the error
1886
1887
# message to display. The contents of $DBErrorString is also printed.
# 
1888
# usage: DBWarn(char *message)
1889
#
1890
sub DBWarn($)
1891
1892
{
    my($message) = $_[0];
1893
    my($text, $progname);
1894

1895
    #
1896
    # Must taint check $PROGRAM_NAME cause it comes from outside. Silly!
1897
1898
1899
1900
1901
1902
1903
1904
    #
    if ($PROGRAM_NAME =~ /^([-\w.\/]+)$/) {
	$progname = $1;
    }
    else {
	$progname = "Tainted";
    }

1905
1906
    $text = "$message - In $progname\n" .
  	    "$DBErrorString\n";
1907

1908
    print STDERR "*** $text";
1909

1910
    libtestbed::SENDMAIL($TBOPS, "DBError - $message", $text);
1911
1912
1913
1914
1915
}

#
# Same as above, but die after the warning.
# 
1916
# usage: DBFatal(char *message);
1917
1918
1919
1920
1921
1922
#
sub DBFatal($)
{
    my($message) = $_[0];

    DBWarn($message);
1923

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1924
    die("\n");
1925
1926
}

1927
1928
1929
#
# Quote a string for DB insertion.
#
1930
# usage: char *DBQuoteSpecial(char *string);
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
#
sub DBQuoteSpecial($)
{