GeniCM.pm.in 91.8 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-2009 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 libtestbed qw(SENDMAIL);
37
use emutil;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
38
# Hate to import all this crap; need a utility library.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
39
use libdb qw(TBGetSiteVar EXPTSTATE_SWAPPED EXPTSTATE_ACTIVE);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
40
use User;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
41
use Node;
42
use Interface;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
43 44
use English;
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
45
use XML::Simple;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
46
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
use POSIX qw(strftime tmpnam);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
use Time::Local;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
49
use Experiment;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
50
use VirtExperiment;
51
use Firewall;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
52 53 54 55 56 57 58 59

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
60
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
61
my $CREATEEXPT     = "$TB/bin/batchexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
62
my $ENDEXPT        = "$TB/bin/endexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
63
my $NALLOC	   = "$TB/bin/nalloc";
64
my $NFREE	   = "$TB/bin/nfree";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
65
my $AVAIL	   = "$TB/sbin/avail";
66
my $PTOPGEN	   = "$TB/libexec/ptopgen";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
67 68
my $TBSWAP	   = "$TB/bin/tbswap";
my $SWAPEXP	   = "$TB/bin/swapexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
69 70 71 72
my $PLABSLICE	   = "$TB/sbin/plabslicewrapper";
my $NAMEDSETUP     = "$TB/sbin/named_setup";
my $VNODESETUP     = "$TB/sbin/vnode_setup";
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
73 74 75 76
my $MAPPER         = "$TB/bin/mapper";
my $VTOPGEN        = "$TB/bin/vtopgen";
my $SNMPIT         = "$TB/bin/snmpit";
my $PRERENDER      = "$TB/libexec/vis/prerender";
77
my $EMULAB_PEMFILE = "@prefix@/etc/genicm.pem";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
# Look up a node by an identifier of unspecified type (perhaps a URN, an
# (obsolete) UUID, or an old-style HRN.  Ultimately, all IDs should be
# URNs and this mess will go away, but for now we try not to make
# any assumptions, because of backward compatibility constraints.
sub LookupNode($)
{
    my ($nodeid) = @_;

    if( GeniHRN::IsValid( $nodeid ) ) {
	# Looks like a URN.
	my ($auth,$t,$id) = GeniHRN::Parse( $nodeid );

	return undef if $auth ne $OURDOMAIN or $t ne "node";

	return Node->Lookup( $id );
    }
 
    #
    # Looks like an old HRN, but we only want the last token for node lookup.
    #
    if ($nodeid =~ /\./) {
	($nodeid) = ($nodeid =~ /\.([-\w]*)$/);

	return Node->Lookup($nodeid);
    }
    
    # Assume it's a UUID, and pass it on as is.
    return Node->Lookup($nodeid);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
109
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
110
# Respond to a Resolve request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
111 112 113 114 115 116
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
117 118
    my $type       = lc( $argref->{'type'} );
    my $hrn        = $argref->{'hrn'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
119 120 121 122

    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
    }
123 124 125 126 127 128 129 130 131 132 133 134
    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
135 136 137
	return GeniResponse->MalformedArgsResponse();
    }
    # Allow lookup by uuid or hrn.
138
    if (! defined($uuid) && !defined( $hrn ) ) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
	return GeniResponse->MalformedArgsResponse();
    }
    if (defined($uuid) && !($uuid =~ /^[-\w]*$/)) {
	return GeniResponse->MalformedArgsResponse();
    }

    my $credential = GeniCredential->CreateFromSigned($cred);
    if (!defined($credential)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniCredential object");
    }
    
    #
    # Make sure the credential was issued to the caller, but no special
    # permission required to resolve component resources.
    #
    if ($credential->owner_uuid() ne $ENV{'GENIUUID'}) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "This is not your credential!");
    }
159
    if ($type eq "node") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
160 161 162
	my $node;
	
	if (defined($uuid)) {
163
	    $node= LookupNode($uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
164 165
	}
	else {
166
	    $node= LookupNode($hrn);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
167 168 169 170 171 172 173
	}
	if (!defined($node)) {
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
					undef, "Nothing here by that name");
	}
	
	# Return a blob.
174
	my $blob = { "hrn"          => "${PGENIDOMAIN}." . $node->node_id(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
175
		     "uuid"         => $node->uuid(),
176
		     "role"	    => $node->role(),
177
		     "hostname"     => $node->node_id() . ".${OURDOMAIN}",
178 179
		     "physctrl"     => 
			 Interface->LookupControl( $node->phys_nodeid() )->IP(),
180 181 182
		     "urn"          => GeniHRN::Generate( $OURDOMAIN,
							  "node",
							  $node->node_id() )
Leigh B. Stoller's avatar
Leigh B. Stoller committed
183 184 185 186 187 188 189 190 191 192 193 194 195
		   };

	#
	# Get the list of interfaces for the node.
	#
	my @interfaces;
	if ($node->AllInterfaces(\@interfaces) != 0) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not get interfaces for $uuid");
	}

	my @iblobs = ();
	foreach my $interface (@interfaces) {
196 197 198
	    next
		if (!defined($interface->switch_id()));
		
199 200
	    my $urn = GeniHRN::GenerateInterface( $OURDOMAIN, $node->node_id(),
						  $interface->iface() );
Leigh B. Stoller's avatar
Leigh B. Stoller committed
201 202 203 204 205 206
	    my $iblob = { "uuid"	=> $interface->uuid(),
			  "iface"	=> $interface->iface(),
			  "type"	=> $interface->type(),
			  "card"	=> $interface->card(),
			  "port"	=> $interface->port(),
			  "role"	=> $interface->role(),
207 208
			  "IP"		=> $interface->IP() || "",
			  "mask"	=> $interface->mask() || "",
Leigh B. Stoller's avatar
Leigh B. Stoller committed
209
			  "MAC"		=> $interface->mac(),
210 211 212 213 214
			  "switch_id"   => "${OURDOMAIN}." . 
			      $interface->switch_id(),
			  "switch_card"	=> $interface->switch_card(),
			  "switch_port"	=> $interface->switch_port(),
			  "wire_type"	=> $interface->wire_type(),
215
			  "urn"         => $urn
Leigh B. Stoller's avatar
Leigh B. Stoller committed
216 217 218 219 220 221 222 223 224 225 226 227
		      };

	    push(@iblobs, $iblob);
	}
	$blob->{'interfaces'} = \@iblobs
	    if (@iblobs);
	
	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
    }
    return GeniResponse->Create(GENIRESPONSE_UNSUPPORTED);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
#
# Discover resources on this component, returning a resource availablity spec
#
sub DiscoverResources($)
{
    my ($argref) = @_;
    my $credential = $argref->{'credential'};
    my $user_uuid  = $ENV{'GENIUSER'};

    $credential = GeniCredential->CreateFromSigned($credential);
    if (!defined($credential)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniCredential object");
    }
    # The credential owner/slice has to match what was provided.
243
    if ($user_uuid ne $credential->owner_uuid()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
244 245 246 247
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Invalid credentials for operation");
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
    if (!TBGetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
	# Cannot get the value, say no.
	$allow_externalusers = 0;
    }
    if (!$allow_externalusers) {
	my $user = GeniUser->Lookup($user_uuid, 1);
	# 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
265
    #
266
    # Use ptopgen in xml mode to spit back an xml file. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
267
    #
268
    if (! open(AVAIL, "$PTOPGEN -x -g -r -p GeniSlices |")) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
269 270 271
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }
272
    my $xml = "";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
273
    while (<AVAIL>) {
274
	$xml .= $_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
275 276 277 278 279
    }
    close(AVAIL);

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

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) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
297
    my $rspec      = $argref->{'rspec'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
298
    my $impotent   = $argref->{'impotent'};
299
    my $cred       = $argref->{'credential'};
300 301
    my $tick       = $argref->{'ticket'};
    my $uuid       = $argref->{'uuid'};
302
    my $vtopo      = $argref->{'virtual_topology'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
303
    my $owner_uuid = $ENV{'GENIUSER'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
304
    my $response   = undef;
305
    my $didfwsetup = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
306 307
    my $restorevirt = 0;	# Flag to restore virtual state
    my $restorephys = 0;	# Flag to restore physical state
308 309 310 311 312 313 314
    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
315

316 317
    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
318
    }
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    if (defined($uuid)) {
	if (!($uuid =~ /^[-\w]*$/)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Improper ticket uuid: $uuid");
	}
	$ticket = GeniTicket->Lookup($uuid);
	if (!defined($ticket)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"No such ticket here: $uuid");
	}
    }
    elsif (defined($rspec)) {
	if (! ($rspec =~ /^[\040-\176\012\015\011]+$/)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Improper rspec");
	}
	$rspec = XMLin($rspec, KeyAttr => [],
		       ForceArray => ["node", "link", "interface",
				      "interface_ref", "linkendpoints"]);
    }
    else {
	return GeniResponse->MalformedArgsResponse();
    }
    if ($isupdate) {
	$ticket = GeniTicket->CreateFromSignedTicket($tick);
	if (!defined($ticket)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not create GeniTicket object");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
348
    }
349
    my $credential = GeniCredential->CreateFromSigned($cred);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
350 351 352 353
    if (!defined($credential)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniCredential object");
    }
354
    my $slice_uuid = $credential->target_uuid();
355
    my $user_uuid  = $credential->owner_uuid();
356
        
357 358 359
    #
    # Make sure the credential was issued to the caller.
    #
360
    if ($user_uuid ne $ENV{'GENIUUID'}) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
361
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
362
				    "This is not your credential!");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
363
    }
364 365 366 367 368 369 370
    
    defined($credential) &&
	($credential->HasPrivilege( "pi" ) or
	 $credential->HasPrivilege( "instantiate" ) or
	 $credential->HasPrivilege( "bind" ) or
	 return GeniResponse->Create( GENIRESPONSE_FORBIDDEN, undef,
				      "Insufficient privilege" ));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
371

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    #
    # Deal with a duplicate ticket request, after verifying credential.
    #
    if (defined($uuid)) {
	#
	# Return the original ticket string, rather then creating and signing
	# a new version. Only the original requestor can get the ticket, which
	# can then be delegated if necessary. 
	#
	if ($user_uuid ne $ticket->owner_uuid()) {
	    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
					"Not your ticket!");
	}
	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $ticket->asString());
    }
    
    #
    # We need this below to sign the ticket.
    #
    my $authority = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
    if (!defined($authority)) {
	print STDERR " Could not get uuid from $EMULAB_PEMFILE\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
396

Leigh B. Stoller's avatar
Leigh B. Stoller committed
397
    #
398
    # Create slice from the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
399 400 401
    #
    my $slice = GeniSlice->Lookup($slice_uuid);
    if (!defined($slice)) {
402 403 404 405 406
	if ($isupdate) {
	    print STDERR "Could not locate slice $slice_uuid for Update\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No slice found for UpdateTicket");
	}
407
	$slice = CreateSliceFromCertificate($credential);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
408
	if (!defined($slice)) {
409
	    print STDERR "Could not create $slice_uuid\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
410
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
411
					"Could not create slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
412
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
413 414
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
415
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
416 417
    # Ditto the user.
    #
418
    my $user = GeniUser->Lookup($user_uuid, 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
419
    if (!defined($user)) {
420 421 422 423 424
	if ($isupdate) {
	    print STDERR "Could not locate $user_uuid for UpdateTicket\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No user found for UpdateTicket");
	}
425
	$user = CreateUserFromCertificate($credential->owner_cert());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
426
	if (!defined($user)) {
427
	    print STDERR "No user $user_uuid in the ClearingHouse\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
428 429 430 431 432
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
			    "Could not get user info from ClearingHouse");
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
    if (!TBGetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
	# Cannot get the value, say no.
	$allow_externalusers = 0;
    }
    if (!$allow_externalusers && !$user->IsLocal()) {
	return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				    "External users temporarily denied");
    }
    
    #
447
    # For now all tickets expire very quickly (minutes), but once the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    # ticket is redeemed, it will expire according to the rspec request.
    #
    if (exists($rspec->{'valid_until'})) {
	my $expires = $rspec->{'valid_until'};

	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");
	}
	
	#
	# No more then 24 hours out ... Needs to be a sitevar?
	#
	my $diff = $when - time();
	if ($diff < (60 * 15) || $diff > (3600 * 24)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"valid_until out of range");
	}
    }
    else {
	# Give it a reasonable default for later when the ticket is redeemed.
	$rspec->{'valid_until'} =
	    POSIX::strftime("20%y-%m-%dT%H:%M:%S", gmtime(time() + (3600*1)));
    }
478 479 480 481 482 483 484

    #
    # Lock the ticket so it cannot be released.
    #
    if (defined($ticket) && $ticket->stored() && $ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
485 486 487 488 489 490
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
491 492 493
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
494
    }
495 496 497
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
498 499
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
500 501 502
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
503

504
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
505
    # For now, there can be only a single toplevel aggregate per slice.
506
    # The existence of an aggregate means the slice is active here. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
507
    #
508 509 510 511 512 513
    if (!$isupdate) {
	my $aggregate = GeniAggregate->SliceAggregate($slice);
	if (defined($aggregate)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Already have an aggregate for slice");
	    goto bad;
514 515 516 517 518 519 520 521
	}
    }

    #
    # Firewall hack; just a flag in the rspec for now.
    #
    if (exists($rspec->{'needsfirewall'}) && $rspec->{'needsfirewall'}) {
	if ($slice->SetFirewallFlag($rspec->{'needsfirewall'}) != 0) {
522 523
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
524 525
	}
    }
526 527

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
528
    # We need this now so we can form a virtual topo.
529
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    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();
    
    #
    # 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);
551 552 553 554 555 556 557 558 559 560

    # This is where nodes are parked until a ticket is redeemed.
    my $reserved_holding = Experiment->Lookup("GeniSlices", "reservations");
    if (!defined($reserved_holding)) {
	#
	# This experiment has to exist!
	#
	print STDERR "Could not find Geni reservations experiment!\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
561 562
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
563
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
564 565
    # 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
566 567
    # cannot be granted.
    #
568 569 570 571
    my %namemap  = ();
    my %tofree   = ();
    my %colomap  = ();
    my %ifacemap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
572
    my %nodemap  = ();
573
    my @nodeids  = ();
574
    my @dealloc;
575 576 577 578 579 580 581 582

    #
    # 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
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
	$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;
	}
	
602 603 604 605 606 607 608
	foreach my $ref (@{$ticket->rspec()->{'node'}}) {
	    my $resource_uuid = $ref->{'component_uuid'} || $ref->{'uuid'};
	    my $manager_uuid  = $ref->{'component_manager_uuid'};
	    my $node_nickname = $ref->{'virtual_id'} || $ref->{'nickname'};
	    my $colocate      = $ref->{'colocate'} || $ref->{'phys_nickname'};

	    # Let remote nodes pass through.
609
	    next
610 611 612
		if (defined($manager_uuid) &&
		    !GeniHRN::Equal( $manager_uuid, $ENV{'MYURN'} ) &&
		    $manager_uuid ne $ENV{'MYUUID'});
613

614
	    my $node = LookupNode($resource_uuid);
615 616
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
617
				 "Bad resource $resource_uuid in ticket");
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
		goto bad;
	    }

	    # Grab the reservation. We will want to release unused nodes,
	    # but only if not already assigned to the slice.
	    my $reservation = $node->Reservation();
	    if (defined($reservation)) {
		$tofree{$resource_uuid} = $node
		    if ($reservation->SameExperiment($reserved_holding));
	    }
	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
633

Leigh B. Stoller's avatar
Leigh B. Stoller committed
634 635
    print STDERR Dumper($rspec);

636
    foreach my $ref (@{$rspec->{'node'}}) {
637 638
	my $resource_uuid = $ref->{'component_uuid'} || $ref->{'uuid'};
	my $manager_uuid  = $ref->{'component_manager_uuid'};
639
	my $manager_urn   = $ref->{'component_manager_urn'};
640 641
	my $node_nickname = $ref->{'virtual_id'} || $ref->{'nickname'};
	my $colocate      = $ref->{'colocate'} || $ref->{'phys_nickname'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
642 643 644 645 646
	my $virtualization_type    = $ref->{'virtualization_type'};
	my $virtualization_subtype = $ref->{'virtualization_subtype'};
	my $exclusive     = $ref->{'exclusive'};
	my $pctype        = "pc";
	my $osname        = "";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
647 648
	my $node;

649
	# Let remote nodes pass through.
650
	next
651 652 653
	    if (defined($manager_uuid) &&
		!GeniHRN::Equal( $manager_uuid, $ENV{'MYURN'} ) &&
		$manager_uuid ne $ENV{'MYUUID'});
654

Leigh B. Stoller's avatar
Leigh B. Stoller committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	if (defined($virtualization_type)) {
	    if ($virtualization_type eq "emulab-vnode") {
		$pctype = "pcvm";

		if (defined($virtualization_subtype)) {
		    if ($virtualization_subtype eq "emulab-jail") {
			$osname = "FBSD-JAIL";
		    }
		    elsif ($virtualization_subtype eq "emulab-openvz") {
			$osname = "OPENVZ-STD";
		    }
		}
		else {
		    goto raw;
		}
	    }
	    else {
	      raw:
		# Lets force to exclusive real node.
		$ref->{'exclusive'} = $exclusive = 1;
		$ref->{'virtualization_type'} = "raw";
		$pctype = "pc";
		$osname = "RHL90-STD";
	    }
	}
	else {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
682
				     "Must provide a virtualization_type");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
683 684 685
	    goto bad;

	}
686 687 688 689 690 691
	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
692
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
693
	# Allow wildcarding.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
694
	#
695 696 697 698 699 700
	if (!defined($resource_uuid) || $resource_uuid eq "*") {
	    if (defined($colocate) && exists($colomap{$colocate})) {
		$node = $colomap{$colocate};
	    }
	    elsif ($isupdate && exists($namemap{$node_nickname})) {
		$node = $namemap{$node_nickname};
701
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
702 703
	}
	else {
704
	    $node = LookupNode($resource_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
705 706 707 708 709 710 711

	    if (!defined($node)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Bad resource $resource_uuid");
		goto bad;
	    }
712 713
	    $osname = $node->default_osid()
		if (defined($node->default_osid()));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
714
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
	my $virtnode =
	    $virtexperiment->NewTableRow("virt_nodes",
					 {"vname"   => $node_nickname,
					  "type"    => $pctype,
					  "osname"  => $osname,
					  "ips"     => '', # deprecated
					  "cmd_line"=> '', # bogus
					  "fixed"   => (defined($node) ?
						     $node->node_id() : "")});
	$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};
	
734 735 736 737
	#
	# Look for interface forward declarations that will be used later
	# in the link specifications. 
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
738 739 740
	next
	    if (!exists($ref->{'interface'}));
	
741 742 743 744 745 746 747 748 749 750 751 752 753
	foreach my $linkref (@{$ref->{'interface'}}) {
	    my $component_id = $linkref->{"component_id"};
	    my $virtual_id   = $linkref->{"virtual_id"};

	    if (!defined($virtual_id)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
			     "Must provide a virtual_id for interfaces");
		goto bad;
	    }
	    
	    $ifacemap{$node_nickname} = {}
	        if (!exists($ifacemap{$node_nickname}));

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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
761 762
	    # This is used after the mapper runs since it uses vname:vport.
	    $ifacemap{"$node_nickname:$vport"} = $linkref;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
763
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
764 765
    }

766 767 768
    goto skiplinks
	if (!exists($rspec->{'link'}));
    
769 770 771 772
    #
    # Now deal with links for wildcarded nodes. We need to fill in the
    # node_uuid.
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
773 774
    my $linknum = 1;
    
775 776
    foreach my $linkref (@{$rspec->{'link'}}) {
	my $nickname   = $linkref->{"nickname"} || $linkref->{"virtual_id"};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
777 778
	my $istunnel   = (exists($linkref->{'link_type'}) &&
			  $linkref->{'link_type'} eq "tunnel");
779 780
	my $interfaces = $linkref->{'linkendpoints'} ||
	    $linkref->{'interface_ref'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
781
	my $ifacenum   = 1;
782

783 784 785 786 787
	if (!defined($nickname)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Must provide a virtual_id for links");
	    goto bad;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
788 789 790 791 792

	if (!$istunnel) {
	    $virtexperiment->NewTableRow("virt_lan_lans",
					 {"vname" => $nickname});
	}
793 794 795 796 797 798
	
	foreach my $ref (@{ $interfaces }) {
	    my $node_nickname = $ref->{'virtual_node_id'} ||
		$ref->{'node_nickname'};
	    my $iface_id     = $ref->{'virtual_interface_id'} ||
		$ref->{'iface_name'};
799

800
	    if (!defined($node_nickname)) {
801 802 803 804 805 806 807 808 809
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "$nickname: Need node id for links");
		goto bad;
	    }
	    if (!defined($iface_id)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "$nickname: Need interface id for links");
810 811 812
		goto bad;
	    }

813
	    if ($istunnel) {
814
		# Might be the other side. Skip for now; might bite later.
815 816
		next
		    if (!exists($namemap{$node_nickname}));
817

818 819 820
		# Not doing anything else.
		next;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
821
	    if (!exists($ifacemap{$node_nickname})) {
822 823 824
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "$nickname: No such virtual_node_id: ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
825
				 "$node_nickname");
826
		goto bad;
827
	    }
828
	    
829
	    #
830
	    # Sanity check the interface.
831
	    #
832 833 834 835 836 837 838
	    if (!exists($ifacemap{$node_nickname}->{$iface_id})) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "$nickname: No such interface on component: ".
				 "$node_nickname:$iface_id");
		goto bad;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
839 840
	    my $iface_ref   = $ifacemap{$node_nickname}->{$iface_id}->{"rspec"};
	    my $iface_name  = $iface_ref->{"component_id"} || "";
841 842 843 844
	    if( GeniHRN::IsValid( $iface_name ) ) {
		my ($urn_authority,$urn_node,$urn_iface) = GeniHRN::ParseInterface( $iface_name );
		$iface_name = $urn_iface;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
845 846 847 848 849 850 851 852 853 854 855 856 857
	    my $iface_vport = $ifacemap{$node_nickname}->{$iface_id}->{"vport"};

	    # XXX
	    my $ip     = "10.10.${linknum}.${ifacenum}";
	    my $mask   = "255.255.255.0";
	    my $member = "$node_nickname:$iface_vport";
	    
	    $virtexperiment->NewTableRow("virt_lans",
					 {"vname"       => $nickname,
					  "vnode"       => $node_nickname,
					  "vport"       => $iface_vport,
					  "ip"          => $ip,
					  "delay"       => 0.0,
858
					  "bandwidth"   => 100000, # kbps
Leigh B. Stoller's avatar
Leigh B. Stoller committed
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
					  "lossrate"    => 0.0,
					  "member"      => $member,
					  "mask"        => $mask,
					  "rdelay"      => 0.0,
					  "rbandwidth"  => 100000, # kbps
					  "rlossrate"   => 0.0,
					  "fixed_iface" => $iface_name});
	    $ifacenum++;
	}
	$linknum++;
    }
  skiplinks:
    $virtexperiment->Dump();
    $virtexperiment->Store();

    # Must chdir to the work directory for the mapper.
    if (! chdir($slice_experiment->WorkDir())) {
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef);
	goto bad;
    }
879

Leigh B. Stoller's avatar
Leigh B. Stoller committed
880 881 882
    # Do a render cause its nice to have on the show experiment page.
    system("$PRERENDER -r $pid $eid");
    system("$PRERENDER -t $pid $eid");
883

Leigh B. Stoller's avatar
Leigh B. Stoller committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    #
    # Now run the mapper in impotent mode. The idea is get a solution
    # without allocating any nodes. If we get a solution, and we can
    # allocate the nodes, we update the rspec with the physical info.
    #
    my $tmpfile = POSIX::tmpnam();

    # First a prerun to get the node counts and verify topo.
    system("$VTOPGEN -p $pid $eid");
    if ($?) {
	$response =
	    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "Could not verify topo");
	goto bad;
    }
    system("$MAPPER -n -d -v -m 1 -u -o $tmpfile $pid $eid");
    if ($?) {
	$response =
	    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "Could not map to resources");
	unlink($tmpfile);
	if ($isupdate) {
	    $slice_experiment->RemovePhysicalState();
	    $slice_experiment->RestorePhysicalState();
908
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
909
	goto bad;
910
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
911 912 913 914 915 916 917 918 919 920 921
    my $solution = XMLin($tmpfile, KeyAttr => [],
			 ForceArray => ["node", "link", "interface",
					"interface_ref", "linkendpoints"]);
    unlink($tmpfile);
    print Dumper($solution);

    foreach my $ref (@{$solution->{'node'}}) {
	my $virtual_id     = $ref->{"virtual_id"};
	my $component_uuid = $ref->{"component_uuid"};
	my $rspec          = $nodemap{$virtual_id}->{'rspec'};
	my $virtnode       = $nodemap{$virtual_id}->{'virtnode'};
922
	my $node           = LookupNode($component_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
923 924 925 926
	my $colocate       = $rspec->{'colocate'} ||
	    $rspec->{'phys_nickname'};
	
	$rspec->{'component_uuid'} = $component_uuid;
927
	$rspec->{'component_manager_urn'} = $ENV{'MYURN'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
	$rspec->{'component_manager_uuid'} = $ENV{'MYUUID'};

	# Also update the virtexperiment table row.
	$virtnode->fixed($node->node_id());

	#
	# Shared and remote nodes do not need to be allocated.
	#
	# XXX This is going to cause breakage since the reservations
	# are not recorded anyplace until the ticket is redeemed.
	#
	if (! ($node->sharing_mode() || $node->isremotenode)) {
	    # Need to allocate this node unless already mapped.
	    push(@nodeids, $node->node_id())
		if (!exists($namemap{$virtual_id}));
	    # Or make sure we do not free it if already allocated.
	    delete($tofree{$component_uuid})
		if ($isupdate && exists($tofree{$component_uuid}));
	}
	$namemap{$virtual_id} = $node;
	$colomap{$colocate} = $node
	    if (defined($colocate));
    }
    foreach my $ref (@{$solution->{'link'}}) {
	my $nickname          = $ref->{"virtual_id"};
	my $interfaces        = $ref->{'interface_ref'};

	foreach my $iface_ref (@{ $interfaces }) {
	    my $virtual_node_id   = $iface_ref->{"virtual_node_id"};
	    my $virtual_port_id   = $iface_ref->{"virtual_port_id"};
	    my $component_id      = $iface_ref->{"component_id"};
	    my $linkref     = $ifacemap{"$virtual_node_id:$virtual_port_id"};
	
	    $linkref->{'component_id'} = $component_id;
	}
    }
    # Store the virt topo again since we changed it above.
    $virtexperiment->Dump();
    $virtexperiment->Store();

    print Dumper($rspec);

    # Nalloc might fail if the node gets picked up by someone else.
    if (@nodeids && !$impotent) {
	system("$NALLOC $pid reservations @nodeids");
	if (($? >> 8) < 0) {
	    $response =
		GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				     "Allocation failure");
	    goto bad;
	}
	elsif (($? >> 8) > 0) {
	    $response =
		GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				     "Could not allocate some nodes");
	    goto bad;
	}
	# In case the code below fails, before ticket is created.
	@dealloc = @nodeids;
    }
    
989
    #
990
    # Create a new ticket.
991
    #
992 993
    my $newticket = GeniTicket->Create($authority, $user, $rspec);
    if (!defined($newticket)) {
994 995 996 997
	$response =
	    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "Could not create GeniTicket object");
	goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
998
    }
999
    if ($newticket->Sign() || $newticket->Store()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1000 1001 1002
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					 "Could not sign Ticket");
	goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1003
    }
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

    if ($isupdate) {
	#
	# Delete (not release) the old ticket. 
	#
	$ticket->Delete(TICKET_RELEASED)
	    if ($ticket->stored());

	# And release any nodes we no longer wanted.
	if (keys(%tofree)) {
	    my @ids = map { $_->node_id() } values(%tofree);

	    system("export NORELOAD=1; ".
		   "$NFREE -x -q GeniSlices reservations @ids");
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1020
    $slice->UnLock();
1021
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $newticket->asString());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1022
  bad:
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1023 1024
    system("$PRERENDER -r $pid $eid")
	if (defined($slice_experiment));
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    #
    # Have to be careful in a ticket update, to not release nodes that
    # might be referenced in the old ticket. 
    #
    if ($isupdate) {
	if (defined($newticket)) {
	    # Delete, not Release (which frees nodes).
	    $newticket->Delete(TICKET_PURGED);
	}
	if (@dealloc) {
	    system("export NORELOAD=1; ".
		   "$NFREE -x -q GeniSlices reservations @dealloc");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1038 1039 1040 1041
	if (defined($slice_experiment) && $restorevirt) {
	    $slice_experiment->RemoveVirtualState();
	    $slice_experiment->RestoreVirtualState();
	}
1042
    }
1043 1044 1045 1046 1047 1048 1049 1050 1051
    else {
	# Release will free the nodes.
	if (defined($newticket)) {
	    $newticket->Release(TICKET_PURGED);
	}
	elsif (@dealloc) {
	    system("export NORELOAD=1; ".
		   "$NFREE -x -q GeniSlices reservations @dealloc");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1052 1053 1054 1055 1056 1057 1058
	#
	# Lets leave the experiment lying around; it will get cleaned
	# up when the slice is expired. But need to kill off the virtual
	# topo we might have added to it. 
	#
	$slice_experiment->RemoveVirtualState()
	    if (defined($slice_experiment));
1059
    }
1060
  unlock:
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1061 1062
    $slice->UnLock()
	if (defined($slice));
1063 1064
    $ticket->UnLock()
	if (defined($ticket) && $ticket->stored());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1065
    return $response;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1066 1067 1068
}

#
1069
# Redeem a ticket
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1070
#
1071
sub RedeemTicket($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1072 1073
{
    my ($argref) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1074

1075
    return SliverWork($argref, 0);
1076
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1077

1078
#
1079
# Update a sliver
1080 1081 1082 1083
#
sub UpdateSliver($)
{
    my ($argref) = @_;
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099

    return SliverWork($argref, 1);
}

#
# Utility function for above routines.
#
sub SliverWork($$)
{
    my ($argref, $isupdate) = @_;
    my $credstr    = $argref->{'credential'};
    my $ticketstr  = $argref->{'ticket'};
    my $impotent   = $argref->{'impotent'};
    my $keys       = $argref->{'keys'};
    my $extraargs  = $argref->{'extraargs'};
    my $didfwsetup = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1100
    my $restorephys = 0;	# Flag to restore physical state
1101 1102 1103 1104

    $impotent = 0
	if (!defined($impotent));

1105
    if (! (defined($credstr) && defined($ticketstr))) {
1106 1107
	return GeniResponse->Create(GENIRESPONSE_BADARGS);
    }
1108
    my $credential = GeniCredential->CreateFromSigned($credstr);
1109
    if (!defined($credential)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1110
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
1111 1112 1113 1114 1115 1116 1117 1118 1119
				    "Could not create GeniCredential object");
    }
    #
    # Make sure the credential was issued to the caller.
    #
    if ($credential->owner_uuid() ne $ENV{'GENIUUID'}) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "This is not your credential!");
    }
1120 1121 1122 1123 1124 1125
    $credential->HasPrivilege( "pi" ) or
	$credential->HasPrivilege( "instantiate" ) or
	$credential->HasPrivilege( "control" ) or
	return GeniResponse->Create( GENIRESPONSE_FORBIDDEN, undef,
				     "Insufficient privilege" );

1126 1127 1128 1129 1130 1131 1132 1133
    my $owner_uuid = $credential->owner_uuid();
    my $owner_cert = $credential->owner_cert();
    my $message    = "Error creating sliver/aggregate";

    my $ticket = GeniTicket->CreateFromSignedTicket($ticketstr);
    if (!defined($ticket)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniTicket object");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1134
    }
1135 1136 1137 1138
    # Only unredeemed tickets are stored in the DB.
    if (!$ticket->stored()) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "This ticket was already redeemed!");
1139
    }
1140 1141
    # Make sure the ticket was issued to the caller.
    if ($ticket->owner_uuid() ne $ENV{'GENIUUID'}) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1142
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
				    "This is not your ticket!");
    }
    # Make sure the ticket target is this Manager
    if ($ticket->target_uuid() ne $ENV{'MYUUID'}) {
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "This ticket is for another authority!");
    }

    #
    # For now, there can be only a single toplevel aggregate per slice.
    #
    my $aggregate;
    my $slice;
    my $slice_uuid;
    
    if ($isupdate) {
	$aggregate = GeniAggregate->Lookup($credential->target_uuid());

	if (!defined($aggregate)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Sliver cannot be found");
	}
	$slice_uuid = $aggregate->slice_uuid();
	$slice = GeniSlice->Lookup($slice_uuid);
	if (!defined($slice)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No slice record for $slice_uuid");
	}
    }
    else {
	$slice_uuid = $credential->target_uuid();
	$slice = GeniSlice->Lookup($slice_uuid);
	if (!defined($slice)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No slice record for $slice_uuid");
	}
	$aggregate  = GeniAggregate->SliceAggregate($slice);

	if (defined($aggregate)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Already have an aggregate for slice");
	}
    }
    if ($ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1188 1189
    }
    if ($slice->Lock() != 0) {
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
	$ticket->UnLock();
	return GeniResponse->BusyResponse("slice");
    }

    # Do not redeem an expired ticket.
    if ($ticket->Expired()) {
	$slice->UnLock();
	$ticket->UnLock();
	return GeniResponse->Create(GENIRESPONSE_EXPIRED, undef,
				    "Ticket has expired");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1200
    }
1201 1202 1203
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
1204
	$ticket->UnLock();
1205 1206 1207
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1208

1209
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1210
    # Create the user.
1211 1212 1213
    #
    my $owner = GeniUser->Lookup($owner_uuid);
    if (!defined($owner)) {
1214
	$owner = CreateUserFromCertificate($owner_cert);
1215 1216 1217 1218 1219
	if (!defined($owner)) {
	    print STDERR "No user $owner_uuid in the ClearingHouse\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No user record for $owner_uuid");
	}
1220
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1221 1222 1223
    if (!$owner->IsLocal() && defined($keys)) {
	$owner->Modify(undef, undef, $keys);
    }
1224

1225
    my $experiment = GeniExperiment($slice);
1226
    if (!defined($experiment)) {
1227 1228
	$slice->UnLock();
	$ticket->UnLock();
1229 1230 1231 1232 1233 1234 1235
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "No local experiment for slice");
    }

    #
    # Figure out what nodes to allocate or free. 
    #
1236 1237 1238
    my %physnodes= ();
    my %nodemap  = ();
    my %linkmap  = ();
1239
    my %toalloc  = ();
1240
    my %colomap  = ();
1241
    my @allocated= ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1242 1243
    my @freenodes= ();
    my @freelinks= ();
1244 1245
    my $pid      = $experiment->pid();
    my $eid      = $experiment->eid();
1246
    my $rspec    = $ticket->rspec();
1247
    my $needplabslice = 0;
1248

1249 1250
    print Dumper($rspec);

1251
    #
1252
    # Find current slivers and save.
1253
    #
1254
    if (defined($aggregate)) {
1255
	my @slivers;
1256 1257 1258
	if ($aggregate->SliverList(\@slivers) != 0) {
	    $message = "Could not get sliverlist for $aggregate";
	    goto bad;
1259 1260 1261
	}
	foreach my $s (@slivers) {
	    if (ref($s) eq "GeniSliver::Node") {
1262
		$nodemap{$s->nickname()} = $s;
1263
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1264 1265
	    elsif (ref($s) eq "GeniAggregate::Link" ||
		   ref($s) eq "GeniAggregate::Tunnel") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1266 1267
		# XXX See the constructor in GeniAggregate.
		my ($linkname) = ($s->hrn() =~ /\.([-\w]*)$/);
1268
		$linkmap{$linkname} = $s;
1269 1270
	    }
	    else {
1271 1272
		$message = "Only nodes or links allowed";
		goto bad;
1273 1274 1275 1276
	    }
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1277 1278 1279 1280 1281 1282 1283 1284
    #
    # Figure out new expiration time; this is the time at which we can
    # idleswap the slice out. 
    #
    if (exists($rspec->{'valid_until'})) {
	my $expires = $rspec->{'valid_until'};

	if (! ($expires =~ /^[-\w:.\/]+/)) {
1285