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

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

9
#
10
11
# A library of useful DB stuff. Mostly things that get done a lot.
# Saves typing.
12
#
Kevin Atkinson's avatar
   
Kevin Atkinson committed
13
14
# NOTE: Overrides perl's builtin fork()
#
15
16
17
18
# 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.
#
19

20
package libdb;
21
use strict;
22
use Exporter;
Mac Newbold's avatar
Mac Newbold committed
23
use vars qw(@ISA @EXPORT);
24
25
@ISA = "Exporter";
@EXPORT =
26
    qw ( NODERELOADING_PID NODERELOADING_EID NODEDEAD_PID NODEDEAD_EID
27
	 OLDRESERVED_PID OLDRESERVED_EID NFREELOCKED_PID NFREELOCKED_EID 
28
29
	 NODEBOOTSTATUS_OKAY NODEBOOTSTATUS_FAILED NODEBOOTSTATUS_UNKNOWN
	 NODESTARTSTATUS_NOSTATUS PROJMEMBERTRUST_NONE PROJMEMBERTRUST_USER
Leigh B. Stoller's avatar
Leigh B. Stoller committed
30
	 PROJMEMBERTRUST_ROOT PROJMEMBERTRUST_GROUPROOT
31
	 PROJMEMBERTRUST_PROJROOT PROJMEMBERTRUST_LOCALROOT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
32

33
	 TBOPSPID EXPTLOGNAME
34
	 PLABMOND_PID PLABMOND_EID PLABHOLDING_PID PLABHOLDING_EID
Kirk Webb's avatar
   
Kirk Webb committed
35
         PLABTESTING_PID PLABTESTING_EID PLABDOWN_PID PLABDOWN_EID
36

37
	 TBTrustConvert TBMinTrust TBGrpTrust TBProjTrust MapNumericUID
Leigh B. Stoller's avatar
Leigh B. Stoller committed
38
39
40

	 TB_NODEACCESS_READINFO TB_NODEACCESS_MODIFYINFO
	 TB_NODEACCESS_LOADIMAGE TB_NODEACCESS_REBOOT
41
42
	 TB_NODEACCESS_POWERCYCLE TB_NODEACCESS_MODIFYVLANS
	 TB_NODEACCESS_MIN TB_NODEACCESS_MAX
Leigh B. Stoller's avatar
Leigh B. Stoller committed
43

44
45
	 NODEFAILMODE_FATAL NODEFAILMODE_NONFATAL NODEFAILMODE_IGNORE

Leigh B. Stoller's avatar
Leigh B. Stoller committed
46
47
48
	 TB_USERINFO_READINFO TB_USERINFO_MODIFYINFO
	 TB_USERINFO_MIN TB_USERINFO_MAX

49
50
	 USERSTATUS_ACTIVE USERSTATUS_FROZEN
	 USERSTATUS_UNAPPROVED USERSTATUS_UNVERIFIED USERSTATUS_NEWUSER
51

52
	 TB_EXPT_READINFO TB_EXPT_MODIFY TB_EXPT_DESTROY TB_EXPT_UPDATE
Leigh B. Stoller's avatar
Leigh B. Stoller committed
53
54
55
56
	 TB_EXPT_MIN TB_EXPT_MAX

	 TB_PROJECT_READINFO TB_PROJECT_MAKEGROUP
	 TB_PROJECT_EDITGROUP TB_PROJECT_DELGROUP
Chad Barb's avatar
   
Chad Barb committed
57
	 TB_PROJECT_GROUPGRABUSERS TB_PROJECT_BESTOWGROUPROOT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
58
59
60
61
62
63
64
65
66
67
68
	 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
69

Leigh B. Stoller's avatar
Leigh B. Stoller committed
70
	 DBLIMIT_NSFILESIZE NODERELOADPENDING_EID
71

Timothy Stack's avatar
   
Timothy Stack committed
72
73
	 NODEREPOSITIONING_PID NODEREPOSITIONING_EID NODEREPOSPENDING_EID

74
	 EXPTSTATE_NEW EXPTSTATE_PRERUN EXPTSTATE_SWAPPED EXPTSTATE_SWAPPING
Leigh B. Stoller's avatar
Leigh B. Stoller committed
75
	 EXPTSTATE_ACTIVATING EXPTSTATE_ACTIVE EXPTSTATE_PANICED
76
77
78
79
80
	 EXPTSTATE_TERMINATING EXPTSTATE_TERMINATED EXPTSTATE_QUEUED
	 EXPTSTATE_MODIFY_PARSE EXPTSTATE_MODIFY_REPARSE EXPTSTATE_MODIFY_RESWAP
	 EXPTSTATE_RESTARTING
	 BATCHSTATE_LOCKED BATCHSTATE_UNLOCKED
	 EXPTCANCEL_CLEAR EXPTCANCEL_TERM EXPTCANCEL_SWAP
81

82
	 TBSetCancelFlag TBGetCancelFlag
Leigh B. Stoller's avatar
Leigh B. Stoller committed
83

Mac Newbold's avatar
Mac Newbold committed
84
	 TB_NODELOGTYPE_MISC TB_NODELOGTYPES TB_DEFAULT_NODELOGTYPE
85
86

	 TB_DEFAULT_RELOADTYPE TB_RELOADTYPE_FRISBEE TB_RELOADTYPE_NETDISK
87

88
89
	 TB_EXPTPRIORITY_LOW TB_EXPTPRIORITY_HIGH

90
	 TB_ASSIGN_TOOFEWNODES TB_OPSPID
91

92
	 TBDB_TBEVENT_NODESTATE TBDB_TBEVENT_NODEOPMODE TBDB_TBEVENT_CONTROL
93
	 TBDB_TBEVENT_COMMAND
Chad Barb's avatar
   
Chad Barb committed
94

95
	 TBDB_NODESTATE_ISUP TBDB_NODESTATE_REBOOTING TBDB_NODESTATE_REBOOTED
96
	 TBDB_NODESTATE_SHUTDOWN TBDB_NODESTATE_BOOTING TBDB_NODESTATE_TBSETUP
97
	 TBDB_NODESTATE_RELOADSETUP TBDB_NODESTATE_RELOADING
98
99
	 TBDB_NODESTATE_RELOADDONE TBDB_NODESTATE_RELOADDONE_V2
	 TBDB_NODESTATE_UNKNOWN
100
	 TBDB_NODESTATE_PXEWAIT TBDB_NODESTATE_PXEWAKEUP
101
	 TBDB_NODESTATE_PXEBOOTING TBDB_NODESTATE_ALWAYSUP
102
	 TBDB_NODESTATE_MFSSETUP TBDB_NODESTATE_TBFAILED
103
	 TBDB_NODESTATE_POWEROFF
Chad Barb's avatar
   
Chad Barb committed
104

105
106
	 TBDB_NODEOPMODE_NORMAL TBDB_NODEOPMODE_DELAYING
	 TBDB_NODEOPMODE_UNKNOWNOS TBDB_NODEOPMODE_RELOADING
107
	 TBDB_NODEOPMODE_NORMALv1 TBDB_NODEOPMODE_MINIMAL
108
109
	 TBDB_NODEOPMODE_RELOAD TBDB_NODEOPMODE_RELOADMOTE
	 TBDB_NODEOPMODE_DELAY
110
	 TBDB_NODEOPMODE_BOOTWHAT
111
	 TBDB_NODEOPMODE_ANY
112
	 TBDB_NODEOPMODE_UNKNOWN
Chad Barb's avatar
   
Chad Barb committed
113

114
	 TBDB_COMMAND_REBOOT
115
116
	 TBDB_COMMAND_POWEROFF TBDB_COMMAND_POWERON TBDB_COMMAND_POWERCYCLE

117
118
119
	 TBDB_STATED_TIMEOUT_REBOOT TBDB_STATED_TIMEOUT_NOTIFY
	 TBDB_STATED_TIMEOUT_CMDRETRY

Chad Barb's avatar
   
Chad Barb committed
120
121
122
	 TBDB_ALLOCSTATE_FREE_CLEAN TBDB_ALLOCSTATE_FREE_DIRTY
	 TBDB_ALLOCSTATE_DOWN TBDB_ALLOCSTATE_RELOAD_TO_FREE
	 TBDB_ALLOCSTATE_RELOAD_PENDING TBDB_ALLOCSTATE_RES_RELOAD
Mac Newbold's avatar
Mac Newbold committed
123
124
	 TBDB_ALLOCSTATE_RES_INIT_DIRTY TBDB_ALLOCSTATE_RES_INIT_CLEAN
	 TBDB_ALLOCSTATE_RES_REBOOT_DIRTY TBDB_ALLOCSTATE_RES_REBOOT_CLEAN
Chad Barb's avatar
   
Chad Barb committed
125
	 TBDB_ALLOCSTATE_RES_READY TBDB_ALLOCSTATE_UNKNOWN
126
	 TBDB_ALLOCSTATE_RES_TEARDOWN TBDB_ALLOCSTATE_DEAD
127
	 TBDB_ALLOCSTATE_RES_RECONFIG
Chad Barb's avatar
   
Chad Barb committed
128

129
130
	 TBDB_STATS_PRELOAD TBDB_STATS_START TBDB_STATS_TERMINATE
	 TBDB_STATS_SWAPIN TBDB_STATS_SWAPOUT TBDB_STATS_SWAPMODIFY
131
	 TBDB_STATS_FLAGS_IDLESWAP TBDB_STATS_FLAGS_PREMODIFY
132
	 TBDB_STATS_FLAGS_START TBDB_STATS_FLAGS_PRESWAPIN
133

134
135
	 TBDB_JAILIPBASE TBDB_JAILIPMASK

136
	 TBDB_RSRVROLE_NODE TBDB_RSRVROLE_VIRTHOST TBDB_RSRVROLE_DELAYNODE
137
	 TBDB_RSRVROLE_SIMHOST
138

139
	 TBDB_EXPT_WORKDIR
140
	 TBSetNodeEventState TBGetNodeEventState
Timothy Stack's avatar
   
Timothy Stack committed
141
	 TBNodeEventStateUpdated
Chad Barb's avatar
   
Chad Barb committed
142
	 TBSetNodeAllocState TBGetNodeAllocState
143
	 TBSetNodeOpMode TBGetNodeOpMode TBSetNodeNextOpMode
144
	 TB_OSID_MBKERNEL 
Mac Newbold's avatar
Mac Newbold committed
145
	 TB_OSID_FREEBSD_MFS TB_OSID_FRISBEE_MFS
146
	 TBBootWhat TBNodeStateTimeout
Mac Newbold's avatar
Mac Newbold committed
147
	 TBDB_TBCONTROL_RESET TBDB_TBCONTROL_RELOADDONE
148
	 TBDB_TBCONTROL_RELOADDONE_V2
149
	 TBDB_TBCONTROL_TIMEOUT TBDB_NO_STATE_TIMEOUT
Mac Newbold's avatar
Mac Newbold committed
150
151
	 TBDB_TBCONTROL_PXEBOOT TBDB_TBCONTROL_BOOTING
	 TBDB_TBCONTROL_CHECKGENISUP
152

153
154
	 TBDB_LOWVPORT TBDB_MAXVPORT TBDB_PORTRANGE

155
156
	 TBDB_PHYSICAL_NODE_TABLES

157
	 TBAdmin TBOpsGuy TBProjAccessCheck TBNodeAccessCheck TBOSIDAccessCheck
Leigh B. Stoller's avatar
Leigh B. Stoller committed
158
	 TBImageIDAccessCheck TBExptAccessCheck ExpLeader MarkNodeDown
159
	 SetNodeBootStatus OSFeatureSupported IsShelved NodeidToExp NodeidToExpOldReserved
160
	 UserDBInfo DBQuery DBQueryFatal DBQueryWarn DBWarn DBFatal DBErr
Kevin Atkinson's avatar
   
Kevin Atkinson committed
161
	 NewTBDBHandle DBQueryN DBQueryFatalN DBQueryWarnN DBErrN
162
	 DBQuoteSpecial UNIX2DBUID ExpState SetExpState ProjLeader
163
164
	 ExpNodes ExpNodeVnames ExpNodesOldReserved
	 DBDateTime DefaultImageID GroupLeader TBGroupUnixInfo
165
	 TBValidNodeLogType TBValidNodeName TBSetNodeLogEntry
166
	 TBSetSchedReload MapNodeOSID TBLockExp TBUnLockExp TBSetExpSwapTime
167
	 TBUnixGroupList TBOSID TBOSMaxConcurrent TBOSCountInstances
168
	 TBResolveNextOSID TBOsidToPid TBOSIDRebootWaittime
169
	 TBOSLoadMaxOkay TBImageLoadMaxOkay TBImageID ExpSwapper
170
	 TBdbfork TBDBDisconnect VnameToNodeid TBExpLocked
171
	 TBIsNodeRemote TBExptSetLogFile TBExptClearLogFile TBExptGetLogFile
172
	 TBIsNodeImageable TBIsNodeVirtual TBControlNetIP TBPhysNodeID
173
	 TBExptOpenLogFile TBExptCloseLogFile TBExptCreateLogFile
174
	 TBNodeUpdateAccountsByPid TBNodeUpdateAccountsByType
175
	 TBNodeUpdateAccountsByUID
176
	 TBSaveExpLogFiles TBExptWorkDir TBExptUserDir TBExptLogDir
177
	 TBExptDestroy TBIPtoNodeID TBNodeBootReset TBNodeStateWait
178
	 TBLeaderMailList ExpGroup TBExptSetSwapUID TBExptSetThumbNail
179
	 TBNodeAllocCheck TBPlabNodeUsername MarkPhysNodeDown
180
181
182
	 TBExptIsElabInElab TBExptIsPlabInElab
	 TBExptPlabInElabPLC TBExptPlabInElabNodes
	 TBBatchUnLockExp TBExptIsBatchExp
183
	 
Mike Hibler's avatar
Mike Hibler committed
184
185
	 TBExptFirewall TBNodeFirewall TBExptFirewallAndPort
	 TBSetExptFirewallVlan TBClearExptFirewallVlan
186
	 TBNodeConsoleTail TBExptGetSwapoutAction TBExptGetSwapState
187

Timothy Stack's avatar
   
Timothy Stack committed
188
	 TBNodeSubNodes
189
	 TBNodeAdminOSID TBNodeDiskloadOSID
190
	 TBNodeType TBNodeTypeProcInfo TBNodeTypeBiosWaittime
191

Mac Newbold's avatar
Mac Newbold committed
192
	 TBExptRemoveVirtualState TBExptBackupVirtualState
Chad Barb's avatar
   
Chad Barb committed
193
194
	 TBExptRestoreVirtualState

Mac Newbold's avatar
Mac Newbold committed
195
	 TBExptRemovePhysicalState TBExptBackupPhysicalState
196
	 TBExptRestorePhysicalState TBExptClearBackupState
Chad Barb's avatar
   
Chad Barb committed
197

198
199
	 TBExptPortRange

200
	 TBDB_WIDEAREA_LOCALNODE
Leigh B. Stoller's avatar
Leigh B. Stoller committed
201
	 TBWideareaNodeID TBTipServers
Mac Newbold's avatar
Mac Newbold committed
202

203
	 TBSiteVarExists TBGetSiteVar TBSetSiteVar
Chad Barb's avatar
   
Chad Barb committed
204

205
	 TBActivityReport GatherSwapStats GatherAssignStats
206
	 TBAvailablePCs
207

208
209
	 TBDB_IFACEROLE_CONTROL TBDB_IFACEROLE_EXPERIMENT
	 TBDB_IFACEROLE_JAIL TBDB_IFACEROLE_FAKE TBDB_IFACEROLE_OTHER
210
	 TBDB_IFACEROLE_GW TBDB_IFACEROLE_OUTER_CONTROL
211

212
213
	 TBDB_ROUTERTYPE_NONE	TBDB_ROUTERTYPE_OSPF
	 TBDB_ROUTERTYPE_STATIC TBDB_ROUTERTYPE_MANUAL
214
	 TBDB_EVENTKEY TBDB_WEBKEY
215
216
	 TBDB_CHECKDBSLOT_NOFLAGS TBDB_CHECKDBSLOT_WARN TBDB_CHECKDBSLOT_ERROR
         max min TBcheck_dbslot
Mac Newbold's avatar
Mac Newbold committed
217
	 hash_recurse array_recurse hash_recurse2 array_recurse2
218
	 TBGetUniqueIndex
219
220

	 TBExptMinMaxNodes TBExptSecurityLevel TBExptIDX
221
222
	 TBDB_SECLEVEL_GREEN TBDB_SECLEVEL_BLUE TBDB_SECLEVEL_YELLOW
	 TBDB_SECLEVEL_ORANGE TBDB_SECLEVEL_RED TBDB_SECLEVEL_ZAPDISK
Leigh B. Stoller's avatar
Leigh B. Stoller committed
223
224

	 TBExptSetPanicBit TBExptGetPanicBit TBExptClearPanicBit
225
226
227
228

	 TB_NODEHISTORY_OP_FREE TB_NODEHISTORY_OP_ALLOC TB_NODEHISTORY_OP_MOVE
	 TBSetNodeHistory

Timothy Stack's avatar
   
Timothy Stack committed
229
230
	 TBGetOSBootCmd

231
232
	 TBRobotLabExpt

233
	 TBExptContainsNodeCT
234
	 );
235

236
# Must come after package declaration!
237
use lib '@prefix@/lib';
Kevin Atkinson's avatar
   
Kevin Atkinson committed
238
use libtblog_simple;
239
use English;
240
use File::Basename;
241
use POSIX qw(strftime);
242
243
require Node;
require NodeType;
244
require Mysql;
245
246
247
use vars qw($DBQUERY_MAXTRIES $DBCONN_MAXTRIES
	    $DBCONN_EXITONERR $DBQUERY_RECONNECT
	    @EXPORT_OK @virtualTables @physicalTables);
248

249
250
251
# Configure variables
my $TB		= "@prefix@";
my $DBNAME	= "@TBDBNAME@";
252
my $TBOPS       = "@TBOPSEMAIL@";
253
254
my $EVENTSYS    = "@EVENTSYS@";
my $BOSSNODE    = "@BOSSNODE@";
255
my $TESTMODE    = @TESTMODE@;
256
my $TBOPSPID	= "emulab-ops";
257
my $SCRIPTNAME  = "Unknown";
258
my $EXPTLOGNAME = "activity.log";
259
my $PROJROOT    = "@PROJROOT_DIR@";
260

261
262
263
264
265
if ($EVENTSYS) {
    require event;
    import event;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
266
267
268
# Untainted scriptname for email below.
if ($PROGRAM_NAME =~ /^([-\w\.\/]+)$/) {
    $SCRIPTNAME = basename($1);
269
270
}
else {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
271
    $SCRIPTNAME = "Tainted";
272
273
}

Kevin Atkinson's avatar
   
Kevin Atkinson committed
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
{
    #
    # Create a special class for keeping track of the process the
    # database handle was created.  This is needed so that the child
    # process after a fork() 1) set's InactiveDestroy to avoid sending
    # a disconnect message since it will also close the parent's
    # database handle 2) reconnects since two separate processes
    # shouldn't share the same handle.  (1) is handled via overridding
    # the database handle DESTROY method, (2) is handled in the
    # DBQueryN function.
    #
    package TestbedDBHandle;
    use vars '@ISA';
    @ISA = ('Mysql');
    @TestbedDBHandle::Statement::ISA = ('Mysql::Statement');
    my %DB_PID; # hash based on db handle
    sub obj_hash( $ ) {
	# Return a hex string of the location of the object in memory.
	# This is slightly better than just converting it to a scalar
	# as two objects as the scalar also included the class name
	# the object is "blessed" into which might change over time
	sprintf("0x%x", $_[0]); 
    }
    sub MakeA ( $ ) {
	my ($obj) = @_;
	bless ($obj);
	$DB_PID{obj_hash($obj)} = $$;
    }
    sub db_pid () {
	my ($self) = @_;
	return $DB_PID{obj_hash($self)};
    }
    sub DESTROY {
	my ($self) = @_;
	if ($self->db_pid() != $$) {
	    $self->setInactiveDestroy(1);
	}
	delete $DB_PID{obj_hash($self)};
	$self->SUPER::DESTROY() if $self->can("SUPER::DESTROY");
    }
}

316
#
317
# Set up for querying the database. Note that fork causes a reconnect
Mac Newbold's avatar
Mac Newbold committed
318
# to the DB in the child.
319
#
Kevin Atkinson's avatar
   
Kevin Atkinson committed
320
my @DB;
321
322
323
324
325
326
$DBQUERY_MAXTRIES  = 1;
$DBQUERY_RECONNECT = 1;
$DBCONN_MAXTRIES   = 5;
$DBCONN_EXITONERR  = 1;
@EXPORT_OK         = qw($DBQUERY_MAXTRIES $DBQUERY_RECONNECT
			$DBCONN_EXITONERR $DBCONN_MAXTRIES);
327

Kevin Atkinson's avatar
   
Kevin Atkinson committed
328
sub TBDBConnect($)
329
{
Kevin Atkinson's avatar
   
Kevin Atkinson committed
330
    my ($dbnum) = @_;
331
    my $maxtries = $DBCONN_MAXTRIES;
332
333
334
335
336
337
338
339
340

    #
    # Construct a 'username' from the name of this script and the user who
    # ran it. This is for accounting purposes.
    #
    my $name = getpwuid($UID);
    if (!$name) {
	$name = "uid$UID";
    }
341
    my $dbuser = "$SCRIPTNAME:$name:$PID";
342

343
    while ($maxtries) {
Kevin Atkinson's avatar
   
Kevin Atkinson committed
344
	$DB[$dbnum] = Mysql->connect("localhost", $DBNAME, $dbuser, "none");
Kevin Atkinson's avatar
   
Kevin Atkinson committed
345
        TestbedDBHandle::MakeA($DB[$dbnum]);
Kevin Atkinson's avatar
   
Kevin Atkinson committed
346
	if (defined($DB[$dbnum])) {
347
348
	    last;
	}
349
	$maxtries--;
350
351
352
353
	if ($maxtries) {
	    print STDERR "Cannot connect to DB; trying again in 5 seconds!\n";
	    sleep(5);
	}
354
    }
Kevin Atkinson's avatar
   
Kevin Atkinson committed
355
    if (!defined($DB[$dbnum])) {
356
357
358
359
	print STDERR
	    "Cannot connect to DB after $DBQUERY_MAXTRIES attempts!\n";
	return -1
	    if (! $DBCONN_EXITONERR);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
360
	exit(-1);
361
    }
Kevin Atkinson's avatar
   
Kevin Atkinson committed
362
    $DB[$dbnum]->{'dbh'}->{'PrintError'} = 0;
363
    $Mysql::QUIET = 1;
364
    return 0;
365
}
Kevin Atkinson's avatar
   
Kevin Atkinson committed
366
TBDBConnect(0);
367

368
# Old version. Should be renamed or just eventfork.
369
370
sub TBdbfork()
{
371
372
373
    if ($EVENTSYS) {
	EventFork();
    }
374
375
}

376
# New version.
377
sub TBDBReconnect($)
378
{
379
380
381
382
383
384
385
386
387
388
389
390
    my ($retry) = @_;
    my ($exitonerr,$maxtries);
    
    if ($retry) {
	$exitonerr = $DBCONN_EXITONERR;
	$DBCONN_EXITONERR = 0;
	
	# And we want to keep trying for a long time!
	$maxtries = $DBCONN_MAXTRIES;
	$DBCONN_MAXTRIES  = 10000;
    }

391
392
393
394
395
    for (my $i = 0; $i < @DB; $i++) {
	undef($DB[$i]);
	return -1
	    if (TBDBConnect($i) != 0);
    }
396
397
398
399
400
401
402

    if ($retry) {
	$DBCONN_EXITONERR = $exitonerr;
	$DBCONN_MAXTRIES  = $maxtries;
    }
    #print "Reconnected to DB in process $PID\n";
   
403
404
405
    return 0;
}

406
407
408
# To avoid keeping a mysql connection around.
sub TBDBDisconnect()
{
Kevin Atkinson's avatar
   
Kevin Atkinson committed
409
410
411
    for (my $i = 0; $i < @DB; $i++) {
	undef($DB[$i]);
    }
412
    select(undef, undef, undef, 0.2);
413
414
}

Kevin Atkinson's avatar
   
Kevin Atkinson committed
415
416
417
418
419
420
421
# Create a new DB handle and return the handle number
sub NewTBDBHandle() {
    my $dbnum = @DB;
    TBDBConnect($dbnum);
    return $dbnum;
}

422
423
424
425
426
#
# Record last DB error string.
#
my $DBErrorString = "";

427
428
429
430
#
# Needs to be config'ed.
#
sub TBDB_EXPT_WORKDIR()		{ "/usr/testbed/expwork"; }
Mac Newbold's avatar
Mac Newbold committed
431

432
433
434
435
436
#
# 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.
#
437
sub NODERELOADING_PID()		{ $TBOPSPID; }
438
sub NODERELOADING_EID()		{ "reloading"; }
439
sub NODERELOADPENDING_EID()	{ "reloadpending"; }
Timothy Stack's avatar
   
Timothy Stack committed
440
441
442
sub NODEREPOSITIONING_PID()	{ $TBOPSPID; }
sub NODEREPOSITIONING_EID()	{ "repositioning"; }
sub NODEREPOSPENDING_EID()	{ "repositionpending"; }
443
sub NODEDEAD_PID()		{ $TBOPSPID; }
444
sub NODEDEAD_EID()		{ "hwdown"; }
445
446
sub PLABMOND_PID()		{ $TBOPSPID; }
sub PLABMOND_EID()		{ "plab-monitor"; }
Kirk Webb's avatar
   
Kirk Webb committed
447
448
sub PLABTESTING_PID()		{ $TBOPSPID; }
sub PLABTESTING_EID()		{ "plab-testing"; }
449
sub PLABHOLDING_PID()		{ $TBOPSPID; }
Kirk Webb's avatar
   
Kirk Webb committed
450
sub PLABHOLDING_EID()		{ "plabnodes"; }
Kirk Webb's avatar
   
Kirk Webb committed
451
sub PLABDOWN_PID()		{ $TBOPSPID; }
Kirk Webb's avatar
   
Kirk Webb committed
452
sub PLABDOWN_EID()		{ "hwdown"; }
453
454
sub OLDRESERVED_PID()		{ $TBOPSPID; }
sub OLDRESERVED_EID()		{ "oldreserved"; }
455
456
sub NFREELOCKED_PID()		{ $TBOPSPID; }
sub NFREELOCKED_EID()		{ "nfree-locked"; }
Robert Ricci's avatar
Robert Ricci committed
457
sub TBOPSPID()			{ $TBOPSPID; }
458
sub EXPTLOGNAME()		{ $EXPTLOGNAME; }
459
460
461
462
463
464

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

465
466
467
468
sub NODEFAILMODE_FATAL()	{ "fatal"; }
sub NODEFAILMODE_NONFATAL()	{ "nonfatal"; }
sub NODEFAILMODE_IGNORE()	{ "ignore"; }

469
# Experiment states
470
471
472
sub EXPTSTATE_NEW()		{ "new"; }
sub EXPTSTATE_PRERUN()		{ "prerunning"; }
sub EXPTSTATE_SWAPPED()		{ "swapped"; }
473
sub EXPTSTATE_QUEUED()		{ "queued"; }
474
475
476
sub EXPTSTATE_SWAPPING()	{ "swapping"; }
sub EXPTSTATE_ACTIVATING()	{ "activating"; }
sub EXPTSTATE_ACTIVE()		{ "active"; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
477
sub EXPTSTATE_PANICED()		{ "paniced"; }
478
479
sub EXPTSTATE_TERMINATING()	{ "terminating"; }
sub EXPTSTATE_TERMINATED()	{ "ended"; }
480
481
482
483
484
485
486
sub EXPTSTATE_MODIFY_PARSE()	{ "modify_parse"; }
sub EXPTSTATE_MODIFY_REPARSE()	{ "modify_reparse"; }
sub EXPTSTATE_MODIFY_RESWAP()	{ "modify_reswap"; }
sub EXPTSTATE_RESTARTING()	{ "restarting"; }
# For the batch_daemon.
sub BATCHSTATE_LOCKED()		{ "locked";}
sub BATCHSTATE_UNLOCKED()	{ "unlocked";}
487

488
# Cancel flags
489
490
491
sub EXPTCANCEL_CLEAR()		{ 0 ;}
sub EXPTCANCEL_TERM()		{ 1 ;}
sub EXPTCANCEL_SWAP()		{ 2 ;}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
492

493
494
sub USERSTATUS_ACTIVE()		{ "active"; }
sub USERSTATUS_FROZEN()		{ "frozen"; }
495
496
497
sub USERSTATUS_UNAPPROVED()	{ "unapproved"; }
sub USERSTATUS_UNVERIFIED()	{ "unverified"; }
sub USERSTATUS_NEWUSER()	{ "newuser"; }
498

499
500
501
#
# We want valid project membership to be non-zero for easy membership
# testing. Specific trust levels are encoded thusly.
Mac Newbold's avatar
Mac Newbold committed
502
#
503
504
sub PROJMEMBERTRUST_NONE()	{ 0; }
sub PROJMEMBERTRUST_USER()	{ 1; }
505
sub PROJMEMBERTRUST_ROOT()	{ 2; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
506
507
508
509
510
511
512
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!
Mac Newbold's avatar
Mac Newbold committed
513
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
514
515
516
517
518
519
# 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; }
520
sub TB_NODEACCESS_MODIFYVLANS()	{ 6; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
521
sub TB_NODEACCESS_MIN()		{ TB_NODEACCESS_READINFO; }
522
sub TB_NODEACCESS_MAX()		{ TB_NODEACCESS_MODIFYVLANS; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
523
524
525
526
527
528
529

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

530
# Experiments.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
531
532
533
sub TB_EXPT_READINFO()		{ 1; }
sub TB_EXPT_MODIFY()		{ 2; }
sub TB_EXPT_DESTROY()		{ 3; }
534
sub TB_EXPT_UPDATE()		{ 4; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
535
sub TB_EXPT_MIN()		{ TB_EXPT_READINFO; }
536
sub TB_EXPT_MAX()		{ TB_EXPT_UPDATE; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
537
538
539
540
541

# Projects.
sub TB_PROJECT_READINFO()	{ 1; }
sub TB_PROJECT_MAKEGROUP()	{ 2; }
sub TB_PROJECT_EDITGROUP()	{ 3; }
Chad Barb's avatar
   
Chad Barb committed
542
sub TB_PROJECT_GROUPGRABUSERS() { 4; }
Chad Barb's avatar
   
Chad Barb committed
543
544
545
546
547
548
549
550
551
552
sub TB_PROJECT_BESTOWGROUPROOT(){ 5; }
sub TB_PROJECT_DELGROUP()	{ 6; }
sub TB_PROJECT_LEADGROUP()	{ 7; }
sub TB_PROJECT_ADDUSER()	{ 8; }
sub TB_PROJECT_DELUSER()	{ 9; }
sub TB_PROJECT_MAKEOSID()	{ 10; }
sub TB_PROJECT_DELOSID()	{ 11; }
sub TB_PROJECT_MAKEIMAGEID()	{ 12; }
sub TB_PROJECT_DELIMAGEID()	{ 13; }
sub TB_PROJECT_CREATEEXPT()	{ 14; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
553
554
555
sub TB_PROJECT_MIN()		{ TB_PROJECT_READINFO; }
sub TB_PROJECT_MAX()		{ TB_PROJECT_CREATEEXPT; }

Mac Newbold's avatar
Mac Newbold committed
556
# OSIDs
Leigh B. Stoller's avatar
Leigh B. Stoller committed
557
558
559
560
561
562
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; }

563
564
# Magic OSID constants
sub TB_OSID_MBKERNEL()          { "_KERNEL_"; } # multiboot kernel OSID
565
566
567
568

# Magic MFS constants
sub TB_OSID_FREEBSD_MFS()	{ "FREEBSD-MFS" };
sub TB_OSID_FRISBEE_MFS()	{ "FRISBEE-MFS" };
569

Leigh B. Stoller's avatar
Leigh B. Stoller committed
570
# ImageIDs
571
572
573
574
575
#
# Clarification:
# READINFO is read-only access to the image and its contents
# (This is what people get for shared images)
# ACCESS means complete power over the image and its [meta]data
Leigh B. Stoller's avatar
Leigh B. Stoller committed
576
577
578
579
580
581
582
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; }
583

584
# Node Log Types
585
586
587
588
sub TB_NODELOGTYPE_MISC		{ "misc"; }
sub TB_NODELOGTYPES()		{ ( TB_NODELOGTYPE_MISC ) ; }
sub TB_DEFAULT_NODELOGTYPE()	{ TB_NODELOGTYPE_MISC; }

589
590
591
592
593
# Node History Stuff.
sub TB_NODEHISTORY_OP_FREE	{ "free"; }
sub TB_NODEHISTORY_OP_ALLOC	{ "alloc"; }
sub TB_NODEHISTORY_OP_MOVE	{ "move"; }

594
595
596
# Reload Types.
sub TB_RELOADTYPE_NETDISK()	{ "netdisk"; }
sub TB_RELOADTYPE_FRISBEE()	{ "frisbee"; }
597
sub TB_DEFAULT_RELOADTYPE()	{ TB_RELOADTYPE_FRISBEE; }
598

599
600
601
602
603
604
605
# Experiment priorities.
sub TB_EXPTPRIORITY_LOW()	{ 0; }
sub TB_EXPTPRIORITY_HIGH()	{ 20; }

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

606
607
608
# System PID.
sub TB_OPSPID()			{ $TBOPSPID; }

609
#
610
611
612
613
# Events we may want to send
#
sub TBDB_TBEVENT_NODESTATE	{ "TBNODESTATE"; }
sub TBDB_TBEVENT_NODEOPMODE	{ "TBNODEOPMODE"; }
614
sub TBDB_TBEVENT_CONTROL	{ "TBCONTROL"; }
615
sub TBDB_TBEVENT_COMMAND	{ "TBCOMMAND"; }
616
sub TBDB_TBEVENT_EXPTSTATE	{ "TBEXPTSTATE"; }
617
618
619
620

#
# For nodes, we use this set of events.
#
621
sub TBDB_NODESTATE_ISUP()	{ "ISUP"; }
622
sub TBDB_NODESTATE_ALWAYSUP()	{ "ALWAYSUP"; }
623
624
625
626
627
sub TBDB_NODESTATE_REBOOTED()	{ "REBOOTED"; }
sub TBDB_NODESTATE_REBOOTING()	{ "REBOOTING"; }
sub TBDB_NODESTATE_SHUTDOWN()	{ "SHUTDOWN"; }
sub TBDB_NODESTATE_BOOTING()	{ "BOOTING"; }
sub TBDB_NODESTATE_TBSETUP()	{ "TBSETUP"; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
628
629
sub TBDB_NODESTATE_RELOADSETUP(){ "RELOADSETUP"; }
sub TBDB_NODESTATE_MFSSETUP()   { "MFSSETUP"; }
630
sub TBDB_NODESTATE_TBFAILED()	{ "TBFAILED"; }
631
632
sub TBDB_NODESTATE_RELOADING()	{ "RELOADING"; }
sub TBDB_NODESTATE_RELOADDONE()	{ "RELOADDONE"; }
633
sub TBDB_NODESTATE_RELOADDONE_V2(){ "RELOADDONEV2"; }
634
sub TBDB_NODESTATE_UNKNOWN()	{ "UNKNOWN"; };
635
sub TBDB_NODESTATE_PXEWAIT()	{ "PXEWAIT"; }
636
637
sub TBDB_NODESTATE_PXEWAKEUP()	{ "PXEWAKEUP"; }
sub TBDB_NODESTATE_PXEBOOTING()	{ "PXEBOOTING"; }
638
sub TBDB_NODESTATE_POWEROFF()	{ "POWEROFF"; }
639

640
sub TBDB_NODEOPMODE_ANY		{ "*"; } # A wildcard opmode
641
642
643
644
sub TBDB_NODEOPMODE_NORMAL	{ "NORMAL"; }
sub TBDB_NODEOPMODE_DELAYING	{ "DELAYING"; }
sub TBDB_NODEOPMODE_UNKNOWNOS	{ "UNKNOWNOS"; }
sub TBDB_NODEOPMODE_RELOADING	{ "RELOADING"; }
645
646
647
sub TBDB_NODEOPMODE_NORMALv1	{ "NORMALv1"; }
sub TBDB_NODEOPMODE_MINIMAL	{ "MINIMAL"; }
sub TBDB_NODEOPMODE_RELOAD	{ "RELOAD"; }
648
sub TBDB_NODEOPMODE_RELOADMOTE	{ "RELOAD-MOTE"; }
649
sub TBDB_NODEOPMODE_DELAY	{ "DELAY"; }
650
sub TBDB_NODEOPMODE_BOOTWHAT	{ "_BOOTWHAT_"; } # A redirection opmode
651
652
sub TBDB_NODEOPMODE_UNKNOWN	{ "UNKNOWN"; }

653
654
655
656
657
sub TBDB_COMMAND_REBOOT         { "REBOOT"; }
sub TBDB_COMMAND_POWEROFF       { "POWEROFF"; }
sub TBDB_COMMAND_POWERON        { "POWERON"; }
sub TBDB_COMMAND_POWERCYCLE     { "POWERCYCLE"; }

658
659
660
661
sub TBDB_STATED_TIMEOUT_REBOOT  { "REBOOT"; }
sub TBDB_STATED_TIMEOUT_NOTIFY  { "NOTIFY"; }
sub TBDB_STATED_TIMEOUT_CMDRETRY{ "CMDRETRY"; }

Chad Barb's avatar
   
Chad Barb committed
662
663
664
sub TBDB_ALLOCSTATE_FREE_CLEAN()       { "FREE_CLEAN"; }
sub TBDB_ALLOCSTATE_FREE_DIRTY()       { "FREE_DIRTY"; }
sub TBDB_ALLOCSTATE_DOWN()             { "DOWN"; }
665
sub TBDB_ALLOCSTATE_DEAD()             { "DEAD"; }
Chad Barb's avatar
   
Chad Barb committed
666
667
668
sub TBDB_ALLOCSTATE_RELOAD_TO_FREE()   { "RELOAD_TO_FREE"; }
sub TBDB_ALLOCSTATE_RELOAD_PENDING()   { "RELOAD_PENDING"; }
sub TBDB_ALLOCSTATE_RES_RELOAD()       { "RES_RELOAD"; }
Chad Barb's avatar
   
Chad Barb committed
669
670
sub TBDB_ALLOCSTATE_RES_REBOOT_DIRTY() { "RES_REBOOT_DIRTY"; }
sub TBDB_ALLOCSTATE_RES_REBOOT_CLEAN() { "RES_REBOOT_CLEAN"; }
671
672
sub TBDB_ALLOCSTATE_RES_INIT_DIRTY()   { "RES_INIT_DIRTY"; }
sub TBDB_ALLOCSTATE_RES_INIT_CLEAN()   { "RES_INIT_CLEAN"; }
Chad Barb's avatar
   
Chad Barb committed
673
sub TBDB_ALLOCSTATE_RES_READY()        { "RES_READY"; }
674
sub TBDB_ALLOCSTATE_RES_RECONFIG()     { "RES_RECONFIG"; }
675
sub TBDB_ALLOCSTATE_RES_TEARDOWN()     { "RES_TEARDOWN"; }
Chad Barb's avatar
   
Chad Barb committed
676
677
sub TBDB_ALLOCSTATE_UNKNOWN()          { "UNKNOWN"; };

678
679
sub TBDB_TBCONTROL_RESET	{ "RESET"; }
sub TBDB_TBCONTROL_RELOADDONE	{ "RELOADDONE"; }
680
sub TBDB_TBCONTROL_RELOADDONE_V2{ "RELOADDONEV2"; }
681
sub TBDB_TBCONTROL_TIMEOUT	{ "TIMEOUT"; }
Mac Newbold's avatar
Mac Newbold committed
682
683
684
sub TBDB_TBCONTROL_PXEBOOT	{ "PXEBOOT"; }
sub TBDB_TBCONTROL_BOOTING	{ "BOOTING"; }
sub TBDB_TBCONTROL_CHECKGENISUP	{ "CHECKGENISUP"; }
685
686
687
688

# Constant we use for the timeout field when there is no timeout for a state
sub TBDB_NO_STATE_TIMEOUT	{ 0; }

689
690
691
692
693
694
#
# 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"; }

695
696
697
#
# We should list all of the DB limits.
#
698
sub DBLIMIT_NSFILESIZE()	{ (2**24 - 1); }
699

700
701
702
703
704
705
706
707
708
709
710
#
# Virtual nodes must operate within a restricted port range. The range
# is effective across all virtual nodes in the experiment. When an
# experiment is swapped in, allocate a subrange from this and setup
# all the vnodes to allocate from that range. We tell the user this
# range so this they can set up their programs to operate in that range.
#
sub TBDB_LOWVPORT()		{ 30000; }
sub TBDB_MAXVPORT()		{ 60000; }
sub TBDB_PORTRANGE()		{ 256;   }

711
712
713
714
715
716
717
718
#
# STATS constants.
#
sub TBDB_STATS_PRELOAD()	{ "preload"; }
sub TBDB_STATS_START()		{ "start"; }
sub TBDB_STATS_TERMINATE()	{ "destroy"; }
sub TBDB_STATS_SWAPIN()		{ "swapin"; }
sub TBDB_STATS_SWAPOUT()	{ "swapout"; }
719
sub TBDB_STATS_SWAPMODIFY()	{ "swapmod"; }
720
sub TBDB_STATS_FLAGS_IDLESWAP()	{ 0x01; }
721
sub TBDB_STATS_FLAGS_PREMODIFY(){ 0x02; }
722
sub TBDB_STATS_FLAGS_START()    { 0x04; }
723
sub TBDB_STATS_FLAGS_PRESWAPIN(){ 0x08; }
724
sub TBDB_STATS_FLAGS_BATCHCTRL(){ 0x10; }
725
# Do not export these variables!
726
my $TBDB_STATS_STARTCLOCK;
727
my $TBDB_STATS_SAVEDSWAPUID;
728

729
730
731
732
# Jail.
sub TBDB_JAILIPBASE()		{ "@JAILIPBASE@"; }
sub TBDB_JAILIPMASK()		{ "@JAILIPMASK@"; }

733
734
735
736
# Reserved node "roles"
sub TBDB_RSRVROLE_NODE()	{ "node"; }
sub TBDB_RSRVROLE_VIRTHOST()	{ "virthost"; }
sub TBDB_RSRVROLE_DELAYNODE()	{ "delaynode"; }
737
sub TBDB_RSRVROLE_SIMHOST()	{ "simhost"; }
738

739
740
741
742
743
# Interfaces roles.
sub TBDB_IFACEROLE_CONTROL()	{ "ctrl"; }
sub TBDB_IFACEROLE_EXPERIMENT()	{ "expt"; }
sub TBDB_IFACEROLE_JAIL()	{ "jail"; }
sub TBDB_IFACEROLE_FAKE()	{ "fake"; }
744
sub TBDB_IFACEROLE_GW()		{ "gw"; }
745
sub TBDB_IFACEROLE_OTHER()	{ "other"; }
746
sub TBDB_IFACEROLE_OUTER_CONTROL(){ "outer_ctrl"; }
747

748
749
750
751
752
753
# Routertypes.
sub TBDB_ROUTERTYPE_NONE()	{ "none"; }
sub TBDB_ROUTERTYPE_OSPF()	{ "ospf"; }
sub TBDB_ROUTERTYPE_STATIC()	{ "static"; }
sub TBDB_ROUTERTYPE_MANUAL()	{ "manual"; }

754
# Key Stuff
755
sub TBDB_EVENTKEY($$)	{ TBExptUserDir($_[0],$_[1]) . "/tbdata/eventkey"; }
756
sub TBDB_WEBKEY($$)	{ TBExptUserDir($_[0],$_[1]) . "/tbdata/webkey"; }
757

758
759
760
761
762
# Regex stuff
sub TBDB_CHECKDBSLOT_NOFLAGS()	{ 0x0; }
sub TBDB_CHECKDBSLOT_WARN()	{ 0x1; }
sub TBDB_CHECKDBSLOT_ERROR()	{ 0x2; }

763
764
# Security Levels.
sub TBDB_SECLEVEL_GREEN()	{ 0; }
765
766
767
768
769
770
771
sub TBDB_SECLEVEL_BLUE()	{ 1; }
sub TBDB_SECLEVEL_YELLOW()	{ 2; }
sub TBDB_SECLEVEL_ORANGE()	{ 3; }
sub TBDB_SECLEVEL_RED()		{ 4; }

# This is the level at which we get extremely cautious when swapping out
sub TBDB_SECLEVEL_ZAPDISK()	{ TBDB_SECLEVEL_YELLOW; }
772

773
774
775
776
777
778
779
780
781
782
783
784
785
786
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
#
# A hash of all tables that contain information about physical nodes - the
# value for each key is the list of columns that could contain the node's ID.
#
sub TBDB_PHYSICAL_NODE_TABLES() {
    return (
	'current_reloads'	=> [ 'node_id' ],
	'delays'		=> [ 'node_id' ],
	'iface_counters'	=> [ 'node_id' ],
	'interfaces'		=> [ 'node_id' ],
	'interface_settings'	=> [ 'node_id' ],
	'last_reservation'	=> [ 'node_id' ],
	'linkdelays'		=> [ 'node_id' ],
	'location_info'		=> [ 'node_id' ],
	'next_reserve'		=> [ 'node_id' ],
	'node_activity'		=> [ 'node_id' ],
	'node_auxtypes'		=> [ 'node_id' ],
	'node_features'		=> [ 'node_id' ],
	'node_hostkeys'		=> [ 'node_id' ],
	'node_idlestats'	=> [ 'node_id' ],
	'node_status'   	=> [ 'node_id' ],
	'node_rusage'		=> [ 'node_id' ],
	'nodeipportnum'		=> [ 'node_id' ],
	'nodelog'		=> [ 'node_id' ],
	'nodes'			=> [ 'node_id', 'phys_nodeid' ],
	'nodeuidlastlogin'	=> [ 'node_id' ],
	'ntpinfo'		=> [ 'node_id' ],
	'outlets'		=> [ 'node_id' ],
	'partitions'		=> [ 'node_id' ],
	'plab_slice_nodes'	=> [ 'node_id' ],
	'port_counters'		=> [ 'node_id' ],
	'reserved'		=> [ 'node_id' ],
	'scheduled_reloads'	=> [ 'node_id' ],
	'state_triggers'	=> [ 'node_id' ],
	'switch_stacks'		=> [ 'node_id' ],
	'tiplines'		=> [ 'node_id' ],
	'tmcd_redirect'		=> [ 'node_id' ],
	'tunnels'		=> [ 'node_id' ],
	'uidnodelastlogin'	=> [ 'node_id' ],
	'v2pmap'		=> [ 'node_id' ],
813
	'vinterfaces'		=> [ 'node_id' ],
814
815
816
817
818
	'widearea_accounts'	=> [ 'node_id' ],
	'widearea_delays'	=> [ 'node_id1', 'node_id2' ],
	'widearea_nodeinfo'	=> [ 'node_id' ],
	'widearea_recent'	=> [ 'node_id1', 'node_id2' ],
	'wires'			=> [ 'node_id1', 'node_id2' ],
819
820
821
	'node_startloc'		=> [ 'node_id' ],
	'node_history'		=> [ 'node_id' ],
	'node_bootlogs'		=> [ 'node_id' ],
Kirk Webb's avatar
   
Kirk Webb committed
822
        'plab_mapping'          => [ 'node_id' ],
823
824
825
    );
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
826
827
828
829
830
831
832
833
834
835
836
837
838
839
#
# 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?
Mac Newbold's avatar
Mac Newbold committed
840
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    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);
    }
Mac Newbold's avatar
Mac Newbold committed
886

Leigh B. Stoller's avatar
Leigh B. Stoller committed
887
888
889
890
891
892
    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.
Mac Newbold's avatar
Mac Newbold committed
893
894
# Return that trust level as one of the numeric values above.
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
895
896
897
# usage: TBGrpTrust($dbuid, $pid, $gid)
#        returns numeric trust value if a group member.
#        returns PROJMEMBERTRUST_NONE if not a group member.
Mac Newbold's avatar
Mac Newbold committed
898
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
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();
Mac Newbold's avatar
Mac Newbold committed
922
    my $trust_string = $row[0];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
923
924
925
926
927
928
929
930
931
932
933

    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.
Mac Newbold's avatar
Mac Newbold committed
934
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
935
936
937
sub TBProjTrust($$)
{
    my ($uid, $pid) = @_;
Mac Newbold's avatar
Mac Newbold committed
938

Leigh B. Stoller's avatar
Leigh B. Stoller committed
939
940
941
    return TBGrpTrust($uid, $pid, $pid);
}

942
#
943
944
# Test admin status. Optional argument is the UID or Name to test. If not
# provided, then test the current UID.
945
#
946
947
948
# XXX Argument is *either* a numeric UID, or a string name.
#
# usage: TBAdmin([int or char* uid]);
949
950
#        returns 1 if an admin type.
#        returns 0 if a mere user.
Mac Newbold's avatar
Mac Newbold committed
951
#
952
953
954
sub TBAdmin(;$)
{
    my($uid) = @_;
955
    my($name);
956

957
958
959
960
    #
    # 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.
961
962
    # Also check with HTTP_ at the front of the name, since this is required
    # to get it through suexec from the web scripts.
963
    #
964
    if (!($ENV{WITH_TB_ADMIN_PRIVS} || $ENV{HTTP_WITH_TB_ADMIN_PRIVS})) {
965
966
967
	return 0;
    }

968
969
970
971
    if (!defined($uid)) {
	$uid = $UID;
    }

972
973
    #
    # Test if numeric. Map to name if it is.
Mac Newbold's avatar
Mac Newbold committed
974
    #
975
976
977
978
979
980
981
    if ($uid =~ /^[0-9]+$/) {
	($name) = getpwuid($uid)
	    or die "$uid not in passwd file\n";
    }
    else {
	$name = $uid;
    }
982
983

    my $query_result =
984
	DBQueryFatal("select admin from users where uid='$name'");
985
986
987
988
989
990
991
992

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

993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
#
# Test whether current user is a member of the emulab-ops project.
# 
sub TBOpsGuy(;$)
{
    my($uid) = @_;
    my($name);

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

    #
    # 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;
    }
    return TBMinTrust(TBProjTrust($name, $TBOPSPID), PROJMEMBERTRUST_USER());
}

1018
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1019
1020
# Project permission checks. The group id (gid) can be undef, in which case
# the pid is used (ie: a default group check is made).
1021
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1022
1023
1024
# Usage: TBProjAccessCheck($uid, $pid, $gid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
Mac Newbold's avatar
Mac Newbold committed
1025
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1026
sub TBProjAccessCheck($$$$)
1027
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1028
1029
    my ($uid, $pid, $gid, $access_type) = @_;
    my $mintrust;
1030

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1031
1032
1033
    if ($access_type < TB_PROJECT_MIN ||
	$access_type > TB_PROJECT_MAX) {
	die("*** Invalid access type: $access_type!");
1034
1035
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1036
1037
    #
    # Admins do whatever they want!
Mac Newbold's avatar
Mac Newbold committed
1038
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1039
1040
    if (TBAdmin($uid)) {
	return 1;
1041
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1042
1043
1044
1045
1046
1047
1048
    $uid = MapNumericUID($uid);

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1051
1052
1053
1054
1055
1056
    if ($access_type == TB_PROJECT_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    elsif ($access_type == TB_PROJECT_CREATEEXPT) {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }
1057
1058
1059
    elsif ($access_type == TB_PROJECT_DELUSER) {
	$mintrust = PROJMEMBERTRUST_PROJROOT;
    }
1060
1061
1062
1063
    elsif ($access_type == TB_PROJECT_MAKEGROUP ||
	   $access_type == TB_PROJECT_DELGROUP) {
	$mintrust = PROJMEMBERTRUST_GROUPROOT;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    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.
Mac Newbold's avatar
Mac Newbold committed
1077
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1078
1079
1080
1081
1082
1083
1084
1085
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!");
1086
1087
1088
    }

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1089
    # Admins do whatever they want!
Mac Newbold's avatar
Mac Newbold committed
1090
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1091
    if (TBAdmin($uid)) {
1092
1093
	return 1;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1094
    $uid = MapNumericUID($uid);
1095

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1096
    my $query_result =
1097
	DBQueryFatal("SELECT gid,expt_head_uid FROM experiments WHERE ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1098
		     "eid='$eid' and pid='$pid'");
Mac Newbold's avatar
Mac Newbold committed
1099

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1100
1101
1102
1103
    if ($query_result->numrows == 0) {
	return 0;
    }
    my @row = $query_result->fetchrow_array();
1104
1105
    my $gid     = $row[0];
    my $creator = $row[1];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1106

1107
1108
1109
    #
    # An experiment may be destroyed by the experiment creator or the
    # project/group leader.
Mac Newbold's avatar
Mac Newbold committed
1110
    #
1111
    if ($access_type == TB_EXPT_READINFO) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1112
1113
1114
1115
1116
1117
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

1118
1119
1120
1121
1122
1123
1124
    #
    # Either proper permission in the group, or group_root in the project.
    # This lets group_roots muck with other people's experiments, including
    # those in groups they do not belong to.
    #
    return TBMinTrust(TBGrpTrust($uid, $pid, $gid), $mintrust) ||
	TBMinTrust(TBGrpTrust($uid, $pid, $pid), PROJMEMBERTRUST_GROUPROOT);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1125
1126
1127
1128
1129
1130
1131
1132
}

#
# Determine if uid can access a node or list of nodes.
#
# Usage: TBNodeAccessCheck($uid, $access_type, $node_id, ...)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
Mac Newbold's avatar
Mac Newbold committed
1133
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
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!");
    }
1144
1145

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1146
    # Admins do whatever they want!