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

3
#
4
5
# A library of useful DB stuff. Mostly things that get done a lot.
# Saves typing.
6
7
8
9
10
#
# 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.
#
11

12
13
14
15
package libdb;
use Exporter;
@ISA = "Exporter";
@EXPORT =
16
17
18
    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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
	 PROJMEMBERTRUST_ROOT PROJMEMBERTRUST_GROUPROOT
	 PROJMEMBERTRUST_PROJROOT

	 TBTrustConvert TBMinTrust TBGrpTrust TBProjTrust

	 TB_NODEACCESS_READINFO TB_NODEACCESS_MODIFYINFO
	 TB_NODEACCESS_LOADIMAGE TB_NODEACCESS_REBOOT
	 TB_NODEACCESS_POWERCYCLE TB_NODEACCESS_MIN TB_NODEACCESS_MAX

	 TB_USERINFO_READINFO TB_USERINFO_MODIFYINFO
	 TB_USERINFO_MIN TB_USERINFO_MAX

	 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
49

50
51
52
53
	 EXPTSTATE_NEW EXPTSTATE_PRERUN EXPTSTATE_SWAPPED EXPTSTATE_SWAPPING
	 EXPTSTATE_ACTIVATING EXPTSTATE_ACTIVE EXPTSTATE_TESTING
	 EXPTSTATE_TERMINATING EXPTSTATE_TERMINATED

54
55
	 BATCHSTATE_POSTED BATCHSTATE_RUNNING BATCHSTATE_TERMINATING
	 BATCHSTATE_ACTIVATING
Leigh B. Stoller's avatar
Leigh B. Stoller committed
56
57
	 TBBatchState TBSetBatchState

58
59
60
	 TB_NODELOGTYPE_MISC TB_NODELOGTYPES TB_DEFAULT_NODELOGTYPE 

	 TB_DEFAULT_RELOADTYPE TB_RELOADTYPE_FRISBEE TB_RELOADTYPE_NETDISK
61

Leigh B. Stoller's avatar
Leigh B. Stoller committed
62
63
	 TBAdmin TBProjAccessCheck TBNodeAccessCheck TBOSIDAccessCheck
	 TBImageIDAccessCheck TBExptAccessCheck ExpLeader MarkNodeDown
64
	 SetNodeBootStatus OSFeatureSupported IsShelved NodeidToExp
65
	 UserDBInfo DBQuery DBQueryFatal DBQueryWarn DBWarn DBFatal
66
	 DBQuoteSpecial UNIX2DBUID ExpState SetExpState ProjLeader
Leigh B. Stoller's avatar
Leigh B. Stoller committed
67
	 ExpNodes DBDateTime DefaultImageID GroupLeader TBGroupUnixInfo
68
	 TBValidNodeLogType TBValidNodeName TBSetNodeLogEntry
69
	 TBSetSchedReload
70
	 );
71

72
73
# Must come after package declaration!
use English;
74
use POSIX qw(strftime);
75
76
require Mysql;

77
78
79
# Configure variables
my $TB		= "@prefix@";
my $DBNAME	= "@TBDBNAME@";
80
my $TBOPS       = "@TBOPSEMAIL@";
81
82

#
83
84
# Set up for querying the database. Note that fork causes a reconnect
# to the DB in the child. 
85
86
87
# 
my $DB = Mysql->connect("localhost", $DBNAME, "script", "none");

88
89
90
91
92
#
# Record last DB error string.
#
my $DBErrorString = "";

93
94
95
96
97
#
# 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.
#
98
sub NODERELOADING_PID()		{ "emulab-ops"; }
99
sub NODERELOADING_EID()		{ "reloading"; }
100
sub NODERELOADPENDING_EID()	{ "reloadpending"; }
101
102
103
104
105
106
107
108
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"; }

109
110
111
112
113
114
115
116
117
118
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"; }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
119
120
121
122
123
sub BATCHSTATE_POSTED()		{ "posted"; }
sub BATCHSTATE_ACTIVATING()	{ "activating"; }
sub BATCHSTATE_RUNNING()	{ "active"; }
sub BATCHSTATE_TERMINATING()	{ "terminating"; }

124
125
126
127
128
129
#
# 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; }
130
sub PROJMEMBERTRUST_ROOT()	{ 2; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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; }
sub TB_NODEACCESS_MIN()		{ TB_NODEACCESS_READINFO; }
sub TB_NODEACCESS_MAX()		{ TB_NODEACCESS_POWERCYCLE; }

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

193
# Node Log Types
194
195
196
197
198
199
200
201
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"; }
sub TB_DEFAULT_RELOADTYPE()	{ TB_RELOADTYPE_NETDISK; }
202

203
204
205
206
207
#
# We should list all of the DB limits.
#
sub DBLIMIT_NSFILESIZE()	{ (1024 * 16); }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#
# 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);
}

324
#
325
326
# Test admin status. Optional argument is the UID or Name to test. If not
# provided, then test the current UID.
327
#
328
329
330
# XXX Argument is *either* a numeric UID, or a string name.
#
# usage: TBAdmin([int or char* uid]);
331
332
333
334
335
336
#        returns 1 if an admin type.
#        returns 0 if a mere user.
# 
sub TBAdmin(;$)
{
    my($uid) = @_;
337
    my($name);
338
339
340
341
342

    if (!defined($uid)) {
	$uid = $UID;
    }

343
344
345
346
347
348
349
350
351
352
    #
    # 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;
    }
353
354

    my $query_result =
355
	DBQueryFatal("select admin from users where uid='$name'");
356
357
358
359
360
361
362
363
364

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

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
365
366
# Project permission checks. The group id (gid) can be undef, in which case
# the pid is used (ie: a default group check is made).
367
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
368
369
370
371
372
# Usage: TBProjAccessCheck($uid, $pid, $gid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
# 
sub TBProjAccessCheck($$$$)
373
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
374
375
    my ($uid, $pid, $gid, $access_type) = @_;
    my $mintrust;
376

Leigh B. Stoller's avatar
Leigh B. Stoller committed
377
378
379
    if ($access_type < TB_PROJECT_MIN ||
	$access_type > TB_PROJECT_MAX) {
	die("*** Invalid access type: $access_type!");
380
381
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
382
383
384
385
386
    #
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
387
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
388
389
390
391
392
393
394
    $uid = MapNumericUID($uid);

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
    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!");
425
426
427
    }

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
428
429
430
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
431
432
	return 1;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
433
    $uid = MapNumericUID($uid);
434

Leigh B. Stoller's avatar
Leigh B. Stoller committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    my $query_result =
	DBQueryFatal("SELECT gid FROM experiments WHERE ".
		     "eid='$eid' and pid='$pid'");
    
    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
    my $gid = $row[0];

    if ($access_type == TB_EXPT_READINFO) {
	$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!");
    }
472
473

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    # 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) {
489
	my $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
490
491
492
493
494
495
	    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'");
496

497
	if ($query_result->numrows == 0) {
498
499
	    return 0;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
500
501
502
503
504
	my @row = $query_result->fetchrow_array();

	if (! TBMinTrust($row[0], $mintrust)) {
	    return 0;
	}
505
506
507
508
509
    }
    return 1;
}

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
510
# Access checks for an OSID. Tests for tbadmin.
511
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
512
513
514
# Usage: TBOSIDAccessCheck($uid, $osid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
515
# 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
516
sub TBOSIDAccessCheck($$$)
517
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
518
519
    my ($uid, $osid, $access_type) = @_;
    my $mintrust;
520

Leigh B. Stoller's avatar
Leigh B. Stoller committed
521
522
    if ($access_type < TB_OSID_MIN || $access_type > TB_OSID_MAX) {
	die("*** Invalid access type $access_type!");
523
524
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
525
526
527
528
529
530
531
    #
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
    }
    $uid = MapNumericUID($uid);
532

Leigh B. Stoller's avatar
Leigh B. Stoller committed
533
534
535
536
537
538
    #
    # No GIDs yet.
    #
    my $query_result =
	DBQueryFatal("SELECT pid FROM os_info WHERE osid='$osid'");
    
539
    if ($query_result->numrows == 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
540
	return 0;
541
    }
542
    my @row = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
543
544
545
546
547
548
549
550
551
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
580
581
    my $pid = $row[0];

    #
    # Global OSIDs can be read by anyone.
    # 
    if (!$pid) {
	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!");
582
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
583
584
585
586
587
588

    #
    # Admins do whatever they want!
    # 
    if (TBAdmin($uid)) {
	return 1;
589
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
590
591
592
593
594
595
596
597
598
599
    $uid = MapNumericUID($uid);

    #
    # No GIDs yet.
    #
    my $query_result =
	DBQueryFatal("SELECT pid FROM images WHERE imageid='$imageid'");
    
    if ($query_result->numrows == 0) {
	return 0;
600
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
601
602
603
    my @row = $query_result->fetchrow_array();
    my $pid = $row[0];

604
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
605
606
607
608
609
610
611
612
613
    # Global ImageIDs can be read by anyone.
    # 
    if (!$pid) {
	if ($access_type == TB_IMAGEID_READINFO) {
	    return 1;
	}
	return 0;
    }

614
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
615
616
617
618
619
620
621
622
623
624
    # 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);
625
626
}

627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#
# 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
#
# 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];
}

672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#
# 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];
}

695
696
697
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
#
# 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'");

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
#
# 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;
}

787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
#
# 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()) {
	push(@nodes, $row[0]);
    }
    return @nodes;
}

814
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
815
816
817
# 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).
818
819
820
821
822
823
#
# usage: MarkNodeDown(char *nodeid)
#
sub MarkNodeDown($)
{
    my($node) = $_[0];
824
825
    my($pid, $eid);

826
827
    $pid = NODEDEAD_PID;
    $eid = NODEDEAD_EID;
828
829

    my $query_result =
830
831
	DBQueryFatal("replace into next_reserve (node_id, pid, eid) ".
		     "values ('$node', '$pid', '$eid')");    
832
833
834
835
836
837

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

838
839
840
841
842
843
844
845
846
847
848
849
850
#
# 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'");
}

851
852
853
854
855
856
#
# Check if a particular feature is supported by an OSID. 
#
# usage: OSFeatureSupported(char *osid, char *feature)
#        returns 1 if supported, 0 if not.
#
857
sub OSFeatureSupported($$) {
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
    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;
}

876
877
878
879
880
881
#
# 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.
#
882
# usage: IsShelved(char *nodeid, [\$shelf], [\$node])
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
#        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;
}

901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
#
# Map nodeid to its pid/eid.
#
# usage: NodeToExp(char *nodeid, \$pid, \$eid)
#        returns 1 if the node is reserved.
#        returns 0 if the node is not reserved.
#
sub NodeidToExp ($$$) {
    my($nodeid, $pid, $eid) = @_;

    my $query_result =
	DBQueryFatal("select pid,eid from reserved where node_id='$nodeid'");

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
#
# 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];
}

947
#
948
# Map login (db uid) to a user_name and user_email.
949
#
950
# usage: UserDBInfo(char *dbuid, \$name, \$email)
951
952
953
#        returns 1 if the UID is okay.
#        returns 0 if the UID is bogus.
#
954
955
sub UserDBInfo ($$$) {
    my($dbuid, $username, $useremail) = @_;
956

957
958
959
960
961
962
963
964
965
966
967
968
969
970
    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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
#
# 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;
}

995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
#
# 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) = @_;
1007
1008

    my $query_result =
1009
	DBQueryFatal("select uid from users where unix_uid='$unix_uid'");
1010
1011
1012
1013
1014

    if ($query_result->num_rows < 1) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1015
1016
1017
1018
1019
1020
1021
1022
1023

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

1024
1025
1026
1027
    $$userlogin = $row[0];
    return 1;
}

1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
#
# 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;
}

1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
#
# 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;
}

1111
1112
1113
#
# 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
1114
1115
# as encapsulation of the DB interface. I'm just tired of typing the same
# silly stuff over and over. 
1116
1117
1118
1119
# 
# usage: DBQuery(char *str)
#        returns the query object result.
#
1120
1121
1122
1123
# 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.
#
1124
1125
1126
1127
1128
1129
1130
1131
sub DBQuery($)
{
    my($query) = $_[0];
    my($result);

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

    if (! $result) {
1132
1133
	$DBErrorString =
	    "  Query: $query\n".
1134
	    "  Error: " . $DB->errstr;
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
    }
    return $result;
}

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

    $result = DBQuery($query);

    if (! $result) {
1150
	DBFatal("DB Query failed");
1151
1152
1153
1154
    }
    return $result;
}

1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
#
# 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;
}

1172
#
1173
# Warn and send email after a failed DB query. First argument is the error
1174
1175
# message to display. The contents of $DBErrorString is also printed.
# 
1176
# usage: DBWarn(char *message)
1177
#
1178
sub DBWarn($)
1179
1180
{
    my($message) = $_[0];
1181
    my($text, $progname);
1182

1183
    #
1184
    # Must taint check $PROGRAM_NAME cause it comes from outside. Silly!
1185
1186
1187
1188
1189
1190
1191
1192
    #
    if ($PROGRAM_NAME =~ /^([-\w.\/]+)$/) {
	$progname = $1;
    }
    else {
	$progname = "Tainted";
    }

1193
1194
    $text = "$message - In $progname\n" .
  	    "$DBErrorString\n";
1195

1196
    print STDERR "*** $text\n";
1197
1198

    system("echo \"$text\" | /usr/bin/mail ".
1199
	   "-s 'TESTBED: DBError - $message' \"$TBOPS\"");
1200
1201
1202
1203
1204
}

#
# Same as above, but die after the warning.
# 
1205
# usage: DBFatal(char *message);
1206
1207
1208
1209
1210
1211
#
sub DBFatal($)
{
    my($message) = $_[0];

    DBWarn($message);
1212

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1213
    die("\n");
1214
1215
}

1216
1217
1218
#
# Quote a string for DB insertion.
#
1219
# usage: char *DBQuoteSpecial(char *string);
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
#
sub DBQuoteSpecial($)
{
    my($string) = $_[0];

    $string = $DB->quote($string);

    return $string;
}

1230
1231
1232
1233
#
# Return a (current) string suitable for DB insertion in datetime slot.
# Of course, you can use this for anything you like!
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1234
# usage: char *DBDateTime(int seconds-to-add);
1235
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1236
sub DBDateTime(;$)
1237
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
    my($seconds) = @_;

    if (! defined($seconds)) {
	$seconds = 0;
    }
    
    return strftime("20%y-%m-%d %H:%M:%S", localtime(time() + $seconds));
}

#
# Helper. Test if numeric. Convert to dbuid if numeric.
#
sub MapNumericUID($)
{
    my ($uid) = @_;
    my $name;
    
    if ($uid =~ /^[0-9]+$/) {
	UNIX2DBUID($uid, \$name)
	    or die("*** $uid not a valid Emulab user!\n");
    }
    else {
	$name = $uid;
    }
    return $name;
1263
1264
}

1265
1266
1;