GeniCluster.pm.in 36.5 KB
Newer Older
1
2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2008-2017 University of Utah and the Flux Group.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#
package GeniCluster;

#
# Portal stuff.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use emdb;
44
use emutil;
45
use WebTask;
46
47
48
use libtestbed;
use libEmulab;
use GeniResponse;
49
use GeniSlice;
50
use GeniCM;
51
use GeniHRN;
52
use GeniUtil;
53
use Reservation;
Leigh B Stoller's avatar
Leigh B Stoller committed
54
use libadminctrl;
55
56
use GeniCredential;
use GeniStd;
57
58
59
60
61
use English;
use Data::Dumper;
use Date::Parse;
use POSIX qw(strftime);
use Time::Local;
62
use File::Temp qw(tempfile);
63
use Project;
64
use NodeType;
65
use Node;
66
67
68
69
70
71

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $MAINSITE 	   = @TBMAINSITE@;
my $OURDOMAIN      = "@OURDOMAIN@";
72
73
my $IDLESTATS      = "$TB/bin/idlestats";
my $SUDO           = "/usr/local/bin/sudo";
74
my $SSH            = "/usr/bin/ssh";
75
my $WAP            = "$TB/sbin/withadminprivs";
76
77
78
79
80
81
my $API_VERSION    = 1.0;

#
# Check permission. At the moment, only the Mothership can issue requests
# and only the Cloudlab clusters will accept them.
#
82
sub CheckPermission($)
83
{
84
    my ($rootonly) = @_;
85
86
87
88
89
90
91
92
    my $myurn = $ENV{"MYURN"};

    my $hrn = GeniHRN->new($ENV{"GENIURN"});
    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				"Could not parse GENIURN")
	if (!defined($hrn));
    
    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
93
94
				"Only the Mothership or local cluster ".
				"can access this interface")
95
96
97
98
99
100
101
102
	if (! ($hrn->authority() eq "emulab.net" ||
	       $hrn->authority() eq $OURDOMAIN));

    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				"Only the root authority ".
				"can access this interface")
	if (defined($rootonly) && $rootonly &&
	    ! ($hrn->IsAuthority() && $hrn->IsRoot()));
103

104
105
106
107
108
109
110
    #
    # Allow the local cluster to talk to itself via this interface.
    # Otherwise must be one of the known Cloudlab clusters.
    #
    return 0
	if ($hrn->authority() eq $OURDOMAIN);

111
112
113
114
115
116
    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
			"Only Cloudlab clusters permit this interface")
	if (! ($OURDOMAIN eq "emulab.net" ||
	       $OURDOMAIN eq "apt.emulab.net" ||
	       $OURDOMAIN eq "utah.cloudlab.us" ||
	       $OURDOMAIN eq "wisc.cloudlab.us" ||
Leigh B Stoller's avatar
Leigh B Stoller committed
117
	       $OURDOMAIN eq "clemson.cloudlab.us" ||
118
	       $OURDOMAIN eq "utahddc.geniracks.net" ||
Leigh B Stoller's avatar
Leigh B Stoller committed
119
	       $OURDOMAIN eq "lab.onelab.eu"));
120
121
122
123
124
125
126
127
128
129
130

    return 0;
}

#
# Tell the client what API revision we support.  The correspondence
# between revision numbers and API features is to be specified elsewhere.
# No credentials are required.
#
sub GetVersion()
{
131
    my $hasperm = CheckPermission(0);
132
133
134
135
136
137
    return $hasperm
	if (GeniResponse::IsError($hasperm));
	    
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $API_VERSION);
}

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
#
# Create user/authority from a credential. We need to do this to support
# admin level operations that require that the target user ans authority
# already exist for the purposes of bookkeeping. But they cannot be
# created during the admin level operation since the creds/certs will not
# be what we expect. I do not much like this, but no brighter ideas at
# this time.
#
# So, the caller will make this call just to get the local user/authority
# into the database, and then issue the actual call as the root authority.
# And only admins at the permitted sites (CheckPermission() above) can do
# that.
#
sub CreateUser($)
{
    my ($argref)  = @_;
    
    my $hasperm = CheckPermission(0);
    return $hasperm
	if (GeniResponse::IsError($hasperm));
	    
    if (!exists($argref->{'credentials'})) {
	return GeniResponse->MalformedArgsResponse("Missing credentials")
    }
    my $credentials = $argref->{'credentials'};	
    
    my ($credential,$speaksfor) = GeniStd::CheckCredentials($credentials);
    return $credential
	if (GeniResponse::IsResponse($credential));

    return GeniResponse->MalformedArgsResponse("Not a user credential")
	if ($credential->target_urn()->type() ne "user");
    
    my $geniuser = GeniCM::CreateUserFromCertificate($credential);
    return $geniuser
	if (GeniResponse::IsResponse($geniuser));

    return GeniResponse->Create(GENIRESPONSE_SUCCESS);
}

178
179
180
181
182
#
# Return the InUse info, which includes the pre-reserve info.
#
sub InUse()
{
183
    my $hasperm = CheckPermission(1);
184
185
    return $hasperm
	if (GeniResponse::IsError($hasperm));
186
187
188
189
190
191
    my $autoswap_max;
    if (!GetSiteVar("general/autoswap_max", \$autoswap_max)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
    # sitevar in hours, convert to seconds
    $autoswap_max *= 3600;
192
193
194
195

    my @blob = ();

    my $query_result =
196
197
198
199
200
	DBQueryWarn("select n.node_id,n.type,r.pid,r.eid,n.reserved_pid,".
		    "  unix_timestamp(s.expires),e.autoswap, ".
		    "  (e.autoswap_timeout - ".
		    "   ((unix_timestamp(now()) - ".
		    "     unix_timestamp(stats.swapin_last))/60)) as ttl, ".
201
202
		    "  u.uid,stats.slice_uuid,cert.urn,e.swappable, ".
		    "  s.lockdown,unix_timestamp(stats.swapin_last) ".
203
204
205
		    "  from nodes as n ".
		    "left join reserved as r on r.node_id=n.node_id ".
		    "left join node_types as t on t.type=n.type ".
206
207
208
209
210
211
212
213
		    "left join experiments as e on e.idx=r.exptidx ".
		    "left join experiment_stats as stats on ".
		    "     stats.exptidx=e.idx ".
		    "left join `geni-cm`.geni_slices as s on ".
		    "     s.uuid=stats.slice_uuid ".
		    "left join `geni-cm`.geni_certificates as cert on ".
		    "     cert.uuid=stats.slice_uuid ".
		    "left join users as u on u.uid_idx=e.swapper_idx ".
214
215
		    "where n.role='testnode' and t.class='pc' ".
		    "order by n.node_id");
216
    while (my ($node_id,$type,$pid,$eid,$reserved_pid,$expires,
217
218
	       $autoswap,$ttl,$uid,$slice_uuid,$slice_urn,
	       $swappable,$slice_lockdown,$swapin_time) =
219
	   $query_result->fetchrow_array()) {
220
221
	my $maxttl;
	
222
223
224
225
226
	#
	# Try and compute a time the node will be released. This is a guess
	# at best, lots of things can change as soon as we calculate it.
	#
	if (defined($expires)) {
227
228
229
230
231
232
	    if ($slice_lockdown) {
		$ttl = "";
	    }
	    else {
		$ttl = $expires - time();
	    }
233
	}
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
	elsif (defined($eid)) {
	    if (!$swappable) {
		$ttl = "";
	    }
	    elsif ($autoswap && defined($ttl)) {
		$ttl = $ttl * 60;
		$maxttl = $autoswap_max - (time() - $swapin_time);
		if ($ttl > $maxttl) {
		    # Admin override.
		    $maxttl = $ttl;
		}
	    }
	    else {
		$ttl = "";
	    }
249
250
251
252
253
254
255
256
257
258
	}
	else {
	    $ttl = "";
	}
	push(@blob, {"node_id"      => $node_id,
		     "type"         => $type,
		     "pid"          => $pid || "",
		     "eid"          => $eid || "",
		     "uid"          => $uid || "",
		     "ttl"          => $ttl,
259
		     "maxttl"       => $maxttl || "",
260
261
		     "slice_urn"    => $slice_urn || "",
		     "slice_uuid"   => $slice_uuid || "",
262
263
		     "reserved_pid" => $reserved_pid || ""});
    }
264
265
266
267
    my $results = {"api_version"  => $API_VERSION,
		   "details"      => \@blob};
		  
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $results);
268
269
270
271
272
273
274
275
}

#
# Return pre-reservation details.
#
sub PreReservations()
{
    my @blob = ();
276
    my $hasperm = CheckPermission(1);
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
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    my $query_result =
	DBQueryWarn("select p.*,nr.node_id,n.type as node_type".
		    "  from project_reservations as p ".
		    "left join node_reservations as nr on ".
		    "     nr.pid_idx=p.pid_idx and ".
		    "     nr.reservation_name=p.name ".
		    "left join nodes as n on n.node_id=nr.node_id ".
		    "order by p.pid,p.name,n.node_id");

    return GeniResponse->Create(GENIRESPONSE_ERROR)
	if (!$query_result);

    while (my $row = $query_result->fetchrow_hashref()) {
      nextpid:
	my @nodes    = ();
	my $pid      = $row->{'pid'};
	my $name     = $row->{'name'};
	my $count    = $row->{'count'};
	my $priority = $row->{'priority'};
	my $active   = $row->{'active'};
	my $terminal = $row->{'terminal'};
	my $types    = $row->{'types'};
	my $creator  = $row->{'creator'};
	my $created  = TBDateStringGMT($row->{'created'});
	my $start    = TBDateStringGMT($row->{'start'})
	    if (defined($row->{'start'}));
	my $end      = TBDateStringGMT($row->{'end'})
	    if (defined($row->{'end'}));
	my @prereserved = ();

	# Which nodes have actually been pre-reserved.
	my $current_result =
	    DBQueryWarn("select node_id,type from nodes ".
313
314
			"where reserved_pid='$pid' and ".
			"      reservation_name='$name'");
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
	return GeniResponse->Create(GENIRESPONSE_ERROR)
	    if (!$current_result);
	while (my ($node_id, $ntype) = $current_result->fetchrow_array()) {
	    push(@prereserved,
		 {"node_id" => $node_id, "type" => $ntype});
	}
	#
	# If this is a reservation for specific node(s), eat those rows.
	#
	while (defined($row->{'node_id'}) &&
	       $row->{'pid'} eq $pid && $row->{'name'} eq $name) {
	    push(@nodes,
		 {"node_id" => $row->{'node_id'},
		  "type"    => $row->{'node_type'}});
	    
	    $row = $query_result->fetchrow_hashref();
Leigh B Stoller's avatar
Leigh B Stoller committed
331
332
	    last
		if (!defined($row));
333
334
335
336
337
338
	}
	push(@blob, {"nodes"        => \@nodes,
		     "pid"          => $pid,
		     "name"         => $name,
		     "count"        => $count,
		     "prereserved"  => \@prereserved,
Leigh B Stoller's avatar
Leigh B Stoller committed
339
		     "types"        => $types || "",
340
341
342
343
344
345
346
347
		     "priority"     => $priority,
		     "created"      => $created,
		     "creator"      => $creator,
		     "start"        => $start || "",
		     "end"          => $end || "",
		     "active"       => $active,
		     "terminal"     => $terminal,
	     });
Leigh B Stoller's avatar
Leigh B Stoller committed
348
349
350
	# We ate the last row.
	last
	    if (!defined($row));
351
352
353
354
355
356
357
358
359
	# We ate the first row of the next reservation.
	goto nextpid
	    if (! ($row->{'pid'} eq $pid && $row->{'name'} eq $name));
    }
    my $results = {"api_version"  => $API_VERSION,
		   "details"      => \@blob};
		  
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $results);
}
360

361
362
363
364
365
366
367
368
369
#
# Return utilization data for the nodes in a slice.
#
sub SliceUtilizationData($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my %blob      = ();
    
370
    my $hasperm = CheckPermission(1);
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
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    my $slice = GeniSlice->Lookup($slice_urn);    
    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (!defined($slice));
    
    my $experiment = $slice->GetExperiment();
    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				"No experiment for $slice")
	if (!defined($experiment));

    my @nodes = $experiment->NodeList(0, 1);
    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				"No nodes is $slice")
	if (!@nodes);

    #
    # Build up a per-type summary count, to which we will add the
    # current total/free counts. 
    #
    my %typelist = ();
    
    foreach my $node (@nodes) {
	my %stats = ();
	$stats{"nodetype"} = $node->type();

	# Type counts.
	if (!exists($typelist{$node->type()})) {
	    $typelist{$node->type()} = {"count" => 0};
	}
	$typelist{$node->type()}->{"count"}++;
	
	my ($idletime, $staleness, $stale) = $node->IdleData();
	if (defined($idletime)) {
	    $stats{"idledata"} = {
		"idletime"   => $idletime,
		"staleness"  => $staleness,
		"stale"      => $stale,
	    };
	}
	$stats{"eventstate"} = $node->eventstate();

	my $rusage = $node->RusageData();
	if (defined($rusage)) {
	    $stats{"rusage"} = $rusage;
	}
	my ($status,$status_stamp) = $node->GetStatus();
	if (defined($status)) {
	    $stats{"status"} = {
		"status"    => $status,
		"timestamp" => $status_stamp,
	    };
	}
	$blob{$node->node_id()} = \%stats;
    }
    #
    # Finish up the per-type info, adding total/inuse/preserved.
    #
    foreach my $type (keys(%typelist)) {
	my $typeinfo = NodeType->Lookup($type);
	next
	    if (!defined($typeinfo));

	if ($typeinfo->isvirtnode()) {
	    $typelist{$typeinfo->type()}->{"total"} = 0;
	    $typelist{$typeinfo->type()}->{"free"}  = 0;
	    next;
	}
	
	my $counts = $typeinfo->Counts();
	if (defined($counts)) {
	    $typelist{$typeinfo->type()}->{"total"} = $counts->{"total"};
	    $typelist{$typeinfo->type()}->{"free"}  = $counts->{"free"};
	}
    }
    my $results = {"api_version"  => $API_VERSION,
		   "typeinfo"     => \%typelist,
		   "details"      => {
		       "nodes" => \%blob,
		   }};
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $results);
}

455
456
457
458
459
460
461
462
463
#
# Return utilization data for the nodes in a slice.
#
sub SliceIdleData($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my %blob      = ();
    
464
    my $hasperm = CheckPermission(1);
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    my $slice = GeniSlice->Lookup($slice_urn);    
    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (!defined($slice));
    
    my $experiment = $slice->GetExperiment();
    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				"No experiment for $slice")
	if (!defined($experiment));

    my $pid  = $experiment->pid();
    my $eid  = $experiment->eid();
    my $swapped = str2time($experiment->swapin_last());
    my $limit   = time() - (3600 * 24 * 3);
    if ($limit < $swapped) {
	$limit = $swapped;
    }
    $limit = emutil::TBDateStringLocal($limit);

    GeniUtil::FlipToElabMan();
487
    if (! open(IDLE, "$WAP $IDLESTATS -s -R -B -S '$limit' -e $pid,$eid |")) {
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start idlestats")
    }
    my $output = "";
    while (<IDLE>) {
	$output .= $_;
    }
    if (! close(IDLE)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    ($! ? "Pipe error running idlestats: $!" :
				     "idlestats exited with $?") .
				    "\n" . $output);
    }
    #
    # We get a giant json encoded string back.
    #
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $output);
}

507
508
509
510
511
512
513
514
515
516
#
# Return openstack data for the nodes in a slice.
#
sub SliceOpenstackData($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my $client_id = $argref->{'client_id'};
    my %blob      = ();

517
    my $hasperm = CheckPermission(1);
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    if ($client_id !~ /^[-\w]+$/) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS)
    }

    my $slice = GeniSlice->Lookup($slice_urn);    
    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (!defined($slice));
    
    my $experiment = $slice->GetExperiment();
    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				"No experiment for $slice")
	if (!defined($experiment));
    my $node = $experiment->VnameToNode($client_id);
    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				"No such controller node for $slice")
	if (!defined($node));
    my $node_id = $node->node_id();

    my $sshopts  = "-o ServerAliveInterval=10 -o ServerAliveCountMax=1 ";
    $sshopts    .= "-o ConnectTimeout=10 ";
    $sshopts    .= "-o BatchMode=yes -o StrictHostKeyChecking=no ";
    my $sshcmd   = "cat /root/setup/cloudlab-openstack-stats.json";

    $EUID = $UID = 0;
    my $output = GeniUtil::ExecQuiet("$SUDO $SSH $sshopts $node_id '$sshcmd'");
    if ($?) {
	GeniUtil::FlipToGeniUser();
	print STDERR "Error getting json from $node_id: $output\n";
	#
	# See if it is cause the file does not exist, we want to tell
	# the caller so it does not keep asking.
	#
	if ($output =~ /No such file/im) {
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED, undef,
					"No json file on $node_id");
	}
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
			    "Error getting json from $node_id: $output");
    }
    GeniUtil::FlipToGeniUser();    
    #
    # We get a json encoded string back.
    #
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $output);
}

567
568
569
570
571
572
573
574
575
576
577
#
# Check Reservation request for a slice. 
#
sub SliceCheckReservation($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my $expiration= $argref->{'expiration'};
    my %blob      = ();
    my $reserror;

578
    my $hasperm = CheckPermission(1);
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    # Gack, why does Frontier do this. It is stupid.
    if (ref($expiration) eq 'Frontier::RPC2::DateTime::ISO8601') {
	$expiration = $expiration->value;
    }
    # Convert to a localtime.
    $expiration = eval { timegm(strptime($expiration)); };
    if ($@) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef, $@);
    }
    if (!defined($expiration)) {
	GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
			     "Could not parse expiration");
    }
    my $slice = GeniSlice->Lookup($slice_urn);    
    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (!defined($slice));

    if (Reservation->ExtendSlice($slice, $expiration, \$reserror, 1)) {
	Reservation->FlushAll();
	return GeniResponse->Create(GENIRESPONSE_REFUSED, undef, $reserror);
    }
    Reservation->FlushAll();
    return GeniResponse->Create(GENIRESPONSE_SUCCESS);
}
606
607
608
609
610
611
612
613
614
615
616
617

#
# Get maximum allowed extension for a slice.
#
sub SliceMaxExtension($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my %blob      = ();
    my $max;
    my $reserror;

618
    my $hasperm = CheckPermission(1);
619
620
621
622
623
624
625
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    my $slice = GeniSlice->Lookup($slice_urn);    
    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (!defined($slice));

626
627
628
629
630
631
632
633
634
635
    #
    # Make sure the experiment exists before calling into the Reservation
    # library, it does not like it when the slice is really new and not
    # fully setup yet.
    #
    my $experiment = $slice->GetExperiment();
    if (!defined($experiment)) {
	return GeniResponse->Create(GENIRESPONSE_BUSY);
    }

636
637
638
639
640
641
642
643
644
    if (Reservation->MaxSliceExtension($slice, \$max, \$reserror)) {
	Reservation->FlushAll();
	return GeniResponse->Create(GENIRESPONSE_REFUSED, undef, $reserror);
    }
    Reservation->FlushAll();
    $max = TBDateStringGMT($max);
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $max);
}

645
646
647
648
649
650
651
652
#
# Attempt a reservation.
#
sub Reserve($)
{
    my ($argref)  = @_;
    my %blob      = ();
    my $reserror;
653
654
    my $asadmin   = 0;
    my ($geniuser, $project);
655
656
657
658
659
660
661
662
663
664
665
666
667
668

    my $hasperm = CheckPermission(0);
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    #
    # We want to support admins creating reservations for projects they
    # are not a member of. But we need to have a local account for that
    # remote admin, and for that we need a user credential. But we also
    # need a local project, but for that we just need the project urn.
    #
    # Otherwise we get a project credential issued to a user in that
    # project.
    #
669
670
671
    if (exists($argref->{'credentials'})) {
	($geniuser, $project) =
	    Credential2UserProject($argref->{'credentials'});
672

673
674
675
676
677
678
679
680
681
682
683
684
	return $geniuser
	    if (GeniResponse::IsResponse($geniuser));
	return GeniResponse->MalformedArgsResponse("Not a local user")
	    if (!$geniuser->IsLocal());
    }
    else {
	#
	# Must be the root authority.
	#
	$hasperm = CheckPermission(1);
	return $hasperm
	    if (GeniResponse::IsError($hasperm));
685

686
687
	return GeniResponse->MalformedArgsResponse("Missing user URN")
	    if (!exists($argref->{'user_urn'}));
688
689
	return GeniResponse->MalformedArgsResponse("Missing project URN")
	    if (!exists($argref->{'project_urn'}));
690
691
	return GeniResponse->MalformedArgsResponse("Invalid user URN")
	    if (!GeniHRN::IsValid($argref->{'user_urn'}));
692
693
	return GeniResponse->MalformedArgsResponse("Invalid project URN")
	    if (!GeniHRN::IsValid($argref->{'project_urn'}));
694
695
696
697
698
	
	# User should already exist; the caller used CreateUser() above first.
	$geniuser = GeniUser->Lookup($argref->{'user_urn'}, 1);
	return GeniResponse->MalformedArgsResponse("No such user")
	    if (!defined($geniuser));
699

700
701
	my $group = GeniUtil::GetHoldingProject($argref->{'project_urn'},
						undef, 1);
702
703
704
	return $group
	    if (GeniResponse::IsResponse($group));
	$project = $group->GetProject();
705
	$asadmin = 1;
706
707
708
709
    }
    my $pid = $project->pid();
    my $uid = $geniuser->emulab_user()->uid();

710
711
712
713
714
    # Different rules for update.
    my $update = (exists($argref->{"update"}) ? $argref->{"update"} : undef);
    return GeniResponse->MalformedArgsResponse("Invalid update index")
	if (defined($update) && $update !~ /^\d+$/);
    
715
    #
716
    # Required arguments when not an update.
717
    #
718
719
720
    my ($count,$start,$end,$type);
    
    if (!$update) {
721
	foreach my $field ("count", "end", "type") {
722
723
724
725
	    return GeniResponse->MalformedArgsResponse("Missing $field")
		if (! (exists($argref->{$field}) && $argref->{$field} ne ""));
	}
	$count = $argref->{"count"};
726
	$start = $argref->{"start"} if (exists($argref->{"start"}));
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
	$end   = $argref->{"end"};
	$type  = $argref->{"type"};

	return GeniResponse->MalformedArgsResponse("Invalid type")
	    if ($type !~ /^[-\w]+$/);

	my $nodetype = NodeType->Lookup($type);
	return GeniResponse->SearchFailedResponse("No such node type")
	    if (!defined($type));
    }
    else {
	my $okay = 0;

	foreach my $field ("count", "start", "end") {
	    $okay = 1
		if (exists($argref->{$field}) && $argref->{$field} ne "");
	}
	return GeniResponse->MalformedArgsResponse("Missing update arguments")
	    if (!$okay);

	$count = $argref->{"count"} if (exists($argref->{"count"}));
	$start = $argref->{"start"} if (exists($argref->{"start"}));
	$end   = $argref->{"end"} if (exists($argref->{"end"}));
750
751
752
753
754
    }
    my $check = (exists($argref->{"check"}) && $argref->{"check"} ? 1 : 0);
    my $reason= (exists($argref->{"reason"}) ? $argref->{"reason"} : undef);

    return GeniResponse->MalformedArgsResponse("Invalid count")
755
	if (defined($count) && $count !~ /^\d+$/);
756
757

    if (defined($reason) &&
758
	!TBcheck_dbslot($reason, "default", "fulltext",
759
760
761
			TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	return GeniResponse->MalformedArgsResponse("Invalid reason")
    }
762
763
764
765
766
767
768
769
770
771
772
773
774
    if (defined($start)) {
	# Gack, why does Frontier do this. It is stupid.
	if (ref($start) eq 'Frontier::RPC2::DateTime::ISO8601') {
	    $start = $start->value;
	}
	# Convert to a localtime.
	$start = eval { timegm(strptime($start)); };
	if ($@) {
	    return GeniResponse->MalformedArgsResponse("Start time: $@");
	}
	return GeniResponse->MalformedArgsResponse("Start time: ".
						   "Could not parse date")
	    if (!defined($start));
775
    }
776
777
778
779
780
781
782
783
784
785
786
787
    if (defined($end)) {
	# Gack, why does Frontier do this. It is stupid.
	if (ref($end) eq 'Frontier::RPC2::DateTime::ISO8601') {
	    $end = $end->value;
	}
	$end = eval { timegm(strptime($end)); };
	if ($@) {
	    return GeniResponse->MalformedArgsResponse("End time: $@");
	}
	return GeniResponse->MalformedArgsResponse("End time: ".
						   "Could not parse date")
	    if (!defined($end));
788
789
790
791
792
793
    }

    if (defined($update)) {
	my $reservation = Reservation->Lookup($update);
	return GeniResponse->SearchFailedResponse("No such reservation")
	    if (!defined($reservation));
794
795
796

	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN)
	    if ($reservation->pid() ne $project->pid());
Leigh B Stoller's avatar
Leigh B Stoller committed
797

798
	$type = $reservation->type();
Leigh B Stoller's avatar
Leigh B Stoller committed
799
800
801
802
803
804
805
806
807
808
809
810
811
    }

    #
    # If admission control says they cannot have as many as wanted, then
    # the reservation is rejected.
    #
    if (defined($count)) {
	my $maximum = libadminctrl::MaximumAllowed($project, $type);
	if (defined($maximum)) {
	    if ($maximum < 0) {
		return GeniResponse->Create(GENIRESPONSE_ERROR);
	    }
	    if ($count > $maximum) {
Leigh B Stoller's avatar
Leigh B Stoller committed
812
813
		return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
					    "Admission Control says limited ".
Leigh B Stoller's avatar
Leigh B Stoller committed
814
815
816
					    "to $maximum nodes");
	    }
	}
817
818
819
820
821
822
823
824
    }

    # Use a webtask to get back output.
    my $webtask = WebTask->CreateAnonymous();
    return GeniResponse->Create(GENIRESPONSE_ERROR)
	if (!defined($webtask));

    my $args = ($check ? "-n " : "") .
825
	(defined($update) ? "-m $update " : "") .
826
	"-T " . $webtask->task_id() . " ".
Leigh B Stoller's avatar
Leigh B Stoller committed
827
	(!defined($update) ? "-t $type " : "") .
828
829
830
	(defined($start) ? "-s $start " : "") .
	(defined($end) ? "-e $end " : "") .
	(defined($update) && defined($count) ? "-S $count " : "") .
831
832
	($asadmin ? "-U $uid " : "") . 
	(!defined($update) ? "$pid $count" : "");
833
834
835
836
837
838
839
840
841

    # Write the reason to a tempfile to pass in. This will auto unlink.
    my $fp;
    if (defined($reason)) {
	$fp = File::Temp->new();
	print $fp $reason;
	$args = "-N $fp $args";
	chmod(0755, "$fp");
    }
842
843
    my $command = ($asadmin ? "$WAP " : "") . "$TB/sbin/reserve -p $args";
    print STDERR "$command\n";
844

845
846
847
848
849
850
851
852
    if ($asadmin) {
	GeniUtil::FlipToElabMan();
    }
    else {
	# We know this is a local user.
	$geniuser->FlipTo($project->GetProjectGroup());
    }
    my $output = GeniUtil::ExecQuiet($command);
853
    
854
    if ($? && $? >> 8 != 2) {
855
	GeniUtil::FlipToGeniUser();
Leigh B Stoller's avatar
Leigh B Stoller committed
856
	#print STDERR "$args\n";
857
858
859
860
861
862
863
864
865
	$webtask->Refresh();
	my $code = $webtask->code();
	my $mesg = $webtask->output();
	$webtask->Delete();
	if (!defined($mesg)) {
	    $mesg = $output;
	}
	return GeniResponse->Create(GENIRESPONSE_REFUSED, $code, $mesg);
    }
866
    my $approved = ($? >> 8 == 2 ? 0 : 1);
867
868
    GeniUtil::FlipToGeniUser();
    $webtask->Delete();
869
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $approved);
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
}

#
# Reservation list or just one.
#
sub Reservations($)
{
    my ($argref)  = @_;
    my %results   = ();
    my $reserror;
    my $query_result;
    my $idx;

    my $hasperm = CheckPermission(0);
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    if (exists($argref->{'idx'})) {
	$idx = $argref->{'idx'};

	return GeniResponse->MalformedArgsResponse("Invalid idx")
	    if ($idx !~ /^\d+$/);
    }

    #
895
896
897
898
899
900
    # If the root authority is asking, then we require a root certificate
    # like all the other restricted calls in this library. We send back
    # the entire list.
    #
    # Otherwise return only those reservations granted by the credential,
    # which should be a project credential or a user (self) credential.
901
902
    #
    if (!exists($argref->{'credentials'})) {
903
904
905
906
	# Root authority check.
	$hasperm = CheckPermission(1);
	return $hasperm
	    if (GeniResponse::IsError($hasperm));
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
	
	$query_result =
	    DBQueryWarn("select *,UNIX_TIMESTAMP(start) as start, ".
			"   UNIX_TIMESTAMP(end) as end, ".
			"   UNIX_TIMESTAMP(created) as created ".
			"  from future_reservations ".
			(defined($idx) ? "where idx='$idx' " : "") .
			"order BY start");
    }
    else {
	my $credentials = $argref->{'credentials'};	
	my ($geniuser,$project) = Credential2UserProject($credentials);

	return $geniuser
	    if (GeniResponse::IsResponse($geniuser));

	if (defined($project)) {
	    my $pid = $project->pid();
	    $query_result =
		DBQueryWarn("select *,UNIX_TIMESTAMP(start) as start, ".
			    "   UNIX_TIMESTAMP(end) as end, ".
			    "   UNIX_TIMESTAMP(created) as created ".
			    "  from future_reservations ".
			    "where pid='$pid' ".
			    (defined($idx) ? "and idx='$idx'" : ""));
	}
	else {
	    my $uid = $geniuser->uid();
	    $query_result =
		DBQueryWarn("select *,UNIX_TIMESTAMP(start) as start, ".
			    "   UNIX_TIMESTAMP(end) as end, ".
			    "   UNIX_TIMESTAMP(created) as created ".
			    "  from future_reservations ".
			    "where uid='$uid'");
	}
    }
    return GeniResponse->Create(GENIRESPONSE_ERROR)
	if (!$query_result);

    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (defined($idx) && !$query_result->numrows);

    while (my $row = $query_result->fetchrow_hashref()) {
	my $blob = {};
   	my $idx  = $row->{'idx'};
	my $pid  = $row->{'pid'};
	my $uid  = $row->{'uid'};
	
	my $project = Project->Lookup($pid);
	if (!defined($project)) {
	    print STDERR "Reservations: No such project $pid\n";
	    next;
	}
	my $user = User->Lookup($uid);
	if (!defined($user)) {
	    print STDERR "Reservations: No such user $uid\n";
	    next;
	}
	$blob->{"idx"}         = $idx;
966
967
	$blob->{"project"}     = $project->nonlocalurn();
	$blob->{"user"}        = $user->nonlocalurn();
968
969
970
971
972
973
974
	$blob->{"nodes"}       = $row->{'nodes'};
	$blob->{"type"}        = $row->{'type'};
	$blob->{"created"}     = TBDateStringGMT($row->{'created'});
	$blob->{"start"}       = TBDateStringGMT($row->{'start'});
	$blob->{"start"}       = TBDateStringGMT($row->{'start'});
	$blob->{"end"}         = TBDateStringGMT($row->{'end'});
	$blob->{"notes"}       = $row->{'notes'} || "";
975
	$blob->{"approved"}    = $row->{'approved'} || "";
976
977
978
979
980
981
982
983
	$results{"$idx"}       = $blob;
    }
    my $blob = {"api_version"  => $API_VERSION,
		"reservations" => \%results,
    };
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
}

984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Approve a pending reservation.
#
sub ApproveReservation($)
{
    my ($argref)  = @_;

    my $hasperm = CheckPermission(1);
    return $hasperm
	if (GeniResponse::IsError($hasperm));

    return GeniResponse->MalformedArgsResponse("Missing reservation ID")
	if (! (exists($argref->{"idx"}) && $argref->{"idx"} ne ""));

    my $idx = $argref->{"idx"};
    return GeniResponse->MalformedArgsResponse("Illegal reservation ID")
	if ($idx !~ /^\d+$/);
For faster browsing, not all history is shown. View entire blame