GeniCluster.pm.in 27.2 KB
Newer Older
1
2
3
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
#!/usr/bin/perl -wT
#
# Copyright (c) 2008-2016 University of Utah and the Flux Group.
# 
# {{{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;
54
55
use GeniCredential;
use GeniStd;
56
57
58
59
60
use English;
use Data::Dumper;
use Date::Parse;
use POSIX qw(strftime);
use Time::Local;
61
use File::Temp qw(tempfile);
62
use Project;
63
use NodeType;
64
65
66
67
68
69

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

#
# Check permission. At the moment, only the Mothership can issue requests
# and only the Cloudlab clusters will accept them.
#
80
sub CheckPermission($)
81
{
82
    my ($rootonly) = @_;
83
84
85
86
87
88
89
90
    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,
91
92
				"Only the Mothership or local cluster ".
				"can access this interface")
93
94
95
96
97
98
99
100
	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()));
101
102
103
104
105
106
107

    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
108
109
	       $OURDOMAIN eq "clemson.cloudlab.us" ||
	       $OURDOMAIN eq "lab.onelab.eu"));
110
111
112
113
114
115
116
117
118
119
120

    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()
{
121
    my $hasperm = CheckPermission(0);
122
123
124
125
126
127
128
129
130
131
132
    return $hasperm
	if (GeniResponse::IsError($hasperm));
	    
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $API_VERSION);
}

#
# Return the InUse info, which includes the pre-reserve info.
#
sub InUse()
{
133
    my $hasperm = CheckPermission(1);
134
135
    return $hasperm
	if (GeniResponse::IsError($hasperm));
136
137
138
139
140
141
    my $autoswap_max;
    if (!GetSiteVar("general/autoswap_max", \$autoswap_max)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
    # sitevar in hours, convert to seconds
    $autoswap_max *= 3600;
142
143
144
145

    my @blob = ();

    my $query_result =
146
147
148
149
150
	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, ".
151
152
		    "  u.uid,stats.slice_uuid,cert.urn,e.swappable, ".
		    "  s.lockdown,unix_timestamp(stats.swapin_last) ".
153
154
155
		    "  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 ".
156
157
158
159
160
161
162
163
		    "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 ".
164
165
		    "where n.role='testnode' and t.class='pc' ".
		    "order by n.node_id");
166
    while (my ($node_id,$type,$pid,$eid,$reserved_pid,$expires,
167
168
	       $autoswap,$ttl,$uid,$slice_uuid,$slice_urn,
	       $swappable,$slice_lockdown,$swapin_time) =
169
	   $query_result->fetchrow_array()) {
170
171
	my $maxttl;
	
172
173
174
175
176
	#
	# 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)) {
177
178
179
180
181
182
	    if ($slice_lockdown) {
		$ttl = "";
	    }
	    else {
		$ttl = $expires - time();
	    }
183
	}
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
	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 = "";
	    }
199
200
201
202
203
204
205
206
207
208
	}
	else {
	    $ttl = "";
	}
	push(@blob, {"node_id"      => $node_id,
		     "type"         => $type,
		     "pid"          => $pid || "",
		     "eid"          => $eid || "",
		     "uid"          => $uid || "",
		     "ttl"          => $ttl,
209
		     "maxttl"       => $maxttl || "",
210
211
		     "slice_urn"    => $slice_urn || "",
		     "slice_uuid"   => $slice_uuid || "",
212
213
		     "reserved_pid" => $reserved_pid || ""});
    }
214
215
216
217
    my $results = {"api_version"  => $API_VERSION,
		   "details"      => \@blob};
		  
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $results);
218
219
220
221
222
223
224
225
}

#
# Return pre-reservation details.
#
sub PreReservations()
{
    my @blob = ();
226
    my $hasperm = CheckPermission(1);
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
    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 ".
263
264
			"where reserved_pid='$pid' and ".
			"      reservation_name='$name'");
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
	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
281
282
	    last
		if (!defined($row));
283
284
285
286
287
288
	}
	push(@blob, {"nodes"        => \@nodes,
		     "pid"          => $pid,
		     "name"         => $name,
		     "count"        => $count,
		     "prereserved"  => \@prereserved,
Leigh B Stoller's avatar
Leigh B Stoller committed
289
		     "types"        => $types || "",
290
291
292
293
294
295
296
297
		     "priority"     => $priority,
		     "created"      => $created,
		     "creator"      => $creator,
		     "start"        => $start || "",
		     "end"          => $end || "",
		     "active"       => $active,
		     "terminal"     => $terminal,
	     });
Leigh B Stoller's avatar
Leigh B Stoller committed
298
299
300
	# We ate the last row.
	last
	    if (!defined($row));
301
302
303
304
305
306
307
308
309
	# 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);
}
310

311
312
313
314
315
316
317
318
319
#
# Return utilization data for the nodes in a slice.
#
sub SliceUtilizationData($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my %blob      = ();
    
320
    my $hasperm = CheckPermission(1);
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    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);
}

405
406
407
408
409
410
411
412
413
#
# Return utilization data for the nodes in a slice.
#
sub SliceIdleData($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my %blob      = ();
    
414
    my $hasperm = CheckPermission(1);
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    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();
437
    if (! open(IDLE, "$WAP $IDLESTATS -s -R -B -S '$limit' -e $pid,$eid |")) {
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
	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);
}

457
458
459
460
461
462
463
464
465
466
#
# 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      = ();

467
    my $hasperm = CheckPermission(1);
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    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);
}

517
518
519
520
521
522
523
524
525
526
527
#
# Check Reservation request for a slice. 
#
sub SliceCheckReservation($)
{
    my ($argref)  = @_;
    my $slice_urn = $argref->{'slice_urn'};
    my $expiration= $argref->{'expiration'};
    my %blob      = ();
    my $reserror;

528
    my $hasperm = CheckPermission(1);
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
    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);
}
556
557
558
559
560
561
562
563
564
565
566
567

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

568
    my $hasperm = CheckPermission(1);
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
    return $hasperm
	if (GeniResponse::IsError($hasperm));

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

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

585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#
# Attempt a reservation.
#
sub Reserve($)
{
    my ($argref)  = @_;
    my %blob      = ();
    my $reserror;

    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.
    #
    if (!exists($argref->{'credentials'})) {
	return GeniResponse->MalformedArgsResponse("Missing credentials")
    }
    my ($geniuser, $project) =
	Credential2UserProject($argref->{'credentials'});

    return $geniuser
	if (GeniResponse::IsResponse($geniuser));
615
616
    return GeniResponse->MalformedArgsResponse("Not a local user")
	if (!$geniuser->IsLocal());
617
618
619
620
621
622
623
624
625
626
627

    #
    # No project, we need to have a project urn.
    #
    if (!defined($project)) {
	return GeniResponse->MalformedArgsResponse("Missing project URN")
	    if (!exists($argref->{'project_urn'}));
	return GeniResponse->MalformedArgsResponse("Invalid project URN")
	    if (!GeniHRN::IsValid($argref->{'project_urn'}));
	my $hrn = GeniHRN->new($argref->{'project_urn'});
	return GeniResponse->MalformedArgsResponse("Mismatching project URN")
628
629
	    if ($hrn->domain() ne
		$geniuser->emulab_user()->nonlocalurn()->domain());
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707

	my $group = GeniUtil::GetHoldingProject($hrn,undef,1);
	return $group
	    if (GeniResponse::IsResponse($group));
	$project = $group->GetProject();
    }
    my $pid = $project->pid();
    my $uid = $geniuser->emulab_user()->uid();

    #
    # Required arguments.
    #
    foreach my $field ("count", "start", "end", "type") {
	return GeniResponse->MalformedArgsResponse("Missing $field")
	    if (! (exists($argref->{$field}) && $argref->{$field} ne ""));
    }
    my $count = $argref->{"count"};
    my $start = $argref->{"start"};
    my $end   = $argref->{"end"};
    my $type  = $argref->{"type"};
    my $check = (exists($argref->{"check"}) && $argref->{"check"} ? 1 : 0);
    my $reason= (exists($argref->{"reason"}) ? $argref->{"reason"} : undef);
    my $update= (exists($argref->{"update"}) ? $argref->{"update"} : undef);

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

    if (defined($reason) &&
	!TBcheck_dbslot($reason, "default", "tinytext",
			TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	return GeniResponse->MalformedArgsResponse("Invalid reason")
    }
    # Gack, why does Frontier do this. It is stupid.
    if (ref($start) eq 'Frontier::RPC2::DateTime::ISO8601') {
	$start = $start->value;
    }
    if (ref($end) eq 'Frontier::RPC2::DateTime::ISO8601') {
	$end = $end->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));
    $end = eval { timegm(strptime($end)); };
    if ($@) {
	return GeniResponse->MalformedArgsResponse("End time: $@");
    }
    return GeniResponse->MalformedArgsResponse("End time: Could not parse date")
	if (!defined($end));

    my $nodetype = NodeType->Lookup($type);
    return GeniResponse->SearchFailedResponse("No such type")
	if (!defined($type));

    #
    # It would be great to check permission here if an update, but without
    # a concept of remote admin, this is not possible.
    #
    if (defined($update)) {
	my $reservation = Reservation->Lookup($update);
	return GeniResponse->SearchFailedResponse("No such reservation")
	    if (!defined($reservation));
    }

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

    my $args = ($check ? "-n " : "") .
708
	(defined($update) ? "-m $update " : "") .
709
	"-T " . $webtask->task_id() . " ".
710
	"-U $uid -t $type -s $start -e $end $pid $count";
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830

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

    GeniUtil::FlipToElabMan();
    my $output = GeniUtil::ExecQuiet("$WAP $TB/sbin/reserve $args");
    
    if ($?) {
	GeniUtil::FlipToGeniUser();
	$webtask->Refresh();
	my $code = $webtask->code();
	my $mesg = $webtask->output();
	$webtask->Delete();
	if (!defined($mesg)) {
	    $mesg = $output;
	}
	return GeniResponse->Create(GENIRESPONSE_REFUSED, $code, $mesg);
    }
    GeniUtil::FlipToGeniUser();
    $webtask->Delete();
    return GeniResponse->Create(GENIRESPONSE_SUCCESS);
}

#
# 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+$/);
    }

    #
    # If the root authority is asking, then no perm checks are necessary.
    # and 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.
    #
    if (!exists($argref->{'credentials'})) {
	my $hrn = GeniHRN->new($ENV{"GENIURN"});
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN)
	    if (! ($hrn->IsAuthority() && $hrn->IsRoot()));
	
	$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;
831
832
	$blob->{"project"}     = $project->nonlocalurn();
	$blob->{"user"}        = $user->nonlocalurn();
833
834
835
836
837
838
839
840
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
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
	$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'} || "";
	$results{"$idx"}       = $blob;
    }
    my $blob = {"api_version"  => $API_VERSION,
		"reservations" => \%results,
    };
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
}

#
# Delete a reservation.
#
sub DeleteReservation($)
{
    my ($argref)  = @_;
    my $project;

    my $hasperm = CheckPermission(0);
    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+$/);

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

    my $urn = $argref->{"project"};
    return GeniResponse->MalformedArgsResponse("Illegal project URN")
	if (!GeniHRN::IsValid($urn));
    my $hrn = GeniHRN->new($urn);

    if ($hrn->domain() eq $OURDOMAIN) {
	$project = Project->Lookup($hrn->id());
    }
    else {
	#
	# We got a project URN but we need to lookup using the SA urn.
	#
	my $purn = GeniHRN::Generate($hrn->authority(), "authority", "sa");
	$project = Project->LookupNonLocal($purn);
    }
    return GeniResponse->MalformedArgsResponse("No such project")
	if (!$project);

    my $reservation = Reservation->Lookup($idx);
    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED)
	if (!defined($reservation));

    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN)
	if ($reservation->pid() ne $project->pid());
    
    $reservation->Cancel() == 0
	or GeniResponse->Create(GENIRESPONSE_ERROR);
    
    return GeniResponse->Create(GENIRESPONSE_SUCCESS);
}

#
# Map a project credential to local user/project.
#
sub Credential2UserProject($)
{
    my ($credentials) = @_;

    my ($credential,$speaksfor) = GeniStd::CheckCredentials($credentials);
    return $credential
	if (GeniResponse::IsResponse($credential));

    return GeniResponse->MalformedArgsResponse("Not a project/user credential")
	if ($credential->target_urn()->type() ne "project" &&
	    $credential->target_urn()->type() ne "user");

    #
    # This will create a local user if it does not exist.
    #
    my $geniuser = GeniCM::CreateUserFromCertificate($credential);
    return $geniuser
	if (GeniResponse::IsResponse($geniuser));
    return ($geniuser)
	if ($credential->target_urn()->type() eq "user");	
    
    #
    # This will create a local project if it does not exist. 
    #
    my $group =
	GeniUtil::GetHoldingProject($credential->target_urn(), $geniuser, 1);
    return $group
	if (GeniResponse::IsResponse($group));
    
    return ($geniuser, $group->GetProject());
}

936
937
# _Always_ make sure that this 1 is at the end of the file...
1;