quickvm.in 30.9 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
# 
# {{{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;
36
use Cwd qw(realpath);
37
38
39
40
41
42

#
# Create a quick VM.
# 
sub usage()
{
43
    print "Usage: quickvm [-u uuid] [-a aggregate] <xmlfile>\n";
44
    print "Usage: quickvm -k <uuid>\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
45
    print "Usage: quickvm -e <seconds> <uuid>\n";
46
    print "Usage: quickvm -s <uuid> <sliver_urn> <imagename>\n";
47
48
    exit(1);
}
49
my $optlist = "dkve:u:a:st:f";
50
51
52
my $debug   = 0;
my $verbose = 1;
my $killit  = 0;
53
54
my $utahddc = 1;
my $DDCURN  = "urn:publicid:IDN+utahddc.geniracks.net+authority+cm";
55
my $xmlfile;
Leigh B Stoller's avatar
Leigh B Stoller committed
56
my $extend;
57
58
my $webtask;
my $webtask_id;
59
my $snapshot;
60
my $foreground = 0;
61
my $localuser  = 0;
62
my $quickuuid;
63
my $aggregate;
64
my $this_user;
65
66
67
68
69

# Protos
sub fatal($);
sub UserError($);
sub Terminate($);
Leigh B Stoller's avatar
Leigh B Stoller committed
70
sub Extend($$);
71
sub SnapShot($$$);
72
sub GenCredentials($$$$);
73
74
75
76
77
78
79
80

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $OURDOMAIN     = "@OURDOMAIN@";
81
my $MAINSITE      = @TBMAINSITE@;
82
83
84
85
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
my $SACERT	  = "$TB/etc/genisa.pem";
my $CMCERT	  = "$TB/etc/genicm.pem";
my $SSHKEYGEN     = "/usr/bin/ssh-keygen";
86
my $SSHSETUP      = "$TB/sbin/aptssh-setup";
87
my $UPDATEGENIUSER= "$TB/sbin/protogeni/updategeniuser";
88
my $VERSIONING    = @PROFILEVERSIONS@;
89
90
91
92
93
94
95
96
97
98
99
100
101
102

# 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
103
use APT_Profile;
Leigh B Stoller's avatar
Leigh B Stoller committed
104
use APT_Instance;
105
106
107
108
109
110
111
112
113
114
115
116
use User;
use OSinfo;
use emutil;
use GeniDB;
use GeniUser;
use GeniCertificate;
use GeniCredential;
use GeniSlice;
use GeniAuthority;
use GeniHRN;
use Genixmlrpc;
use GeniResponse;
117
use GeniXML;
118
use WebTask;
119
120
121
122
123
124
125
126
127

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
128
129
130
if (defined($options{"a"})) {
    $aggregate = $options{"a"};
}
131
132
133
134
135
136
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verbose = 1;
}
137
138
139
if (defined($options{"f"})) {
    $foreground = 1;
}
140
141
142
if (defined($options{"k"})) {
    $killit = 1;
}
143
144
145
if (defined($options{"s"})) {
    $snapshot = 1;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
146
147
148
if (defined($options{"e"})) {
    $extend = $options{"e"};
}
149
150
151
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
}
152
153
154
if (defined($options{"u"})) {
    $quickuuid = $options{"u"};
}
155
if (@ARGV < 1) {
156
157
158
159
160
    usage();
}
if ($killit) {
    $quickuuid = shift(@ARGV);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
161
162
163
164
165
166
elsif ($extend) {
    if ($extend !~ /^\d*$/) {
	usage();
    }
    $quickuuid = shift(@ARGV);
}
167
168
169
170
171
172
elsif ($snapshot) {
    usage()
	if (@ARGV != 3);
    
    $quickuuid = shift(@ARGV);
}
173
174
175
176
177
178
179
180
else {
    $xmlfile = shift(@ARGV);

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

	if (! defined($this_user)) {
	    fatal("You ($UID) do not exist!");
	}
186
	$localuser = 1;
187
    }
188
    if (!defined($this_user) || !$this_user->IsAdmin()) {
189
190
191
192
193
194
195
196
	if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	    $xmlfile = $1;
	}
	else {
	    fatal("Bad data in pathname: $xmlfile");
	}

	# Use realpath to resolve any symlinks.
197
	my $translated = realpath($xmlfile);
198
199
200
201
202
203
204
205
206
	if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	    $xmlfile = $1;
	}
	else {
	    fatal("Bad data in translated pathname: $xmlfile");
	}
    }
}

207
208
209
# Email record.
if (! $debug) {
    AuditStart(0, undef, LIBAUDIT_LOGTBLOGS()|LIBAUDIT_LOGONLY());
210
    AddAuditInfo("cc", "aptnet-logs\@flux.utah.edu");
211
}
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

# 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");
}
227
my $speaker_signer = $GeniCredential::LOCALSA_FLAG;
228
229
230
231
232
233
234
235
236
237
238
239

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

#
240
# Load the CM authority, since that is who we talk to.
241
#
242
243
my $CMURN;

244
245
246
247
if (defined($aggregate)) {
    $CMURN = $aggregate;
}
elsif ($utahddc) {
248
    $CMURN = $DDCURN;
249
}
250
251
252
253
254
255
256
257
else {
    my $cm_certificate = GeniCertificate->LoadFromFile($CMCERT);
    if (!defined($cm_certificate)) {
	fatal("Could not load certificate from $CMCERT\n");
    }
    $CMURN = $cm_certificate->urn();
}
my $cm_authority = GeniAuthority->Lookup($CMURN);
258
if (!defined($cm_authority)) {
259
260
261
262
    $cm_authority = GeniAuthority->CreateFromRegistry("cm", $CMURN);
    if (!defined($cm_authority)) {    
	fatal("Could not load CM authority object");
    }
263
264
265
266
267
}

if ($killit) {
    exit(Terminate($quickuuid));
}
Leigh B Stoller's avatar
Leigh B Stoller committed
268
269
270
elsif ($extend) {
    exit(Extend($quickuuid, $extend));
}
271
272
273
elsif ($snapshot) {
    exit(SnapShot($quickuuid, $ARGV[0], $ARGV[1]));
}
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

#
# 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.
#
290
foreach my $key ("username", "email", "profile") {
291
292
293
294
295
296
297
298
299
    fatal("Missing required attribute '$key'")
	if (! (exists($xmlparse->{'attribute'}->{"$key"}) &&
	       defined($xmlparse->{'attribute'}->{"$key"}) &&
	       $xmlparse->{'attribute'}->{"$key"} ne ""));
}

#
# Gather up args and sanity check.
#
300
301
my ($value, $user_urn, $user_uid, $user_hrn, $user_email,
    $sshkey, $profile, $version);
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324

#
# 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
325
$value = $xmlparse->{'attribute'}->{"profile"}->{'value'};
326
# This is a safe lookup.
Leigh B Stoller's avatar
Leigh B Stoller committed
327
328
my $profile_object = APT_Profile->Lookup($value);
if (!defined($profile_object)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
329
    fatal("No such profile: $value");
330
}
331
my $rspecstr = $profile_object->CheckFirewall(!$localuser);
332
333
$profile = $profile_object->profileid();
$version = $profile_object->version();
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

#
# 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!");
	}
    }
}
357
358
chomp($sshkey)
    if (defined($sshkey));
359
360
361
362
363
364

#
# 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).
#
365
366
367
368
369
370
371
372
373
374
375
376
# Note that we want to check for the user local account ahead of
# SA account, to bypass their guest account that might still be
# in the table.
#
my $geniuser;

if ($localuser) {
    $geniuser = GeniUser::LocalUser->Lookup($user_uid);
}
else {
    $geniuser = GeniUser->Lookup($user_urn);

377
378
379
    #
    # In Utah, check for alternate SA
    #
380
    if (!defined($geniuser) && $MAINSITE) {
381
382
	$user_urn = GeniHRN::Generate("aptlab.net", "user", $user_uid);
	$user_hrn = "aptlab.${user_uid}";
383
	$geniuser = GeniUser->Lookup($user_urn, 0);
384
385
    }
}
386
if (!defined($geniuser)) {
387
388
389
    if ($localuser) {
	fatal("Could not lookup local user $user_urn");
    }
390
    
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    #
    # Do not allow overlap with local users.
    #
    if (User->Lookup($user_uid)) {
	fatal("User $user_uid exists in the local user table");
    }

    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");
    }
408
409
410
411
412
413
414
415
    my $blob = {"urn"      => $user_urn,
		"hrn"      => $user_hrn,
		"email"    => $user_email,
		"showuuid" => 1};
    if ($MAINSITE) {
	$blob->{'useaptca'} = 1;
    }
    my $certificate = GeniCertificate->Create($blob);
416
417
418
419
420
421
422
423
424
425
    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
426
    # Setup browser ssh.
427
    #
428
429
430
    system("$SSHSETUP " . $geniuser->uuid());
    fatal("Could not create ssh key pair")
	if ($?);
431
432
433
434
}
my $user_uuid = $geniuser->uuid();
# So we know this user has dome something lately.
$geniuser->BumpActivity();
435
436
437
438
439
440
441
442
443

#
# Guest users use the apt CA, and so we must sign the speaksfor
# credential with the APT SA as well so that the target of the
# speaksfor credential is in the same namespace as the signer.
#
if (!$localuser && $MAINSITE) {
    $speaker_signer = "/usr/testbed/etc/utah-apt.sa";
}
444

445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
if ($localuser) {
    my $emulab_user = $geniuser->emulab_user();
    if ($emulab_user->IsNonLocal()) {
	system("$UPDATEGENIUSER -s " . $emulab_user->uid());
	if ($?) {
	    fatal("Could not update ssh keys for nonlocal user");
	}
    }
}
elsif (!$localuser && defined($sshkey)) {
    #
    # 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.
    #
460
461
462
    $geniuser->DeleteKeys();
    $geniuser->AddKey($sshkey);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
463
# There will be "internal" keys cause we pass the flag asking for them.
464
my @sshkeys;
Leigh B Stoller's avatar
Leigh B Stoller committed
465
if ($geniuser->GetKeyBundle(\@sshkeys, 1) < 0 || !@sshkeys) {
466
467
468
469
470
471
    fatal("No ssh keys to use for $geniuser!");
}

#
# Now generate a slice registration and credential
#
472
473
474
475
my $slice_id    = $user_uid . "-QV" . TBGetUniqueIndex('next_quickvm', 1);
my $slice_urn   = GeniHRN::Generate($OURDOMAIN, "slice", $slice_id);
my $slice_hrn   = "${PGENIDOMAIN}.${slice_id}";
my $SERVER_NAME = (exists($ENV{"SERVER_NAME"}) ? $ENV{"SERVER_NAME"} : "");
476

477
478
print STDERR "\n";
print STDERR "$user_urn\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
479
print STDERR "$slice_urn\n";
480
print STDERR "$SERVER_NAME\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
481
print STDERR "\n";
482
483
print STDERR "$rspecstr\n";

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
#
# 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");
}
510
511
# These get quick expirations, unless it is a real user.
if ($slice->SetExpiration(time() + (($localuser ? 16 : 3) * 3600)) != 0) {
512
513
514
515
516
    $slice->Delete();
    fatal("Could not set the slice expiration for $slice_urn");
}
my $slice_uuid = $slice->uuid();

517
#
518
# Generate credentials we need.
519
#
520
521
522
523
my ($slice_credential, $speaksfor_credential) =
    GenCredentials($slice, $geniuser, $sa_authority, $speaker_signer);
if (! (defined($speaksfor_credential) &&
       defined($slice_credential))) {
524
    $slice->Delete();
525
    fatal("Could not generate credentials");
526
527
}

528
#
529
# Got this far, lets create a quickvm record.
530
#
531
my $quickvm_uuid = (defined($quickuuid) ? $quickuuid : NewUUID());
532
533
534
if (!defined($quickvm_uuid)) {
    fatal("Could not generate a new uuid");
}
Leigh B Stoller's avatar
Leigh B Stoller committed
535
my $instance = APT_Instance->Create({'uuid'         => $quickvm_uuid,
536
537
				     'profile_id'   => $profile,
				     'profile_version' => $version,
Leigh B Stoller's avatar
Leigh B Stoller committed
538
539
540
541
				     'slice_uuid'   => $slice_uuid,
				     'creator'      => $geniuser->uid(),
				     'creator_idx'  => $geniuser->idx(),
				     'creator_uuid' => $geniuser->uuid(),
542
				     'aggregate_urn'=> $CMURN,
543
544
				     'status'       => "created",
				     'servername'   => $SERVER_NAME});
Leigh B Stoller's avatar
Leigh B Stoller committed
545
if (!defined($instance)) {
546
    $slice->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
547
    fatal("Could not create instance record for $quickvm_uuid");
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
}

#
# 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();
Leigh B Stoller's avatar
Leigh B Stoller committed
583
    $instance->SetStatus("failed");
584
585
586
587
588
589
590
591
592
593
    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();
Leigh B Stoller's avatar
Leigh B Stoller committed
594
    $instance->SetStatus("failed");
595
596
    fatal("Could not find the manifest in the response!");
}
Leigh B Stoller's avatar
Leigh B Stoller committed
597
598
$instance->SetStatus("provisioned");
$instance->SetManifest($manifest);
599
600
601
602
603
604
605
606

#
# 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;
607
my $public_url;
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623

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)) {
624
625
626
627
628
629
630
	print STDERR "SliverStatus failed";
	if (defined($response)) {
	    print STDERR ": " . $response->output();
	}
	print STDERR "\n";
	$failed = 1;
	last;
631
632
633
634
635
    }
    next
	if ($response->code() == GENIRESPONSE_BUSY);

    my $blob = $response->value();
636
637
638
    if (exists($blob->{'public_url'})) {
	$public_url = $blob->{'public_url'};
    }
639
640
641
642
643
644
645
646
647
    if ($blob->{'status'} eq "ready") {
	$ready = 1;
	last;
    }
    elsif ($blob->{'status'} eq "failed") {
	$failed = 1;
	last;
    }
}
648
649
650
651
652
653
print STDERR "$slice_urn\n";
print STDERR "$public_url\n"
    if (defined($public_url));
print STDERR "\n";
print STDERR "$manifest\n\n";

654
if ($failed || !$ready) {
Leigh B Stoller's avatar
Leigh B Stoller committed
655
    $instance->SetStatus("failed");
656
657
658
659
660
661
662
663
664
    if (!$ready) {
	print STDERR "$slice_urn timed out.\n";
    }
    else {
	print STDERR "$slice_urn failed.\n"; 
    }
}
else {
    $instance->SetStatus("ready");
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
}
$slice->UnLock();
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);
}

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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
#
# Generate or yank the speaks for credential out of the DB.
#
sub GenCredentials($$$$)
{
    my ($target, $geniuser, $authority, $signer) = @_;
    my ($speaksfor, $credential);

    #
    # If a local user account, but a nonlocal id, then we should
    # have a speaksfor credential stored, as well as a certificate
    # for the user.
    #
    if ($geniuser->IsLocal() && $geniuser->emulab_user()->IsNonLocal()) {
	my ($speaksfor_string, $certificate_string) =
	    $geniuser->emulab_user()->GetStoredCredential();
	if (! (defined($speaksfor_string) &&
	       defined($certificate_string))) {
	    print STDERR "No stored speaksfor/certificate for $geniuser\n";
	    goto bad;
	}
	$speaksfor = GeniCredential->CreateFromSigned($speaksfor_string);
	if (!defined($speaksfor)) {
	    print STDERR "Could not create speaksfor credential\n";
	    goto bad;
	}
	my $certificate =
	    GeniCertificate->LoadFromString($certificate_string);
	if (!defined($certificate)) {
	    print STDERR "Could not load certificate from string\n";
	    goto bad;
	}
	$credential = GeniCredential->Create($target, $certificate);
    }
    else {
	$speaksfor = GeniCredential->Create($geniuser, $authority);
	if (!defined($speaksfor)) {
	    print STDERR "Could not create speaksfor credential\n";
	    goto bad;
	}
	$speaksfor->SetType("speaksfor");
	if ($speaksfor->Sign($signer)) {
	    print STDERR "Could not sign speaksfor credential\n";
	    goto bad;
	}
	$credential = GeniCredential->Create($target, $geniuser);
    }
    if (!defined($credential)) {
	print STDERR "Could not create credential for $target\n";
	goto bad;
    }
    # And sign it.
    if ($credential->Sign($GeniCredential::LOCALSA_FLAG) != 0) {
	$credential->Delete();
	print STDERR "Could not sign $target credential\n";
	goto bad;
    }
    return ($credential, $speaksfor);
  bad:
    return ();
}

747
748
749
750
751
752
753
#
# Terminate a quick VM.
#
sub Terminate($)
{
    my ($uuid) = @_;

Leigh B Stoller's avatar
Leigh B Stoller committed
754
755
    my $instance = APT_Instance->Lookup($uuid);
    if (! defined($instance)) {
756
757
	fatal("No such quick VM: $uuid");
    }
758
759
760
761
762
763
764
765
766
767
768
769
    if (defined($instance->aggregate_urn()) &&
	$instance->aggregate_urn() ne $CMURN) {
	$CMURN = $instance->aggregate_urn();
	
	$cm_authority = GeniAuthority->Lookup($CMURN);
	if (!defined($cm_authority)) {
	    $cm_authority = GeniAuthority->CreateFromRegistry("cm", $CMURN);
	    if (!defined($cm_authority)) {    
		fatal("Could not load CM authority object");
	    }
	}
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
770
    my $geniuser = GeniUser->Lookup($instance->creator_uuid(), 1);
771
772
773
    if (!defined($geniuser)) {
	fatal("No creator for quick VM: $uuid");
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
774
    my $slice = GeniSlice->Lookup($instance->slice_uuid());
775
    if (!defined($slice)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
776
	if ($instance->status() eq "failed") {
777
778
	    goto done;
	}
779
780
	fatal("No slice for quick VM: $uuid");
    }
781
782
783
784
785
786
787
788
789
    #
    # Generate credentials we need.
    #
    my ($slice_credential, $speaksfor_credential) =
	GenCredentials($slice, $geniuser, $sa_authority, $speaker_signer);
    if (! (defined($speaksfor_credential) &&
	   defined($slice_credential))) {
	fatal("Could not generate credentials");
    }
790

791
792
793
794
795
796
797
    #
    # Lock the slice in case it is doing something else, like taking
    # a disk image.
    #
    if ($slice->Lock()) {
	fatal("Slice is busy, cannot lock it");
    }
798
    my $old_status = $instance->status();
Leigh B Stoller's avatar
Leigh B Stoller committed
799
    $instance->SetStatus("terminating");
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814

    #
    # 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();
    }
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
    #
    # We have to watch for resource busy errors, and retry. For a while
    # at least. Eventually give up cause it might be a permanently locked
    # slice cause of earlier error. 
    #
    my $tries = 10;
    while ($tries) {
	my $response =
	    Genixmlrpc::CallMethod($cm_authority->url(), undef,
				   "DeleteSlice",
				   { "slice_urn"   => $slice->urn(),
				     "credentials" =>
					 [$slice_credential->asString(),
					  $speaksfor_credential->asString()]});

	if (!defined($response) ||
	    ($response->code() != GENIRESPONSE_SUCCESS &&
	     $response->code() != GENIRESPONSE_SEARCHFAILED &&
	     $response->code() != GENIRESPONSE_BUSY)) {
	    $instance->SetStatus($old_status);
835
	    $slice->UnLock();
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
	    fatal("DeleteSlice failed: ".
		  (defined($response) ? $response->output() : "") . "\n");
	}
	last
	    if ($response->code() == GENIRESPONSE_SUCCESS ||
		$response->code() == GENIRESPONSE_SEARCHFAILED);

	#
	# Wait for a while and try again. 
	#
	$tries--;
	if ($tries) {
	    print STDERR "Slice is busy, will retry again in a bit ...\n";
	    sleep(30);
	}
    }
    if (!$tries) {
853
	$slice->UnLock();
854
	$instance->SetStatus($old_status);
855
	fatal("DeleteSlice failed: Slice was busy for way too long");
856
857
    }
    $slice->Delete();
858
  done:
859
    $instance->RecordHistory();
Leigh B Stoller's avatar
Leigh B Stoller committed
860
    $instance->Delete();
861
862
    exit(0);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
863
864
865
866
867
868
869
870

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

Leigh B Stoller's avatar
Leigh B Stoller committed
871
872
    my $instance = APT_Instance->Lookup($uuid);
    if (! defined($instance)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
873
874
	fatal("No such quick VM: $uuid");
    }
875
876
877
878
879
880
881
882
883
884
885
886
    if (defined($instance->aggregate_urn()) &&
	$instance->aggregate_urn() ne $CMURN) {
	$CMURN = $instance->aggregate_urn();
	
	$cm_authority = GeniAuthority->Lookup($CMURN);
	if (!defined($cm_authority)) {
	    $cm_authority = GeniAuthority->CreateFromRegistry("cm", $CMURN);
	    if (!defined($cm_authority)) {    
		fatal("Could not load CM authority object");
	    }
	}
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
887
    my $geniuser = GeniUser->Lookup($instance->creator_uuid(), 1);
Leigh B Stoller's avatar
Leigh B Stoller committed
888
889
890
    if (!defined($geniuser)) {
	fatal("No creator for quick VM: $uuid");
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
891
    my $slice = GeniSlice->Lookup($instance->slice_uuid());
Leigh B Stoller's avatar
Leigh B Stoller committed
892
    if (!defined($slice)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
893
894
895
	if ($instance->status() eq "failed") {
	    goto done;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
896
897
898
899
900
901
902
	fatal("No slice for quick VM: $uuid");
    }

    # Need to update slice before creating new credential. 
    $slice->AddToExpiration($extend);
    my $new_expires = $slice->ExpirationGMT();

903
904
905
906
907
908
909
910
911
    #
    # Generate credentials we need.
    #
    my ($slice_credential, $speaksfor_credential) =
	GenCredentials($slice, $geniuser, $sa_authority, $speaker_signer);
    if (! (defined($speaksfor_credential) &&
	   defined($slice_credential))) {
	fatal("Could not generate credentials");
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
912
913
914
915
916
917
918
919
920
921
    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) {
922
923
924
	if ($response->code() == GENIRESPONSE_REFUSED) {
	    UserError($response->output());
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
925
926
927
928
929
930
	fatal("RenewSlice failed: ".
	      (defined($response) ? $response->output() : "") . "\n");
    }
    $slice->SetExpiration($new_expires);
    exit(0);
}
931
932
933
934
935
936
937
938

#
# SnapShot.
#
sub SnapShot($$$)
{
    my ($uuid, $sliver_urn, $imagename) = @_;

939
    $this_user = User->ThisUser();
940
941
942
    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
943
944
945
946
947
948
949
950
    my $instance = APT_Instance->Lookup($uuid);
    if (! defined($instance)) {
	fatal("No such quick VM: $uuid");
    }
    my $old_status = $instance->status();
    if ($old_status ne "ready") {
	fatal("Instance must be in the ready state to take a snapshot");
    }
951
952
953
954
    my $profile = $instance->Profile();
    if (! defined($profile)) {
	fatal("No profile for $instance");
    }
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
    if (defined($instance->aggregate_urn()) &&
	$instance->aggregate_urn() ne $CMURN) {
	$CMURN = $instance->aggregate_urn();
	
	$cm_authority = GeniAuthority->Lookup($CMURN);
	if (!defined($cm_authority)) {
	    $cm_authority = GeniAuthority->CreateFromRegistry("cm", $CMURN);
	    if (!defined($cm_authority)) {    
		fatal("Could not load CM authority object");
	    }
	}
    }
    my $geniuser = GeniUser->Lookup($instance->creator_uuid(), 1);
    if (!defined($geniuser)) {
	fatal("No creator for quick VM: $uuid");
    }
    my $slice = GeniSlice->Lookup($instance->slice_uuid());
    if (!defined($slice)) {
	if ($instance->status() eq "failed") {
	    goto done;
	}
	fatal("No slice for quick VM: $uuid");
    }

979
980
981
982
983
984
985
986
987
    #
    # Generate credentials we need.
    #
    my ($slice_credential, $speaksfor_credential) =
	GenCredentials($slice, $geniuser, $sa_authority, $speaker_signer);
    if (! (defined($speaksfor_credential) &&
	   defined($slice_credential))) {
	fatal("Could not generate credentials");
    }
988
989
990
991
992
993
994

    #
    # We do this with slice locked.
    #
    if ($slice->Lock()) {
	fatal("Slice is busy, cannot lock it");
    }
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006

    #
    # We got a webtask ID, which means we want to store the status
    # in the webtask structure. Look it up, create if it does not
    # exist.
    #
    if (defined($webtask_id)) {
	$webtask = WebTask->Lookup($webtask_id);
	if (!defined($webtask)) {
	    fatal("Could not locate webtask for $webtask_id")
	}
    }
1007
1008
    $instance->SetStatus("imaging");

1009
1010
    # For debugging.
    my $cmurl = $cm_authority->url();
Leigh B Stoller's avatar
Leigh B Stoller committed
1011
    #$cmurl =~ s/protogeni/protogeni\/stoller/;
1012

1013
    my $response =
1014
	Genixmlrpc::CallMethod($cmurl, undef,
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
			       "CreateImage",
			       { "slice_urn"  => $slice->urn(),
				 "sliver_urn" => $sliver_urn,
				 "imagename"  => $imagename,
				 "credentials" =>
				     [$slice_credential->asString(),
				      $speaksfor_credential->asString()]});

    if (!defined($response) || $response->code() != GENIRESPONSE_SUCCESS) {
	$instance->SetStatus($old_status);
	$slice->UnLock();
	fatal("CreateImage failed: ".
	      (defined($response) ? $response->output() : "") . "\n");
    }
1029
1030
1031
1032
1033
1034
    my ($image_urn, $image_url,
	$version_urn, $version_url) = @{ $response->value() };
    if (!defined($version_urn)) {
	$version_urn = $image_urn;
	$version_url = $image_url
    }
1035
1036
1037
1038
1039
1040

    #
    # We got a webtask ID, which means we want to create a web task
    # structure to track its progress.
    #
    if (defined($webtask)) {
1041
1042
	$webtask->image_urn($version_urn);
	$webtask->image_url($version_url);
1043
1044
	$webtask->Store();
    }
1045
1046
1047
1048
    
    #
    # Exit and leave child to poll. We are looking for the sliver
    # to unlock, which means the createimage is done. What we do
1049
    # not know is if it failed to actually create the image. Need
1050
1051
    # to think about this.
    #
1052
    if (! ($debug || $foreground)) {
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
	my $child = fork();
	if ($child) {
	    # Parent exits but avoid libaudit email.
	    AuditAbort();
	    print "$image_urn,$image_url\n";
	    exit(0);
	}
	# Let parent exit;
	sleep(2);
	# All of the logging magic happens in here.
	libaudit::AuditFork();
    }
1065
1066
1067
1068
    # Bind the process id.
    $webtask->SetProcessID($PID)
	if (defined($webtask));
    
1069
    my $seconds  = 1200;
1070
    my $interval = 5;
1071
1072
1073
1074
1075
1076
1077
1078
    my $ready    = 0;
    my $failed   = 0;

    while ($seconds > 0) {
	sleep($interval);
	$seconds -= $interval;
    
	my $response =
1079
	    Genixmlrpc::CallMethod($cmurl, undef,
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
				   "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)) {
	    print STDERR "SliverStatus failed";
	    if (defined($response)) {
		print STDERR ": " . $response->output();
	    }
	    print STDERR "\n";
	    $failed = 1;
	    last;
	}
	next
	    if ($response->code() == GENIRESPONSE_BUSY);

	my $blob = $response->value();
	if (exists($blob->{'public_url'})) {
	    $public_url = $blob->{'public_url'};
	}
1104
1105
1106
1107
1108
1109
1110
1111
	if (defined($webtask)) {
	    #
	    # Need to find the sliver inside the blob.
	    #
	    my $sliverblob = $blob->{'details'}->{$sliver_urn};
	    if (defined($sliverblob)) {
		$webtask->state($sliverblob->{'state'});
		$webtask->rawstate($sliverblob->{'rawstate'});
1112
		$webtask->Store();
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
	    }
	}
	if ($blob->{'status'} eq "failed") {
	    $failed = 1;
	    last;
	}
	#
	# We are watching for the image status to report ready or failed.
	#
	$response =
	    Genixmlrpc::CallMethod($cmurl, undef,
				   "ImageInfo",
				   { "image_urn"   => $image_urn,
				     "credentials" =>
					 [$slice_credential->asString(),
					  $speaksfor_credential->asString()]});

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

	$blob = $response->value();

	if (defined($webtask)) {
	    if (exists($blob->{'size'})) {
		$webtask->image_size($blob->{'size'});
	    }
	    if (exists($blob->{'status'})) {
		$webtask->image_status($blob->{'status'});
	    }
	    $webtask->Store();
	}
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
	if ($blob->{'status'} eq "ready") {
	    $ready = 1;
	    last;
	}
	elsif ($blob->{'status'} eq "failed") {
	    $failed = 1;
	    last;
	}
    }
    if ($failed) {
	print STDERR "Imaging failed\n";
1165
1166
1167
	$webtask->Exited(1)
	    if (defined($webtask));
	exit(1);
1168
1169
1170
    }
    elsif (!$ready) {
	print STDERR "Imaging timed out\n"; 
1171
1172
1173
	$webtask->Exited(60)
	    if (defined($webtask));
	exit(1);
1174
1175
1176
    }
    else {
	# Leave the slice locked if it failed; need to think about
1177
1178
1179
1180
1181
1182
1183
	# what we should do.
	#
	# If successful, we create a new version of the profile and
	# update the rspec to reflect the new image version. Note
	# that we expect the CM is doing image versioning, so do not
	# bother to check if the image version is actually new.
	#
1184
1185
1186
1187
1188
1189
1190
1191
	if ($VERSIONING) {
	    $profile = $profile->NewVersion($this_user);
	    if (!defined($profile)) {
		print STDERR "Could not create new profile version\n";
		$webtask->Exited(70)
		    if (defined($webtask));
		exit(1);
	    }
1192
1193
	}
	$profile->UpdateDiskImage($image_urn);
1194
1195
	$slice->UnLock();
	$instance->SetStatus("ready");
1196
1197
1198
1199
1200
	# We garbage collect these later, so anyone waiting has a chance
	# to see the exit status
	$webtask->Exited(0)
	    if (defined($webtask));
	print "$image_urn,$image_url\n";
1201
1202
1203
1204
    }
  done:
    exit(0);
}