quickvm.in 18.8 KB
Newer Older
1
2
#!/usr/bin/perl -w
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2008-2014 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
# 
# {{{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.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
use XML::Simple;
use File::Temp qw(tempfile);
use Data::Dumper;

#
# Create a quick VM.
# 
sub usage()
{
42
    print "Usage: quickvm [-l] <xmlfile>\n";
43
    print "Usage: quickvm -k <uuid>\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
44
    print "Usage: quickvm -e <seconds> <uuid>\n";
45
46
    exit(1);
}
47
my $optlist = "dkve:l";
48
49
50
my $debug   = 0;
my $verbose = 1;
my $killit  = 0;
51
my $localuser = 0;;
52
my $xmlfile;
Leigh B Stoller's avatar
Leigh B Stoller committed
53
my $extend;
54
55
56
57
58
59
my $quickuuid;

# Protos
sub fatal($);
sub UserError($);
sub Terminate($);
Leigh B Stoller's avatar
Leigh B Stoller committed
60
sub Extend($$);
61
62
63
64
65
66
67
68
69
70
71
72

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $OURDOMAIN     = "@OURDOMAIN@";
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
my $SACERT	  = "$TB/etc/genisa.pem";
my $CMCERT	  = "$TB/etc/genicm.pem";
my $SSHKEYGEN     = "/usr/bin/ssh-keygen";
73
my $SSHSETUP      = "$TB/sbin/aptssh-setup";
74
75
76
77
78
79
80
81
82
83
84
85
86
87

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/site/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use libtestbed;
use libaudit;
Leigh B Stoller's avatar
Leigh B Stoller committed
88
use APT_Profile;
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use User;
use OSinfo;
use emutil;
use GeniDB;
use GeniUser;
use GeniCertificate;
use GeniCredential;
use GeniSlice;
use GeniAuthority;
use GeniHRN;
use Genixmlrpc;
use GeniResponse;

#
# 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{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verbose = 1;
}
116
117
118
if (defined($options{"l"})) {
    $localuser = 1;
}
119
120
121
if (defined($options{"k"})) {
    $killit = 1;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
122
123
124
if (defined($options{"e"})) {
    $extend = $options{"e"};
}
125
126
127
128
129
130
if (@ARGV != 1) {
    usage();
}
if ($killit) {
    $quickuuid = shift(@ARGV);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
131
132
133
134
135
136
elsif ($extend) {
    if ($extend !~ /^\d*$/) {
	usage();
    }
    $quickuuid = shift(@ARGV);
}
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
else {
    $xmlfile = shift(@ARGV);

    #
    # Check the filename when invoked from the web interface; must be a
    # file in /tmp.
    #
    if (getpwuid($UID) ne "nobody") {
	my $this_user = User->ThisUser();

	if (! defined($this_user)) {
	    fatal("You ($UID) do not exist!");
	}
	fatal("Only admins can run this script.")
	    if (!$this_user->IsAdmin());
    }
    else {
	if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	    $xmlfile = $1;
	}
	else {
	    fatal("Bad data in pathname: $xmlfile");
	}

	# Use realpath to resolve any symlinks.
	my $translated = `realpath $xmlfile`;
	if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	    $xmlfile = $1;
	}
	else {
	    fatal("Bad data in translated pathname: $xmlfile");
	}
    }
}

# Email record. 
Leigh B Stoller's avatar
Leigh B Stoller committed
173
AuditStart(0, undef)
174
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    if (! $debug);

# Connect to the SA DB.
DBConnect(GENISA_DBNAME());

#
# Load the SA cert to act as caller context.
#
my $sa_certificate = GeniCertificate->LoadFromFile($SACERT);
if (!defined($sa_certificate)) {
    fatal("Could not load certificate from $SACERT\n");
}
my $sa_authority = GeniAuthority->Lookup($sa_certificate->urn());
if (!defined($sa_authority)) {
    fatal("Could not load SA authority object");
}

#
# We want to contact our local CM to create the sliver.
# We use the normal XMLRPC route.
#
my $context = Genixmlrpc->Context($sa_certificate);
if (!defined($context)) {
    fatal("Could not create context to talk to CM");
}
Genixmlrpc->SetContext($context);

#
# Load the CM cert and authority, since that is who we talk to.
#
my $cm_certificate = GeniCertificate->LoadFromFile($CMCERT);
if (!defined($cm_certificate)) {
    fatal("Could not load certificate from $CMCERT\n");
}
my $cm_authority = GeniAuthority->Lookup($cm_certificate->urn());
if (!defined($cm_authority)) {
    fatal("Could not load CM authority object");
}

if ($killit) {
    exit(Terminate($quickuuid));
}
Leigh B Stoller's avatar
Leigh B Stoller committed
216
217
218
elsif ($extend) {
    exit(Extend($quickuuid, $extend));
}
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);
print STDERR Dumper($xmlparse)
    if ($debug || $verbose);

#
# Make sure all the required arguments were provided.
#
Leigh B Stoller's avatar
Leigh B Stoller committed
235
foreach my $key ("username", "email", "profile", "name") {
236
237
238
239
240
241
242
243
244
    fatal("Missing required attribute '$key'")
	if (! (exists($xmlparse->{'attribute'}->{"$key"}) &&
	       defined($xmlparse->{'attribute'}->{"$key"}) &&
	       $xmlparse->{'attribute'}->{"$key"} ne ""));
}

#
# Gather up args and sanity check.
#
Leigh B Stoller's avatar
Leigh B Stoller committed
245
my ($value, $user_urn, $user_uid, $user_hrn, $user_email, $sshkey, $profile);
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

#
# Username and email has to be acceptable to Emulab user system.
#
$value = $xmlparse->{'attribute'}->{"username"}->{'value'};
if (! TBcheck_dbslot($value, "users", "usr_name",
		     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
    fatal("Illegal username: $value");
}
$user_uid = $value;
$user_urn = GeniHRN::Generate("$OURDOMAIN", "user", $user_uid);
$user_hrn = "${PGENIDOMAIN}.${user_uid}";

$value = $xmlparse->{'attribute'}->{"email"}->{'value'};
if (! TBcheck_dbslot($value, "users", "usr_email",
		     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
    fatal("Illegal email address: $value");
}
$user_email = $value;

#
# Not many choices; see if it exists.
#
Leigh B Stoller's avatar
Leigh B Stoller committed
269
$value = $xmlparse->{'attribute'}->{"profile"}->{'value'};
Leigh B Stoller's avatar
Leigh B Stoller committed
270
271
if ($value !~ /^\d*$/) {
    fatal("Illegal imageid: $value");
272
}
Leigh B Stoller's avatar
Leigh B Stoller committed
273
274
my $profile_object = APT_Profile->Lookup($value);
if (!defined($profile_object)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
275
    fatal("No such profile: $value");
276
}
Leigh B Stoller's avatar
Leigh B Stoller committed
277
278
my $rspecstr = $profile_object->rspec();
$profile = $value;
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

#
# This is so the php code can look it up in the DB. Silly.
#
my $quickvm_name = $xmlparse->{'attribute'}->{"name"}->{'value'};
if ($quickvm_name !~ /^[\w]+$/) {
    fatal("Bad name: $quickvm_name");
}

#
# Use ssh-keygen to see if the key is valid and convertable. We first
# try to get the fingerprint, which will tells us if its already in
# openssh format. If not, try to convert it.
#
if (exists($xmlparse->{'attribute'}->{"sshkey"}) &&
    defined($xmlparse->{'attribute'}->{"sshkey"}) &&
    $xmlparse->{'attribute'}->{"sshkey"} ne "") {
    $sshkey = $xmlparse->{'attribute'}->{"sshkey"}->{'value'};
    my ($fh, $keyfile) = tempfile(UNLINK => 0);
    print $fh $sshkey;

    if (system("$SSHKEYGEN -l -f $keyfile >/dev/null 2>/dev/null")) {
	if (! open(KEYGEN, "$SSHKEYGEN -i -f $keyfile 2>/dev/null |")) {
	    fatal("Could not start ssh-keygen");
	}
	$sshkey = <KEYGEN>;
	if (!close(KEYGEN)) {
	    UserError("Could not parse ssh key!");
	}
	chomp($sshkey);
    }
}

#
# See if the GeniUser exists. Create if not, but that means we
# have to create an ssl certificate (which the user will never see)
# so that we can operate on behalf of the user (via speaksfor).
#
317
my $geniuser = GeniUser->Lookup($user_urn, $localuser);
318
if (!defined($geniuser)) {
319
320
321
    if ($localuser) {
	fatal("Could not lookup local user $user_urn");
    }
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
    #
    # Do not allow overlap with local users.
    #
    if (User->Lookup($user_uid)) {
	fatal("User $user_uid exists in the local user table");
    }

    #
    # New users must have a key.
    #
    if (!defined($sshkey)) {
	UserError("You must supply an ssh key!");
    }
    print "Geni user does not exist; creating one ...\n"
	if ($debug);

    #
    # Want to remember the auth token we emailed for later.
    #
    my $auth_token = $xmlparse->{'attribute'}->{"auth_token"}->{'value'};
    if ($auth_token !~ /^[\w]+$/) {
	fatal("Bad auth token: $auth_token");
    }

    my $certificate = GeniCertificate->Create({"urn"   => $user_urn,
					       "hrn"   => $user_hrn,
					       "email" => $user_email,
					       "showuuid" => 1});
    fatal("Could not create certificate")
	if (!defined($certificate));

    $geniuser = GeniUser->Create($certificate, $sa_authority);
    fatal("Could not create new geni user")
	if (!defined($geniuser));

    $geniuser->SetAuthToken($auth_token);

    #
Leigh B Stoller's avatar
Leigh B Stoller committed
360
    # Setup browser ssh.
361
    #
362
363
364
    system("$SSHSETUP " . $geniuser->uuid());
    fatal("Could not create ssh key pair")
	if ($?);
365
366
367
368
369
370
371
372
}
my $user_uuid = $geniuser->uuid();
# So we know this user has dome something lately.
$geniuser->BumpActivity();

# Remember key. For now we accept only one key. We store it simply
# so we can display it again for the user in the web interface.
# We allow key reuse for existing users, see above.
373
if (!$localuser && defined($sshkey)) {
374
375
376
377
    $geniuser->DeleteKeys();
    $geniuser->AddKey($sshkey);
}
# There will be "internal" keys ...
378
379
my @sshkeys;
if ($geniuser->GetKeyBundle(\@sshkeys) < 0 || !@sshkeys) {
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
455
456
457
458
459
460
461
462
463
464
465
466
467
    fatal("No ssh keys to use for $geniuser!");
}

#
# Now generate a slice registration and credential
#
my $slice_id   = "QV" . TBGetUniqueIndex('next_quickvm', 1);
my $slice_urn  = GeniHRN::Generate($OURDOMAIN, "slice", $slice_id);
my $slice_hrn  = "${PGENIDOMAIN}.${slice_id}";

#
# Make sure slice is unique. Probably retry here at some point. 
#
if (GeniSlice->Lookup($slice_hrn) || GeniSlice->Lookup($slice_urn)) {
    fatal("Could not form a unique slice name");
}
	    
#
# Generate a certificate for this new slice.
#
my $slice_certificate =
    GeniCertificate->Create({'urn'  => $slice_urn,
			     'hrn'  => $slice_hrn,
			     'showuuid' => 1,
			     'email'=> $user_email});

if (!defined($slice_certificate)) {
    fatal("Could not generate certificate for $slice_urn");
}
# Slice is created as locked.
my $slice = GeniSlice->Create($slice_certificate,
			      $geniuser, $sa_authority, undef, 1);
if (!defined($slice)) {
    $slice_certificate->Delete();
    fatal("Could not create new slice object for $slice_urn");
}
# These get quick expirations.
if ($slice->SetExpiration(time() + (3 * 3600)) != 0) {
    $slice->Delete();
    fatal("Could not set the slice expiration for $slice_urn");
}
my $slice_uuid = $slice->uuid();

# Create a slice credential
my $slice_credential =
    GeniCredential->CreateSigned($slice,
				 $geniuser,
				 $GeniCredential::LOCALSA_FLAG);
if (!defined($slice_credential)) {
    $slice->Delete();
    fatal("Could not create credential for $slice_urn");
}

#
# In order to connect as the SA instead of the user we just created,
# lets generate a speaksfor credential that allows the SA to speakfor
# for the new user. Fancy, eh?
#
my $speaksfor_credential = GeniCredential->Create($geniuser, $sa_authority);
fatal("Could not create speaksfor credential")
    if (!defined($speaksfor_credential));
$speaksfor_credential->SetType("speaksfor");
fatal("Could not sign speaksfor credential")
    if ($speaksfor_credential->Sign($GeniCredential::LOCALSA_FLAG));

#
# Got this far, lets create a quickvm record in the SA database.
# Mostly this for the web interface.
#
my $quickvm_uuid = NewUUID();
if (!defined($quickvm_uuid)) {
    fatal("Could not generate a new uuid");
}

sub SetQuickVMStatus($$)
{
    my ($uuid, $status) = @_;

    GeniDB::DBQueryWarn("update quickvms set status='$status' ".
			"where uuid='$uuid'")
	or return -1;

    return 0;
}

if (!GeniDB::DBQueryWarn("insert into quickvms set ".
			 "  uuid='$quickvm_uuid', slice_uuid='$slice_uuid', ".
			 "  creator_uuid='$user_uuid', status='created', ".
Leigh B Stoller's avatar
Leigh B Stoller committed
468
			 "  profile='$profile', name='$quickvm_name'")) {
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
517
518
519
520
521
522
523
    $slice->Delete();
    fatal("Could not create quickvm record");
}

#
# Exit and let caller poll for status.
#
if (!$debug) {
    my $child = fork();
    if ($child) {
	# Parent exits but avoid libaudit email.
	exit(0);
    }
    # Let parent exit;
    sleep(2);
    # All of the logging magic happens in here.
    libaudit::AuditFork();
}

#
# This creates the sliver and starts it.
#
my $response =
    Genixmlrpc::CallMethod($cm_authority->url(), undef,
			   "CreateSliver",
			   { "slice_urn"   => $slice_urn,
			     "rspec"       => $rspecstr,
			     "keys"        =>
				 [{'urn'   => $user_urn,
				   'login' => $user_uid,
				   'keys'  => \@sshkeys }],
			     "credentials" =>
				 [$slice_credential->asString(),
				  $speaksfor_credential->asString()]});

if (!defined($response) || $response->code() != GENIRESPONSE_SUCCESS) {
    $slice->Delete();
    fatal("CreateSliver failed: ".
	  (defined($response) ? $response->output() : "") . "\n");
}

#
# We are going to use the manifests table.
#
my $manifest = $response->value()->[1];
if (!defined($manifest)) {
    $slice->UnLock();
    SetQuickVMStatus($quickvm_uuid, "failed");
    fatal("Could not find the manifest in the response!");
}
my $safe_manifest = DBQuoteSpecial($manifest);
GeniDB::DBQueryWarn("update quickvms set ".
		    " status='provisioned', manifest=$safe_manifest ".
		    "where uuid='$quickvm_uuid'");

Leigh B Stoller's avatar
Leigh B Stoller committed
524
525
526
print STDERR "\n";
print STDERR "$manifest\n\n";

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
#
# but have to wait for the sliver to be ready, which means polling.
#
my $seconds  = 600;
my $interval = 15;
my $ready    = 0;
my $failed   = 0;

while ($seconds > 0) {
    sleep($interval);
    $seconds -= $interval;
    
    my $response =
	Genixmlrpc::CallMethod($cm_authority->url(), undef,
			       "SliverStatus",
			       { "slice_urn"   => $slice_urn,
				 "credentials" =>
				     [$slice_credential->asString(),
				      $speaksfor_credential->asString()]});

    if (!defined($response) || !defined($response->value()) ||
	($response->code() != GENIRESPONSE_SUCCESS &&
	 $response->code() != GENIRESPONSE_BUSY)) {
	fatal("SliverStatus failed: ".
	      (defined($response) ? $response->output() : "") . "\n");
    }
    next
	if ($response->code() == GENIRESPONSE_BUSY);

    my $blob = $response->value();
    if ($blob->{'status'} eq "ready") {
	$ready = 1;
	last;
    }
    elsif ($blob->{'status'} eq "failed") {
	$failed = 1;
	SetQuickVMStatus($quickvm_uuid, "failed");
	last;
    }
}
if ($failed) {
    fatal("$slice_urn failed."); 
}
elsif (!$ready) {
Leigh B Stoller's avatar
Leigh B Stoller committed
571
    SetQuickVMStatus($quickvm_uuid, "failed");
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
    fatal("$slice_urn timed out."); 
}
$slice->UnLock();
SetQuickVMStatus($quickvm_uuid, "ready");
exit(0);

sub fatal($) {
    my ($mesg) = $_[0];

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}
sub UserError($) {
    my($mesg) = $_[0];

    AuditAbort()
	if (!$debug);
    print $mesg;
    exit(1);
}

#
# Terminate a quick VM.
#
sub Terminate($)
{
    my ($uuid) = @_;
    my $safe_uuid = DBQuoteSpecial($uuid);

    my $query_result =
	DBQueryWarn("select * from quickvms where uuid=$safe_uuid");
    if (! ($query_result && $query_result->numrows)) {
	fatal("No such quick VM: $uuid");
    }
    my $row = $query_result->fetchrow_hashref();

609
    my $geniuser = GeniUser->Lookup($row->{'creator_uuid'}, 1);
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
650
651
652
653
654
655
    if (!defined($geniuser)) {
	fatal("No creator for quick VM: $uuid");
    }
    my $slice = GeniSlice->Lookup($row->{'slice_uuid'});
    if (!defined($slice)) {
	fatal("No slice for quick VM: $uuid");
    }
    # Create a slice credential
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
    if (!defined($slice_credential)) {
	fatal("Could not create credential for $slice");
    }
    my $speaksfor_credential = GeniCredential->Create($geniuser, $sa_authority);
    fatal("Could not create speaksfor credential")
	if (!defined($speaksfor_credential));
    $speaksfor_credential->SetType("speaksfor");
    fatal("Could not sign speaksfor credential")
	if ($speaksfor_credential->Sign($GeniCredential::LOCALSA_FLAG));

    SetQuickVMStatus($uuid, "terminating");

    #
    # Exit and let caller poll for status.
    #
    if (!$debug) {
	my $child = fork();
	if ($child) {
	    # Parent exits but avoid libaudit email.
	    exit(0);
	}
	# Let parent exit;
	sleep(2);
	# All of the logging magic happens in here.
	libaudit::AuditFork();
    }
    my $response =
	Genixmlrpc::CallMethod($cm_authority->url(), undef,
			       "DeleteSlice",
			       { "slice_urn"   => $slice->urn(),
				 "credentials" =>
				     [$slice_credential->asString(),
				      $speaksfor_credential->asString()]});

656
657
658
    if (!defined($response) ||
	($response->code() != GENIRESPONSE_SUCCESS &&
	 $response->code() != GENIRESPONSE_SEARCHFAILED)) {
659
660
661
662
663
664
665
	fatal("DeleteSlice failed: ".
	      (defined($response) ? $response->output() : "") . "\n");
    }
    $slice->Delete();
    DBQueryWarn("delete from quickvms where uuid=$safe_uuid");
    exit(0);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681

#
# Extend a quick VM.
#
sub Extend($$)
{
    my ($uuid, $seconds) = @_;
    my $safe_uuid = DBQuoteSpecial($uuid);

    my $query_result =
	DBQueryWarn("select * from quickvms where uuid=$safe_uuid");
    if (! ($query_result && $query_result->numrows)) {
	fatal("No such quick VM: $uuid");
    }
    my $row = $query_result->fetchrow_hashref();

682
    my $geniuser = GeniUser->Lookup($row->{'creator_uuid'}, 1);
Leigh B Stoller's avatar
Leigh B Stoller committed
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
    if (!defined($geniuser)) {
	fatal("No creator for quick VM: $uuid");
    }
    my $slice = GeniSlice->Lookup($row->{'slice_uuid'});
    if (!defined($slice)) {
	fatal("No slice for quick VM: $uuid");
    }

    # Need to update slice before creating new credential. 
    $slice->AddToExpiration($extend);
    my $new_expires = $slice->ExpirationGMT();
    
    # Create a slice credential
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
    if (!defined($slice_credential)) {
	fatal("Could not create credential for $slice");
    }
    my $speaksfor_credential = GeniCredential->Create($geniuser, $sa_authority);
    fatal("Could not create speaksfor credential")
	if (!defined($speaksfor_credential));
    $speaksfor_credential->SetType("speaksfor");
    fatal("Could not sign speaksfor credential")
	if ($speaksfor_credential->Sign($GeniCredential::LOCALSA_FLAG));

    my $response =
	Genixmlrpc::CallMethod($cm_authority->url(), undef,
			       "RenewSlice",
			       { "slice_urn"  => $slice->urn(),
				 "expiration" => $new_expires,
				 "credentials" =>
				     [$slice_credential->asString(),
				      $speaksfor_credential->asString()]});

    if (!defined($response) || $response->code() != GENIRESPONSE_SUCCESS) {
	fatal("RenewSlice failed: ".
	      (defined($response) ? $response->output() : "") . "\n");
    }
    $slice->SetExpiration($new_expires);
    exit(0);
}