GeniCM.pm.in 118 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
#!/usr/bin/perl -wT
#
3
# GENIPUBLIC-COPYRIGHT
4
# Copyright (c) 2008-2010 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# All rights reserved.
#
package GeniCM;

#
# The server side of the CM interface on remote sites. Also communicates
# with the GMC interface at Geni Central as a client.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

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

# Must come after package declaration!
use lib '@prefix@/lib';
use GeniDB;
use Genixmlrpc;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
24
25
use GeniResponse;
use GeniTicket;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
26
use GeniCredential;
27
use GeniCertificate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
28
use GeniSlice;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
29
use GeniAggregate;
30
use GeniAuthority;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
31
use GeniSliver;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
32
use GeniUser;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
33
use GeniRegistry;
34
use GeniUtil;
35
use GeniHRN;
36
use GeniXML;
37
use GeniUsage;
38
use libtestbed qw(SENDMAIL);
39
use emutil;
40
41
use EmulabConstants;
use libEmulab;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
42
43
use English;
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
44
use XML::Simple;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
45
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
46
use POSIX qw(strftime tmpnam);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
use Time::Local;
48
use Compress::Zlib;
49
use File::Temp qw(tempfile);
50
use MIME::Base64;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
51
52
53
54
55
56
57
58

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
59
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
60
my $CREATEEXPT     = "$TB/bin/batchexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
61
my $ENDEXPT        = "$TB/bin/endexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
62
my $NALLOC	   = "$TB/bin/nalloc";
63
my $NFREE	   = "$TB/bin/nfree";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
64
my $AVAIL	   = "$TB/sbin/avail";
65
my $PTOPGEN	   = "$TB/libexec/ptopgen";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
66
67
my $TBSWAP	   = "$TB/bin/tbswap";
my $SWAPEXP	   = "$TB/bin/swapexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
68
69
my $PLABSLICE	   = "$TB/sbin/plabslicewrapper";
my $NAMEDSETUP     = "$TB/sbin/named_setup";
70
my $EXPORTS_SETUP  = "$TB/sbin/exports_setup";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
71
72
my $VNODESETUP     = "$TB/sbin/vnode_setup";
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
73
my $TARFILES_SETUP = "$TB/bin/tarfiles_setup";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
74
75
76
my $MAPPER         = "$TB/bin/mapper";
my $VTOPGEN        = "$TB/bin/vtopgen";
my $SNMPIT         = "$TB/bin/snmpit";
77
my $NEWGROUP       = "$TB/bin/newgroup";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
78
my $PRERENDER      = "$TB/libexec/vis/prerender";
79
my $XMLLINT	   = "/usr/local/bin/xmllint";
80
my $ADDAUTHORITY   = "$TB/sbin/protogeni/addauthority";
81
my $EMULAB_PEMFILE = "@prefix@/etc/genicm.pem";
82
my $API_VERSION    = 1;
83
84
85
86
87
88
89
90
91
92
93

#
# 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()
{
    return GeniResponse->Create( GENIRESPONSE_SUCCESS, $API_VERSION );
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
94
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
95
# Respond to a Resolve request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
96
97
98
99
100
101
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
102
103
    my $type       = lc( $argref->{'type'} );
    my $hrn        = $argref->{'hrn'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
104
105
106
107

    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
    }
108
109
110
111
    if (defined($uuid) && GeniHRN::IsValid($uuid)) {
	$hrn  = $uuid;
	$uuid = undef;
    }
112
113
114
115
116
117
118
119
120
121
122
123
    if( defined( $hrn ) && GeniHRN::IsValid( $hrn ) ) {
	my ($auth,$t,$id) = GeniHRN::Parse( $hrn );

	return GeniResponse->Create( GENIRESPONSE_ERROR, undef,
				     "Authority mismatch" )
	    if( $auth ne $OURDOMAIN );

	$type = lc( $t );
	
	$hrn = $id;	
    }
    if (! (defined($type) && ($type =~ /^(node)$/))) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
124
125
126
	return GeniResponse->MalformedArgsResponse();
    }
    # Allow lookup by uuid or hrn.
127
    if (! defined($uuid) && !defined( $hrn ) ) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
128
129
130
131
132
133
	return GeniResponse->MalformedArgsResponse();
    }
    if (defined($uuid) && !($uuid =~ /^[-\w]*$/)) {
	return GeniResponse->MalformedArgsResponse();
    }

134
135
136
137
    my $credential = CheckCredential($cred);
    return $credential
	if (GeniResponse::IsResponse($credential));

138
    if ($type eq "node") {
139
	require Interface;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
140
141
142
	my $node;
	
	if (defined($uuid)) {
143
	    $node= GeniUtil::LookupNode($uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
144
145
	}
	else {
146
	    $node= GeniUtil::LookupNode($hrn);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
147
	}
148
	if (! defined($node)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
149
150
151
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
					undef, "Nothing here by that name");
	}
152

153
	my $rspec = GetAdvertisement(0, $node->node_id(), "0.1");
154
155
156
157
	if (! defined($rspec)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not start avail");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
158
159
	
	# Return a blob.
160
	my $blob = { "hrn"          => "${PGENIDOMAIN}." . $node->node_id(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
161
		     "uuid"         => $node->uuid(),
162
		     "role"	    => $node->role(),
163
164
		     "hostname"     =>
			 GeniUtil::FindHostname($node->node_id()),
165
166
		     "physctrl"     => 
			 Interface->LookupControl( $node->phys_nodeid() )->IP(),
167
168
		     "urn"          => GeniHRN::Generate( $OURDOMAIN,
							  "node",
169
170
							  $node->node_id() ),
		     "rspec"        => $rspec
Leigh B. Stoller's avatar
Leigh B. Stoller committed
171
172
173
174
175
176
177
		   };

	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
    }
    return GeniResponse->Create(GENIRESPONSE_UNSUPPORTED);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
178
179
180
181
182
183
#
# Discover resources on this component, returning a resource availablity spec
#
sub DiscoverResources($)
{
    my ($argref) = @_;
184
    my $credstr   = $argref->{'credential'};
185
    my $available = $argref->{'available'} || 0;
186
187
188
189
190
    my $compress  = $argref->{'compress'} || 0;

    my $credential = CheckCredential($credstr);
    return $credential
	if (GeniResponse::IsResponse($credential));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
191

192
    return DiscoverResourcesAux($available, $compress, [$credential]);
193
194
}
# Helper function for V2.
195
sub DiscoverResourcesAux($$$)
196
{
197
    my ($available, $compress, $credentials) = @_;
198
    my $user_urn  = $ENV{'GENIRN'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
199

200
201
202
    # Oh, for $*%(s sake.  Frontier::RPC2 insists on representing a
    # Boolean as its own object type -- which Perl always interprets as
    # true, regardless of the object's value.  Undo all of that silliness.
203
204
205
206
207
208
    if (defined($available) && ref($available) eq 'Frontier::RPC2::Boolean') {
	$available = $available->value;
    }
    if (defined($compress) && ref($compress) eq 'Frontier::RPC2::Boolean') {
	$compress = $compress->value;
    }
209

Leigh B. Stoller's avatar
Leigh B. Stoller committed
210
211
212
213
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
214
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
215
216
	      # Cannot get the value, say no.
	      $allow_externalusers = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
217
    }
218
219
220
221
222
223
224

    # Figure out if user has a credentials that exempts him
    # from the following policy. If external users are blocked access
    # and he presents a credential that exempts him from it, 
    # then he should get access.
    my $isExempted = 0;
    foreach my $credential (@$credentials) {
225
        if (GeniXML::PolicyExists('allow_externalusers', $credential) == 1) {
226
227
228
229
230
231
        $isExempted = 1;
        last;
      }
    }

    if (!$allow_externalusers && !$isExempted) {
232
	my $user = GeniUser->Lookup($user_urn, 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
233
234
235
236
237
238
239
	# No record means the user is remote.
	if (!defined($user) || !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
					"External users temporarily denied");
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
240
    #
241
    # Acquire the advertisement from ptopgen and compress it if requested.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
242
    #
243
    my $xml = GetAdvertisement($available, undef, "0.2");
244
    if (! defined($xml)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
245
246
247
248
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }

249
250
251
252
253
254
    if( $compress ) {
	my $coder = Frontier::RPC2->new();
	my $base64 = encode_base64( compress( $xml ) );
	$xml = $coder->base64( $base64 );	
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
255
256
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $xml);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
257

258
259
260
#
# Use ptopgen in xml mode to spit back an xml file. 
#
261
sub GetAdvertisement($$$)
262
{
263
    my ($available, $pc, $version) = @_;
264
265
    my $xml = undef;

266
    my $invocation = "$PTOPGEN -x -g $version -r -p GeniSlices";
267
268
269
270
271
    $invocation .= " -a" unless $available;
    if (defined($pc)) {
	$invocation .= " -1 $pc";
    }
    if (open(AVAIL, "$invocation |")) {
272
	$xml = "";
273
274
275
276
277
278
279
280
	while (<AVAIL>) {
	    $xml .= $_;
	}
	close(AVAIL);
    }
    return $xml;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
281
#
282
# Update a ticket with a new rspec.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
283
#
284
sub UpdateTicket($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
285
286
{
    my ($argref) = @_;
287
288
289
290
291
292
293
294
295
296

    return GetTicket($argref, 1);
}

#
# Respond to a GetTicket request. 
#
sub GetTicket($;$)
{
    my ($argref, $isupdate) = @_;
297
    my $rspecstr   = $argref->{'rspec'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
298
    my $impotent   = $argref->{'impotent'};
299
300
    my $credstr    = $argref->{'credential'};
    my $tickstr    = $argref->{'ticket'};
301
302
303
304
305
306
307
    my $ticket;

    # Default to no update
    $isupdate = 0
	if (!defined($isupdate));
    $impotent = 0
	if (!defined($impotent));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
308

309
    if (! defined($credstr)) {
310
	return GeniResponse->MalformedArgsResponse();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
311
    }
312
    if (!defined($rspecstr)) {
313
314
	return GeniResponse->MalformedArgsResponse();
    }
315
316
317
318
    if (! ($rspecstr =~ /^[\040-\176\012\015\011]+$/)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Improper characters in rspec");
    }
319
320
321
322
    my $credential = CheckCredential($credstr);
    return $credential
	if (GeniResponse::IsResponse($credential));

323
    if ($isupdate) {
324
325
326
	$ticket = CheckTicket($tickstr);
	return $ticket
	    if (GeniResponse::IsResponse($ticket));
327
    }
328
    return GetTicketAux($credential,
329
			$rspecstr, $isupdate, $impotent, 0, 1, $ticket);
330
}
331

332
sub GetTicketAux($$$$$$$)
333
{
334
335
    my ($credential, $rspecstr, $isupdate, $impotent, $v2, $level,
	$ticket) = @_;
336
    
337
338
339
340
341
342
    defined($credential) &&
	($credential->HasPrivilege( "pi" ) or
	 $credential->HasPrivilege( "instantiate" ) or
	 $credential->HasPrivilege( "bind" ) or
	 return GeniResponse->Create( GENIRESPONSE_FORBIDDEN, undef,
				      "Insufficient privilege" ));
343
    
344
345
    my $slice_urn = $credential->target_urn();
    my $user_urn  = $credential->owner_urn();
346
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
347
    #
348
    # Create user from the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
349
    #
350
351
    my $user = CreateUserFromCertificate($credential->owner_cert());
    if (!defined($user)) {
352
	if ($isupdate) {
353
	    print STDERR "Could not locate $user_urn for UpdateTicket\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
354
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
355
					"No user found for UpdateTicket");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
356
	}
357
	return GeniResponse->Create(GENIRESPONSE_ERROR);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
358
359
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
360
    #
361
    # Create slice from the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
362
    #
363
364
    my $slice = GeniSlice->Lookup($slice_urn);
    if (!defined($slice)) {
365
	if ($isupdate) {
366
	    print STDERR "Could not locate slice $slice_urn for Update\n";
367
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
368
369
370
371
372
373
374
					"No slice found for UpdateTicket");
	}
	$slice = CreateSliceFromCertificate($credential, $user);
	if (!defined($slice)) {
	    print STDERR "Could not create $slice_urn\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not create slice");
375
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
376
    }
377
    
378
    return GetTicketAuxAux($slice, $user, $rspecstr,
379
380
			   $isupdate, $impotent, $v2, $level, $ticket,
			   [$credential]);
381
}
382
sub GetTicketAuxAux($$$$$$$$$)
383
{
384
385
    my ($slice, $user, $rspecstr, 
        $isupdate, $impotent, $v2, $level, $ticket, $credentials) = @_;
386
387
388
    my $response    = undef;
    my $restorevirt = 0;	# Flag to restore virtual state
    my $restorephys = 0;	# Flag to restore physical state
389
390
    require OSinfo;
    require VirtExperiment;
391
392
393
394
395
396

    #
    # We need this below to sign the ticket.
    #
    my $authority = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
    if (!defined($authority)) {
397
	print STDERR " Could not load authority for $EMULAB_PEMFILE\n";
398
399
400
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }

401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
    #
    # Run xmllint on the rspec to catch format errors.
    #
    my ($fh, $filename) = tempfile(UNLINK => 0);
    if (!defined($fh)) {
	print STDERR "Could not create temp file for rspec\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
    print $fh $rspecstr;
    close($fh);
    my $xmlerrors = `$XMLLINT --noout $filename 2>&1`;
    unlink($filename);
    if ($?) {
	return GeniResponse->Create(GENIRESPONSE_ERROR,
				    $xmlerrors,
				    "rspec is not well formed");
    }

419
420
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
421
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
422
				    "Error Parsing rspec XML");
423
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
424

Leigh B. Stoller's avatar
Leigh B. Stoller committed
425
426
427
428
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
429
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
430
431
432
433
434
435
436
437
438
439
440
441
442
443
	    # Cannot get the value, say no.
	    $allow_externalusers = 0;
    }

    # Figure out if user has a credentials that exempts him
    # from the following policy. If external users are blocked access
    # and he presents a credential that exempts him from it, 
    # then he should get access.
    my $isExempted = 0;
    foreach my $credential (@$credentials) {
      if (1 == GeniXML::PolicyExists('allow_externalusers', $credential)) {
        $isExempted = 1;
        last;
      }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
444
    }
445
446
447

    if (!$allow_externalusers && !$isExempted && !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
448
449
450
451
				    "External users temporarily denied");
    }
    
    #
452
    # For now all tickets expire very quickly (minutes), but once the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
453
    # ticket is redeemed, it will expire according to the rspec request.
454
455
456
    # If nothing specified in the rspec, then it will expire when the
    # slice record expires, which was given by the expiration time of the
    # slice credential.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
457
    #
Jonathon Duerig's avatar
Jonathon Duerig committed
458
    my $expires = GeniXML::GetExpires($rspec);
459
    if (defined($expires)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
460
461
462
463
464
465
466
467
468
469
470
471
	if (! ($expires =~ /^[-\w:.\/]+/)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Illegal valid_until in rspec");
	}
	# Convert to a localtime.
	my $when = timegm(strptime($expires));
	if (!defined($when)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Could not parse valid_until");
	}
	
	#
472
	# Do we need a policy limit?
473
474
475
  # A sitevar controls the sliver lifetime.
  #
  my $max_sliver_lifetime = 0;
476
  if (!GetSiteVar('protogeni/max_sliver_lifetime', \$max_sliver_lifetime)){
477
478
	    # Cannot get the value, default it to 90 days.
	    $max_sliver_lifetime = 90;
479
480
481
482
483
  }

  # Check if the user has a credential that lets him obtain slivers
  # with extended sliver lifetime. If so allow him to get sliver.
  foreach my $credential (@$credentials) {
484
485
486
487
488
489
      my $nodes = GeniXML::FindNodesNS("//n:max_sliver_lifetime",
          $credential->extensions(), $GeniUtil::EXTENSIONS_NS);
      if ($nodes->size > 0) {
          $max_sliver_lifetime = int($nodes->pop()->string_value);
          last;
      }
490
  }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
491
	my $diff = $when - time();
492
	if ($diff < (60 * 5) || $diff > (3600 * 24 * $max_sliver_lifetime)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
493
494
495
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"valid_until out of range");
	}
496
497
498
499
500
501

	#
	# Must be before the slice expires.
	#
	my $slice_expires = $slice->expires();
	if (defined($slice_expires)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
502
	    $slice_expires = str2time($slice_expires);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
503
	    if ($when > $slice_expires) {
504
505
506
507
		return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "valid_until is past slice expiration");
	    }
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
508
    }
509
510
511
512
513
514
515

    #
    # Lock the ticket so it cannot be released.
    #
    if (defined($ticket) && $ticket->stored() && $ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
    }
516
517
518
    if (defined($ticket)) {
	$ticket->SetSlice($slice);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
519
520
521
522
523
524
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
525
526
527
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
528
    }
529
530
531
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
532
533
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
534
535
536
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
537
538
539
540
541
542
543
544
    # Ditto for expired.
    if ($slice->IsExpired()) {
	$slice->UnLock();
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
				    "Slice has expired");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
545

546
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
547
    # For now, there can be only a single toplevel aggregate per slice.
548
    # The existence of an aggregate means the slice is active here. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
549
    #
550
    my $aggregate = GeniAggregate->SliceAggregate($slice);
551
552
553
554
555
    if (!$isupdate) {
	if (defined($aggregate)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Already have an aggregate for slice");
	    goto bad;
556
557
	}
    }
558
559
560
561
562
    elsif ($v2 && $level && !defined($ticket) && !defined($aggregate)) {
	print STDERR "No aggregate for $slice in version two API\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
563
564
565
566

    #
    # Firewall hack; just a flag in the rspec for now.
    #
567
568
569
    my $needsfirewall = GeniXML::GetText("needsfirewall", $rspec);
    if (defined($needsfirewall)) {
	if ($slice->SetFirewallFlag($needsfirewall) != 0) {
570
571
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
572
573
	}
    }
574
575

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
576
    # We need this now so we can form a virtual topo.
577
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
578
579
580
581
582
583
584
585
    my $slice_experiment = GeniExperiment($slice);
    if (!defined($slice_experiment)) {
	print STDERR "Could not create new Geni slice experiment!\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
    my $pid = $slice_experiment->pid();
    my $eid = $slice_experiment->eid();
586
587
588
589
590

    #
    # Mark the experiment locally as coming from the cooked interface.
    # This changes what tmcd returns to the local nodes.
    #
591
    my $generated_by = GeniXML::GetText("generated_by", $rspec);
592
593
    if (defined($generated_by) &&
	$generated_by eq "libvtop") {
594
595
596
597
	$slice_experiment->Update({"geniflags" =>
				       $Experiment::EXPT_GENIFLAGS_EXPT|
				       $Experiment::EXPT_GENIFLAGS_COOKED});
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
598
599
600
601
602
603
604
605
606
607
608
609
610
    
    #
    # Create a virt topology object. We are going to load this up as we
    # process the rspec.
    #
    my $virtexperiment = VirtExperiment->CreateNew($slice_experiment);
    if (!defined($virtexperiment)) {
	print STDERR "Could not create VirtExperiment object!\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
    # Turn off fixnode; we will control this on the commandline.
    $virtexperiment->allowfixnode(0);
611
    $virtexperiment->multiplex_factor(3);
612

Leigh B. Stoller's avatar
Leigh B. Stoller committed
613
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
614
615
    # An rspec is a structure that requests specific nodes. If those
    # nodes are available, then reserve it. Otherwise the ticket
Leigh B. Stoller's avatar
Leigh B. Stoller committed
616
617
    # cannot be granted.
    #
618
619
620
    my %namemap  = ();
    my %colomap  = ();
    my %ifacemap = ();
Jonathon Duerig's avatar
Jonathon Duerig committed
621
    my %iface2node = ();
622
    my %vportmap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
623
    my %nodemap  = ();
624
    my @nodeids  = ();
625
    my %lannodes = ();
626
627
628
629
630
631
632
633

    #
    # If this is a ticket update, we want to seed the namemap with
    # existing nodes. This is cause the rspec might refer to wildcards
    # that were already bound in a previous call. We also want to know
    # what nodes are currently reserved in case we have to release some.
    #
    if ($isupdate) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
	$slice_experiment->ClearBackupState();
	if ($slice_experiment->BackupVirtualState()) {
	    print STDERR "Could not backup virtual state!\n";
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
	}
	if ($slice_experiment->RemoveVirtualState()) {
	    print STDERR "Could not remove virtual state!\n";
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
	}
	$restorevirt = 1;

	if ($slice_experiment->BackupPhysicalState()) {
	    print STDERR "Could not backup physical state!\n";
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
	}
652
653
654
655
656
657
658
	my $oldrspec;
	if ($v2 && defined($aggregate)) {
	    $oldrspec = $aggregate->GetManifest(0);
	}
	else {
	    $oldrspec = $ticket->rspec();
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
659
	
660
	foreach my $ref (GeniXML::FindNodes("n:node",
661
					    $oldrspec)->get_nodelist()) {
662
	    # Let remote nodes pass through.
663
	    next
664
		if (!GeniXML::IsLocalNode($ref));
665

666
667
	    # Skip lan nodes; they are fake.
	    next
668
		if (GeniXML::IsLanNode($ref));
669

670
	    my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
671
	    my $colocate      = GeniXML::GetColocate($ref);
672
673
	    my $component_id  = GeniXML::GetNodeId($ref);
	    my $node = GeniUtil::LookupNode($component_id);
674
675
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
676
				 "Bad resource $component_id in ticket");
677
678
679
680
681
682
683
684
		goto bad;
	    }

	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
685

686
    print GeniXML::Serialize($rspec);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
687

688
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
689
690
	my $component_id  = GeniXML::GetNodeId($ref);
	my $manager_id    = GeniXML::GetManagerId($ref);
691
	my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
692
693
694
695
	my $colocate      = GeniXML::GetColocate($ref);
	my $subnode_of    = GeniXML::GetSubnodeOf($ref);
	my $virtualization_type = GeniXML::GetVirtualizationType($ref);
	
696
	my $virtualization_subtype
Jonathon Duerig's avatar
Jonathon Duerig committed
697
698
                          = GeniXML::GetVirtualizationSubtype($ref);
	my $exclusive     = GeniXML::GetExclusive($ref);
699
	my $pctype;
700
	my $osname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
701
702
	my $node;

703
	# Let remote nodes pass through.
704
	next
705
	    if (! GeniXML::IsLocalNode($ref));
706

707
708
709
710
711
	#
	# Lan nodes are fake and do not go into the virt topo. Need
	# to remember them though, for when we do the links below.
	# They are still in the returned ticket though. 
	#
712
	if (GeniXML::IsLanNode($ref)) {
713
714
715
716
	    $lannodes{$node_nickname} = $ref;
	    next;
	}

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
	#
	# Check for disk_image request. Specified as a URN. 
	#
	my $diskref = GeniXML::FindFirst("n:disk_image", $ref);
	if (defined($diskref)) {
	    my $dname = GeniXML::GetText("name", $diskref);

	    if (defined($dname)) {
		if (! GeniHRN::IsValid($dname)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
		my ($auth,$type,$id) = GeniHRN::Parse($dname);
		my ($ospid,$os) = ($id =~ m{(.*)//(.*)});
		if ($type ne "image" || !defined($ospid) || !defined($os)){
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
		#
740
741
		# For now, the project has to be emulab-ops or the
		# the current project.
742
		#
743
744
		if (! ($ospid eq TBOPSPID() ||
		       $ospid eq $slice_experiment->pid())) {
745
746
747
748
749
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				 "Illegal project name in URN: $dname");
		    goto bad;
		}
750
		my $osinfo = OSinfo->Lookup($ospid, $os);
751
752
753
		if (!defined($osinfo)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
754
					     "Unknown image URN: $dname");
755
756
757
758
759
760
761
762
763
		    goto bad;
		}
		#
		# This is only going to be used in raw mode. 
		#
		$osname = $os;
	    }
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
764
765
766
	if (defined($virtualization_type)) {
	    if ($virtualization_type eq "emulab-vnode") {
		if (defined($virtualization_subtype)) {
767
768
		    $pctype = "pcvm";
		    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
769
770
771
772
773
774
		    if ($virtualization_subtype eq "emulab-jail") {
			$osname = "FBSD-JAIL";
		    }
		    elsif ($virtualization_subtype eq "emulab-openvz") {
			$osname = "OPENVZ-STD";
		    }
775
776
777
778
		    elsif ($virtualization_subtype eq "emulab-spp") {
			$osname = "SPPVM-FAKE";
			$pctype = "sppvm";
			# Lets force to shared node.
Jonathon Duerig's avatar
Jonathon Duerig committed
779
			if (! GeniXML::SetExclusive($ref, 0)) {
780
781
782
			    $response
				= GeniResponse->Create(GENIRESPONSE_BADARGS,
						       undef,
783
784
				       "Malformed rspec: ".
				       "Cannot set exclusive tag to false");
785
786
787
			    goto bad;
			}
			$exclusive = 0;
788
789
			# Kludge for libvtop.
			$virtexperiment->multiplex_factor(1);
790
			$virtexperiment->encap_style("vlan");
791
		    }
792
793
794
795
		    elsif ($virtualization_subtype eq "raw") {
			$pctype = undef;
			goto raw;
		    }
796
797
798
799
800
801
802
803
		    else {
			$response
			    = GeniResponse->Create(GENIRESPONSE_BADARGS,
						   undef,
				       "Malformed rspec: ".
				       "Unknown virtualization_subtype");
			goto bad;
		    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
804
805
806
807
808
809
810
811
		}
		else {
		    goto raw;
		}
	    }
	    else {
	      raw:
		# Lets force to exclusive real node.
Jonathon Duerig's avatar
Jonathon Duerig committed
812
		if (! GeniXML::SetExclusive($ref, 1)) {
813
814
		    $response = GeniResponse->Create(GENIRESPONSE_BADARGS,
						     undef,
815
			"Malformed rspec: Cannot set exclusive tag to true");
816
817
818
		    goto bad;
		}
		$exclusive = 1;
Jonathon Duerig's avatar
Jonathon Duerig committed
819
		if (! GeniXML::SetVirtualizationType($ref, "raw")) {
820
821
		    $response = GeniResponse->Create(GENIRESPONSE_BADARGS,
						     undef,
822
			"Malformed rspec: Cannot set virtualization_type to raw");
823
824
		    goto bad;
		}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
825
826
827
828
	    }
	}
	else {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
829
				     "Must provide a virtualization_type");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
830
831
832
	    goto bad;

	}
833
834
835
836
837
838
	if (!defined($node_nickname)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Must provide a virtual_id for nodes");
	    goto bad;
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
839
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
840
	# Allow wildcarding.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
841
	#
842
	if (!defined($component_id) || $component_id eq "*") {
843
844
845
846
847
	    if (defined($colocate) && exists($colomap{$colocate})) {
		$node = $colomap{$colocate};
	    }
	    elsif ($isupdate && exists($namemap{$node_nickname})) {
		$node = $namemap{$node_nickname};
848
	    }
849
850
851
852
853
854
855
856
	    # If the node still isn't bound and doesn't have a pctype,
	    # use the user-specified one.
	    if (! defined($node) && ! defined($pctype)) {
		my $usertype = GeniXML::FindFirst("n:node_type", $ref);
		if (defined($usertype)) {
		    $pctype = GeniXML::GetText("type_name", $usertype);
		}
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
857
858
	}
	else {
859
	    $node = GeniUtil::LookupNode($component_id);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
860
861
862
863

	    if (!defined($node)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
864
					 "Bad resource $component_id");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
865
866
		goto bad;
	    }
867
868
	    $pctype = $node->type()
		if (!defined($pctype));
869
870
	}
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
871
	# If no osname by this point, try for the default.
872
873
	#
	if (defined($node) && !defined($osname)) {
874
875
876
877
878
	    if (defined($node->default_osid())) {	    
		my $osinfo = OSinfo->Lookup($node->default_osid());
		$osname = $osinfo->osname()
		    if (defined($osinfo));
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
879
	}
880
881
882
	# The slot does not like to be NULL.
	$osname = ""
	    if (!defined($osname));
883
	
884
885
886
	# Need some kind of default.
	$pctype = "pc"
	    if (!defined($pctype));
887
	
888
889
890
891
892
	my $nodeblob = {"vname"   => $node_nickname,
			"type"    => $pctype,
			"osname"  => $osname,
			"ips"     => '', # deprecated
			"cmd_line"=> '', # bogus
Leigh B. Stoller's avatar
Leigh B. Stoller committed
893
894
			"fixed"   => (defined($subnode_of) ? $subnode_of :
				      defined($node) ? $node->node_id() : ""),
895
			};
896
897

	# Tarball and startup command.
898
	my $startupcmd = GeniXML::GetText("startup_command", $ref);
899
	if (defined($startupcmd)) {
900
901
902
903
904
905
906
907
908
	    if (! TBcheck_dbslot($startupcmd, "virt_nodes", "startupcmd",
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Invalid startup command");
		goto bad;
	    }
	    $nodeblob->{'startupcmd'} = $startupcmd;
	}
909
	my $tarfiles = GeniXML::GetText("tarfiles", $ref);
910
	if (defined($tarfiles)) {
911
	    if (! TBcheck_dbslot($tarfiles, "virt_nodes", "tarfiles",
912
913
914
915
916
917
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Invalid tarfiles");
		goto bad;
	    }
918
	    $nodeblob->{'tarfiles'} = $tarfiles;
919
920
921
922
923
924
925
926
	}

	my $virtnode = $virtexperiment->NewTableRow("virt_nodes", $nodeblob);
	if (!defined($virtnode)) {
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					     "Error creating virtnode");
	    goto bad;
	}
927

Leigh B. Stoller's avatar
Leigh B. Stoller committed
928
929
930
931
932
933
934
935
936
937
	$virtexperiment->NewTableRow("virt_node_desires",
				     {"vname"    => $node_nickname,
				      "desire"   => "pcshared",
				      "weight"   => 0.95})
	    if (!defined($exclusive) || !$exclusive);

	# Store reference so we can munge it below. 
	$nodemap{$node_nickname} = {"rspec"    => $ref,
				    "virtnode" => $virtnode};
	
938
939
940
941
	#
	# Look for interface forward declarations that will be used later
	# in the link specifications. 
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
942
	next
943
	    if (!defined(GeniXML::FindFirst("n:interface", $ref)));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
944
	
945
	foreach my $linkref (GeniXML::FindNodes("n:interface",
946
						$ref)->get_nodelist()) {
Jonathon Duerig's avatar
Jonathon Duerig committed
947
	    my $virtual_id   = GeniXML::GetVirtualId($linkref);
948
949
950
951
952
953

	    if (!defined($virtual_id)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
			     "Must provide a virtual_id for interfaces");
		goto bad;
	    }
Jonathon Duerig's avatar
Jonathon Duerig committed
954
955

	    $iface2node{$virtual_id} = $node_nickname;
956
957
958
959
	    
	    $ifacemap{$node_nickname} = {}
	        if (!exists($ifacemap{$node_nickname}));

Leigh B. Stoller's avatar
Leigh B. Stoller committed
960
961
962
	    # port counter.
	    my $vport = scalar(keys(%{ $ifacemap{$node_nickname} }));

963
	    # Store reference so we can munge it below. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
964
965
	    $ifacemap{$node_nickname}->{$virtual_id} = {"rspec" => $linkref,
							"vport" => $vport};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
966

Leigh B. Stoller's avatar
Leigh B. Stoller committed
967
	    # This is used after the mapper runs since it uses vname:vport.
968
	    $vportmap{"$node_nickname:$vport"} = {"rspec" => $linkref};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
969
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
970
971
    }

972
    goto skiplinks
973
	if (!defined(GeniXML::FindFirst("n:link", $rspec)));
974
    
975
    #
976
    # Now deal with links for wildcarded nodes. 
977
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
978
979
    my $linknum = 1;
    
980
    foreach my $linkref (GeniXML::FindNodes("n:link",
981
					    $rspec)->get_nodelist()) {
982
	my $lanname    = GeniXML::GetVirtualId($linkref);
Jonathon Duerig's avatar
Jonathon Duerig committed
983
	my $istunnel   = GeniXML::IsTunnel($linkref);
984
985
	my @interfaces = GeniXML::FindNodes("n:linkendpoints | ".
					    "n:interface_ref",
986
					    $linkref)->get_nodelist();
987
	my %managers   = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
988
	my $ifacenum   = 1;
989
	my $trivial_ok = 0;
990

991
	if (!defined($lanname)) {
992
993
994
995
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Must provide a virtual_id for links");
	    goto bad;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
996

997
998
999
1000
	#
	# Look for managers list; optional for now. If not specified then
	# we assume the link is for thie CM.
	#