manage_reservations.in 15.7 KB
Newer Older
1
2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-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
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
use CGI;
use POSIX ":sys_wait_h";
use Date::Parse;

#
# Back-end script to manage APT profiles.
#
sub usage()
{
    print("Usage: manage_reservations [-a <urn>] list [-u uid | -p pid]\n");
    print("Usage: manage_reservations [-a <urn>] delete pid idx\n");
40
41
    print("Usage: manage_reservations [-a <urn>] approve idx\n");
    print("Usage: manage_reservations [-a <urn>] systeminfo\n");
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    exit(-1);
}
my $optlist     = "dt:a:";
my $debug       = 0;
my $webtask_id;
my $webtask;
my $authority;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $OURDOMAIN	= "@OURDOMAIN@";
my $MYURN	= "urn:publicid:IDN+${OURDOMAIN}+authority+cm";

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use EmulabConstants;
use emdb;
use emutil;
76
use Brand;
77
78
79
80
81
82
83
84
use User;
use Project;
use Reservation;
use EmulabConstants;
use libEmulab;
use libtestbed;
use WebTask;
use APT_Geni;
85
use APT_Aggregate;
86
87
88
89
90
91
92
93
use GeniResponse;
use GeniUser;

# Protos
sub fatal($);
sub DoReserve();
sub DoList();
sub DoDelete();
94
95
sub DoApprove();
sub DoSystemInfo();
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
sub readfile($);

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not lookup webtask $webtask_id");
    }
    # Convenient.
    $webtask->AutoStore(1);
}
if (defined($options{"d"})) {
    $debug++;
}
if (@ARGV < 1) {
    usage();
}
my $action = shift(@ARGV);

#
# Default to local cluster
#
if (defined($options{"a"})) {
    $authority = APT_Geni::GetAuthority($options{"a"});
}
else {
    $authority = APT_Geni::GetAuthority($MYURN);
}
if (!defined($authority)) {
    fatal("Could not look up authority");
}
# For credentials.
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
my $geniuser = GeniUser->CreateFromLocal($this_user);

if ($action eq "reserve") {
    DoReserve();
}
elsif ($action eq "list") {
    DoList();
}
elsif ($action eq "delete") {
    DoDelete();
}
151
152
153
154
155
156
elsif ($action eq "approve") {
    DoApprove();
}
elsif ($action eq "systeminfo") {
    DoSystemInfo();
}
157
158
159
160
161
162
163
164
165
166
167
168
169
else {
    usage();
}
exit(0);

#
# Create a reservation.
#
sub DoReserve()
{
    #
    # We allow for a user or project argument.
    #
170
    my $optlist = "t:s:e:nN:u:p:";
171
172
    my ($start, $end, $type, $reason, $update);
    my $checkonly = 0;
173
174
    my $portal;
    my $brand;
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
    my %rpcargs = ();
    my $context;
    my ($credential,$speaksfor);
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV < 2);
    my $project = Project->Lookup($ARGV[0]);
    my $count   = $ARGV[1];

    if (defined($options{"s"})) {
	$start = $options{"s"};
    }
    if (defined($options{"e"})) {
	$end = $options{"e"};
    }
    if (defined($options{"t"})) {
	$type = $options{"t"};
    }
    if (defined($options{"u"})) {
	$update = $options{"u"};
    }
200
201
202
    if (defined($options{"p"})) {
	$portal = $options{"p"};
    }
203
204
205
206
207
208
209
    if (defined($options{"N"})) {
	$reason = readfile($options{"N"});
    }
    if (defined($options{"n"})) {
	$checkonly = 1;
    }
    usage()
210
	if (!defined($project));
211
212
213
214
215
    # Need brand for email. No portal argument means emulab brand.
    $brand = Brand->Create($portal);
    if (!defined($brand)) {
	fatal("Bad branding");
    }
216
217
218
    if (defined($update)) {
	usage()
	    if (! (defined($count) || defined($start) || defined($end)));
219
    }
220
221
    else {
	usage()
222
	    if (! (defined($count) && defined($type) && defined($end)));
223
224
225
226
227
228
229
	
	if ($type !~ /^[-\w]+$/) {
	    fatal("Type is not a string");
	}
    }
    if (defined($count) && $count !~ /^\d+$/) {
	fatal("Count is not an integer");
230
    }
231
232
233
    if (defined($start) &&
	!($start =~ /^\d+$/ || str2time($start))) {
	fatal("Start is not a unix timestamp or datetime");
234
    }
235
236
237
    if (defined($end) &&
	!($end =~ /^\d+$/ || str2time($end))) {
	fatal("End is not a unix timestamp or datetime");
238
    }
239
240
241
242
    $rpcargs{"start"} = TBDateStringGMT($start) if (defined($start));
    $rpcargs{"end"}   = TBDateStringGMT($end) if (defined($end));
    $rpcargs{"count"} = $count if (defined($count));
    $rpcargs{"type"}  = $type if (!defined($update));
243
244
245
246
247
248
249
250
251
252
253
    $rpcargs{"check"} = $checkonly;
    $rpcargs{"reason"}= $reason if (defined($reason));
    $rpcargs{"update"}= $update if (defined($update));
    
    $context = APT_Geni::GeniContext();
    if ($this_user->IsAdmin()) {
	#
	# We do not have a very good notion of cross site admin.
	#
	($credential,$speaksfor) =
	    APT_Geni::GenUserCredential($geniuser);
254
	$rpcargs{"project_urn"} = $project->urn()->asString();
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    }
    else {
	if (!$project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT())) {
	    fatal("No permission to access reservation list for $project")
	}
	($credential,$speaksfor) =
	    APT_Geni::GenProjectCredential($project, $geniuser);
    }
    fatal("Could not generate credentials")
	if (!defined($credential));
    my $credentials = [$credential->asString()];
    if (defined($speaksfor)) {
	$credentials = [@$credentials, $speaksfor->asString()];
    }
    $rpcargs{"credentials"} = $credentials;
    
    my $response =
	APT_Geni::PortalRPC($authority, $context, "Reserve", \%rpcargs);
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
    print Dumper($response);
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
    #
    # Exit with different status if the reservation is feasible but
    # needs to be approved. The value is a boolean indicating
    # approved.  Note that this applies even in "check" mode; the
    # approval code indicates if the request is feasible and will be
    # immediately approved.
    #
    if ($response->value()) {
	# approved right away
	exit(0);
    }
    #
    # Needs to be approved, exit with special status.
    #
    # If this was not $checkonly, then we want to send email locally
    # since the email was generated to the tbops but not the portal
    # email lists.
    #
    if (!$checkonly) {
	my $this_uid   = $this_user->uid();
	my $this_email = $this_user->email();
	my $url        = $brand->wwwBase() . "/list-reservations.php";
    
	$brand->SendEmail($brand->ExtensionsEmailAddress(),
	  "Pending reservation request needs approval",
	  "A reservation request was made by $this_uid, but it needs approval.".
	  "\n\n".
	  "See: $url", $this_email);
    }
    
    exit(2);
311
312
313
314
315
316
317
318
319
320
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
}

#
# Ask for a list of reservations.
#
sub DoList()
{
    #
    # We allow for a user or project argument.
    #
    my $optlist = "u:p:Ai:";
    my $anon    = 0;
    my $idx;
    my $project;
    my $user = $this_user;
    my %rpcargs = ();
    my $context;
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"A"})) {
	$anon = 1;
    }
    if (defined($options{"i"})) {
	$idx = $options{"i"};
    }
    if (defined($options{"u"})) {
	$user = User->Lookup($options{"u"});
	if (!defined($user)) {
	    fatal("No such user");
	}
	if (!$this_user->IsAdmin() && !$this_user->SameUser($user)) {
	    fatal("No permission to access reservation list for $user")
	}
	$geniuser = $this_user->CreateFromLocal($user);
    }
    if (defined($options{"p"})) {
	$project = Project->Lookup($options{"p"});

	if (!defined($project)) {
	    fatal("No such project");
	}
	if (!$this_user->IsAdmin() &&
	    !$project->AccessCheck($user, TB_PROJECT_CREATEEXPT())) {
	    fatal("No permission to access reservation list for $project")
	}
    }
    if ($this_user->IsAdmin() || $anon) {
	#
	# We do not have a very good notion of cross site admin. Get
	# the entire list, we will filter here.
	#
    }
    else {
	my ($credential,$speaksfor);
	
	if (defined($project)) {
	    ($credential,$speaksfor) =
		APT_Geni::GenProjectCredential($project, $geniuser);
	}
	else {
	    ($credential,$speaksfor) =
		APT_Geni::GenUserCredential($geniuser);
	}
	fatal("Could not generate credentials")
	    if (!defined($credential));
	
	my $credentials = [$credential->asString()];
	if (defined($speaksfor)) {
	    $credentials = [@$credentials, $speaksfor->asString()];
	}
	$rpcargs{"credentials"} = $credentials;
	$context = APT_Geni::GeniContext();
    }
    if (defined($idx)) {
	$rpcargs{"idx"} = $idx;
    }
    my $response =
	APT_Geni::PortalRPC($authority, $context, "Reservations", (\%rpcargs));
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
    my $list = $response->value()->{'reservations'};
    #
    # Map remote URNs to local projects and users. Not all of them can
    # be mapped of course, we leave those as is. 
    #
    foreach my $details (values(%$list)) {
404
	my $userhrn  = GeniHRN->new($details->{'user'});
405
406
407
408
409
	my $geniuser = GeniUser->Lookup($details->{'user'}, 1);
	if (defined(($geniuser))) {
	    $details->{'uid'}     = $geniuser->uid();
	    $details->{'uid_idx'} = $geniuser->uid_idx();
	}
410
411
412
	else {
	    $details->{'uid'}     = $userhrn->id();
	}
413
414
415
416
417
418
419
420
	my $projhrn = GeniHRN->new($details->{'project'});
	if ($projhrn->domain() eq $OURDOMAIN && defined($projhrn->project())) {
	    my $project = Project->Lookup($projhrn->project());
	    if (defined(($project))) {
		$details->{'pid'}     = $project->pid();
		$details->{'pid_idx'} = $project->pid_idx();
	    }
	}
421
422
423
	else {
	    $details->{'pid'} = $projhrn->id();
	}
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    }
    #
    # Strip out unwanted results if we asked as an admin for a specific
    # user or project.
    #
    if ($this_user->IsAdmin()) {

    }
    if (defined($webtask)) {
	$webtask->value($list);
	$webtask->Exited(0);
    }
    else {
	print Dumper($list);
    }
    exit(0);
}

#
# Delete a reservation.
#
sub DoDelete()
{
    usage()
	if (@ARGV != 2);
    my $pid = shift(@ARGV);
    my $idx = shift(@ARGV);
    
    # Check this since Reservation->Lookup() does not validate.
    fatal("Invalid index")
	if ($idx !~ /^\d+$/);

    my $project = Project->Lookup($pid);
    fatal("No such project")
	if (!defined($project));
    
    if (!$this_user->IsAdmin() &&
	!$project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT())) {
	fatal("No permission to access reservation list for $project")
    }
    my $response =
	APT_Geni::PortalRPC($authority, undef, "DeleteReservation",
			    {"idx" => $idx,
467
			     "project" => $project->urn()->asString()});
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    exit(0);
}

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
517
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
567
568
569
570
571
572
573
574
575
576
577
578
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
#
# Approve a reservation.
#
sub DoApprove()
{
    usage()
	if (@ARGV != 1);
    my $idx = shift(@ARGV);
    
    # Check this since Reservation->Lookup() does not validate.
    fatal("Invalid index")
	if ($idx !~ /^\d+$/);

    if (!$this_user->IsAdmin()) {
	fatal("No permission to approve reservations")
    }
    # PortalRPC will use the root context in this case, which is
    # essentially saying the caller is an admin.
    my $response =
	APT_Geni::PortalRPC($authority, undef, "ApproveReservation",
			    {"idx" => $idx});
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    exit(0);
}

#
# Get the reservation system info.
#
sub DoSystemInfo()
{
    my $optlist = "p:";
    my $portal;
    my $errmsg;
    my @aggregates = ($authority);
    my @webtasks   = ();

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"p"})) {
	$portal = $options{"p"}
    }
    usage()
	if (@ARGV);

    #
    # Portal argument says to ignore aggregate argument, and contact
    # all aggregates listed for the portal. 
    #
    if (defined($portal)) {
	@aggregates = ();
	
	my @list = APT_Aggregate->LookupForPortal($portal);
	foreach my $aggregate (@list) {
	    my $authority = APT_Geni::GetAuthority($aggregate->urn());
	    if (!defined($authority)) {
		$errmsg = "Cannot lookup authority for $aggregate";
		goto bad;
	    }
	    push(@aggregates, $authority);
	}
    }

    my $coderef = sub {
	my ($blob) = @_;
	my $authority = $blob->{"authority"};
	my $webtask   = $blob->{"webtask"};
	
	# PortalRPC will use the root context in this case, which is
	# essentially saying the caller is an admin. But thats okay
	# for this call, it is just informational.
	my $response =
	    APT_Geni::PortalRPC($authority, undef, "ReservationSystemInfo");
	
	if (GeniResponse::IsError($response)) {
	    #
	    # All errors are fatal.
	    #
	    if (defined($webtask)) {
		$webtask->output($response->output());
		$webtask->Exited(-1);
	    }
	    else {
		print STDERR $response->output() . "\n";
	    }
	    return -1;
	}
	if (defined($webtask)) {
	    $webtask->value($response->value());
	    $webtask->Exited(0);
	}
	return 0;
    };
    #
    # Multiple aggregates, we use parrun. We need a webtask for each
    # authority to communicate the results back to the parent, who
    # then combines them all.
    #
    my @return_codes = ();
    my @agglist = ();

    foreach my $auth (@aggregates) {
	my $temptask = WebTask->CreateAnonymous();
	# For delete below.
	push(@webtasks, $temptask);
	push(@agglist, {"authority" => $auth,
			"webtask"   => $temptask});
    }
    if (ParRun({"maxwaittime" => 60,
		"maxchildren" => scalar(@agglist)},
	    \@return_codes, $coderef, @agglist)) {
	#
	# The parent caught a signal. Leave things intact so that we can
	# kill things cleanly later.
	#
	$errmsg = "Internal error get reservation info";
	goto bad;
    }
    #
    # Check the exit codes, create return structure for the web interface.
    #
    my $blob = {};
    
    foreach my $agg (@agglist) {
	my $code  = shift(@return_codes);
	my $auth  = $agg->{'authority'};
	my $wtask = $agg->{'webtask'};

	$wtask->Refresh();

	if ($code) {
	    $errmsg  = $wtask->output();
	    goto bad;
	}
	$blob->{$auth->urn()} = $wtask->value();
    }
    if (defined($webtask)) {
	$webtask->value($blob);
	$webtask->Exited(0);
    }
    else {
	print Dumper($blob);
    }
    foreach my $temptask (@webtasks) {
	$temptask->Delete();
    }
    exit(0);

  bad:
    foreach my $temptask (@webtasks) {
	$temptask->Delete();
    }
    fatal($errmsg);
}

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
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->code(-1);
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

sub UserError($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->code(1);
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(1);
}

sub readfile($) {
    local $/ = undef;
    my ($filename) = @_;
    open(FILE, $filename) or fatal("Could not open $filename: $!");
    my $contents = <FILE>;
    close(FILE);
    return $contents;
}