GeniCM.pm.in 71.3 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;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
34
use libtestbed;
35
use emutil;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
36
# Hate to import all this crap; need a utility library.
37
use libdb qw(TBGetSiteVar);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
38
use User;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
39
use Node;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
40
use libadminctrl;
41
use Interface;
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 46 47
use Date::Parse;
use POSIX qw(strftime);
use Time::Local;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
use Experiment;
49
use Firewall;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
50 51 52 53 54 55 56 57

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
58
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
59
my $CREATEEXPT     = "$TB/bin/batchexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
60
my $ENDEXPT        = "$TB/bin/endexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
61
my $NALLOC	   = "$TB/bin/nalloc";
62
my $NFREE	   = "$TB/bin/nfree";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
63
my $AVAIL	   = "$TB/sbin/avail";
64
my $PTOPGEN	   = "$TB/libexec/ptopgen";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
65 66
my $TBSWAP	   = "$TB/bin/tbswap";
my $SWAPEXP	   = "$TB/bin/swapexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
67 68 69 70
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
71 72

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
73
# Respond to a Resolve request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
74 75 76 77 78 79 80
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
    my $type       = $argref->{'type'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
81
    my $hrn;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
82 83 84 85 86 87 88 89

    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
    }
    if (! (defined($type) && ($type =~ /^(Node)$/))) {
	return GeniResponse->MalformedArgsResponse();
    }
    # Allow lookup by uuid or hrn.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
90
    if (! defined($uuid)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
	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!");
    }
    if ($type eq "Node") {
	my $node;
	
	if (defined($uuid)) {
	    $node= Node->Lookup($uuid);
	}
	else {
	    #
	    # We only want the last token for node lookup.
	    #
	    if ($hrn =~ /\./) {
122
		($hrn) = ($hrn =~ /\.([-\w]*)$/);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
123 124 125 126 127 128 129 130 131
	    }
	    $node= Node->Lookup($hrn);
	}
	if (!defined($node)) {
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
					undef, "Nothing here by that name");
	}
	
	# Return a blob.
132
	my $blob = { "hrn"          => "${PGENIDOMAIN}." . $node->node_id(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
133
		     "uuid"         => $node->uuid(),
134
		     "role"	    => $node->role(),
135
		     "hostname"     => $node->node_id() . ".${OURDOMAIN}",
136 137
		     "physctrl"     => 
			 Interface->LookupControl( $node->phys_nodeid() )->IP(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
138 139 140 141 142 143 144 145 146 147 148 149 150
		   };

	#
	# 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) {
151 152 153
	    next
		if (!defined($interface->switch_id()));
		
Leigh B. Stoller's avatar
Leigh B. Stoller committed
154 155 156 157 158 159
	    my $iblob = { "uuid"	=> $interface->uuid(),
			  "iface"	=> $interface->iface(),
			  "type"	=> $interface->type(),
			  "card"	=> $interface->card(),
			  "port"	=> $interface->port(),
			  "role"	=> $interface->role(),
160 161
			  "IP"		=> $interface->IP() || "",
			  "mask"	=> $interface->mask() || "",
Leigh B. Stoller's avatar
Leigh B. Stoller committed
162
			  "MAC"		=> $interface->mac(),
163 164 165 166 167
			  "switch_id"   => "${OURDOMAIN}." . 
			      $interface->switch_id(),
			  "switch_card"	=> $interface->switch_card(),
			  "switch_port"	=> $interface->switch_port(),
			  "wire_type"	=> $interface->wire_type(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
168 169 170 171 172 173 174 175 176 177 178 179
		      };

	    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
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
#
# 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.
195
    if ($user_uuid ne $credential->owner_uuid()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
196 197 198 199
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Invalid credentials for operation");
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    #
    # 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
217
    #
218
    # Use ptopgen in xml mode to spit back an xml file. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
219
    #
220
    if (! open(AVAIL, "$PTOPGEN -x -g -r -p GeniSlices |")) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
221 222 223
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }
224
    my $xml = "";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
225
    while (<AVAIL>) {
226
	$xml .= $_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
227 228 229 230 231
    }
    close(AVAIL);

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
233
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
234
# Respond to a GetTicket request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
235 236 237 238 239
#
sub GetTicket($)
{
    my ($argref) = @_;
    my $rspec      = $argref->{'rspec'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
240
    my $impotent   = $argref->{'impotent'};
241
    my $cred       = $argref->{'credential'};
242
    my $vtopo      = $argref->{'virtual_topology'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
243
    my $owner_uuid = $ENV{'GENIUSER'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
244
    my $response   = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
245

246 247
    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
248
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
249 250 251
    if (! (defined($rspec) && ($rspec =~ /^[-\w]+$/))) {
	GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
			     "Improper rspec");	
Leigh B. Stoller's avatar
Leigh B. Stoller committed
252
    }
253
    $rspec = XMLin($rspec, ForceArray => ["node", "link", "linkendpoints"]);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
254

Leigh B. Stoller's avatar
Leigh B. Stoller committed
255 256 257
    $impotent = 0
	if (!defined($impotent));

258
    my $credential = GeniCredential->CreateFromSigned($cred);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
259 260 261 262
    if (!defined($credential)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniCredential object");
    }
263
    my $slice_uuid = $credential->target_uuid();
264 265
    my $user_uuid  = $credential->owner_uuid();
    
266

267 268 269 270
    #
    # Make sure the credential was issued to the caller.
    #
    if ($credential->owner_uuid() ne $ENV{'GENIUUID'}) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
271
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
272
				    "This is not your credential!");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
273
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
274

275 276 277 278 279 280
    $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
281
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
282
    # Create slice form the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
283 284 285
    #
    my $slice = GeniSlice->Lookup($slice_uuid);
    if (!defined($slice)) {
286
	$slice = CreateSliceFromCertificate($credential);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
287
	if (!defined($slice)) {
288
	    print STDERR "Could not create $slice_uuid\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
289
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
290
					"Could not create slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
291
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
292 293
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
294
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
295 296
    # Ditto the user.
    #
297
    my $user = GeniUser->Lookup($user_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
298
    if (!defined($user)) {
299
	$user = CreateUserFromCertificate($credential->owner_cert());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
300
	if (!defined($user)) {
301
	    print STDERR "No user $user_uuid in the ClearingHouse\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
302 303 304 305 306
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
			    "Could not get user info from ClearingHouse");
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320
    #
    # 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");
    }
    
    #
321
    # For now all tickets expire very quickly (minutes), but once the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    # 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)));
    }
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
	return GeniResponse->BusyResponse();
    }
360 361 362 363 364 365
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
366

367
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
368
    # For now, there can be only a single toplevel aggregate per slice.
369
    # The existence of an aggregate means the slice is active here. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
370 371 372 373 374 375 376
    #
    my $aggregate = GeniAggregate->SliceAggregate($slice);
    if (defined($aggregate)) {
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Already have an aggregate for slice");
    }
377 378 379 380 381 382 383 384 385 386 387

    #
    # Say a ticket already exists in the DB? Lets throw that ticket
    # away and generate a new one. This is partly a debugging
    # mechanism.  To really do this correctly, would want to merge in
    # the existing resources with the new rspec request. Do not
    # want to go there yet.
    #
    my $existing_ticket = GeniTicket->LookupForSlice($slice);
    if (defined($existing_ticket)) {
	print STDERR "Releasing existing ticket $existing_ticket\n";
388
	if ($existing_ticket->Release(TICKET_EXPIRED) != 0) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
	    print STDERR "Error releasing existing ticket $existing_ticket\n";
	    $slice->UnLock();
	    return GeniResponse->Create(GENIRESPONSE_ERROR);
	}
    }

    #
    # Firewall hack; just a flag in the rspec for now.
    #
    if (exists($rspec->{'needsfirewall'}) && $rspec->{'needsfirewall'}) {
	if ($slice->SetFirewallFlag($rspec->{'needsfirewall'}) != 0) {
	    $slice->UnLock();
	    return GeniResponse->Create(GENIRESPONSE_ERROR);
	}
    }
    
    my $experiment = GeniExperiment($slice);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
406
    if (!defined($experiment)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
407 408 409
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_ERROR,
				    undef, "Internal Error");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
410 411
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
412
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
413 414
    # 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
415 416
    # cannot be granted.
    #
417
    # XXX Simpleminded.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
418
    #
419
    my %namemap = ();
420 421
    my %physmap = ();
    my %virtmap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
422
    my @nodeids = ();
423
    my @dealloc;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
424 425 426
    my $pid     = $experiment->pid();
    my $eid     = $experiment->eid();

427 428
    foreach my $ref (@{$rspec->{'node'}}) {
	my $resource_uuid = $ref->{'uuid'};
429
	my $node_nickname = $ref->{'nickname'};
430
	my $phys_nickname = $ref->{'phys_nickname'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
431
	my $virtualization_type = $ref->{'virtualization_type'};
432
	my $sliver_uuid   = NewUUID();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
433 434 435 436 437 438
	my $node;

	#
	# Mostly for debugging right now, allow a wildcard.
	#
	if ($resource_uuid eq "*") {
439 440 441 442 443 444
	    if (defined($phys_nickname) && exists($physmap{$phys_nickname})) {
		$node = $physmap{$phys_nickname};
	    }
	    else {
		$node = FindFreeNode($virtualization_type, @nodeids);
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
	    
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_UNAVAILABLE,
						 undef,
						 "No free nodes for wildcard");
		goto bad;
	    }
	    $resource_uuid = $node->uuid();
	    $ref->{'uuid'} = $node->uuid();
	}
	else {
	    $node = Node->Lookup($resource_uuid);

	    if (!defined($node)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Bad resource $resource_uuid");
		goto bad;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
464
	}
465 466 467 468
	# We assign the sliver uuids here so that user can associate
	# slivers with parts of the rspec later.
	$ref->{'sliver_uuid'} = $sliver_uuid;
	
469 470 471 472 473 474
	#
	# Widearea nodes do not need to be allocated, but for now all
	# I allow is a plabdslice node.
	#
	if ($node->isremotenode()) {
	    if (! $node->isplabphysnode()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
475 476 477 478
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Only plab widearea nodes");
		goto bad;
479
	    }
480
	    goto skipalloc;
481
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
482 483

	#
484
	# See if the node is already reserved. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
485 486 487
	#
	my $reservation = $node->Reservation();
	if (defined($reservation)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
488 489 490 491
	    $response =
		GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				     "$resource_uuid ($node) not available");
	    goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
492
	}
493 494 495 496 497 498
	# watch for duplicates, as for multiple vnodes on a pnode.
	push(@nodeids, $node->node_id())
	    if (! grep {$_ eq $node->node_id()} @nodeids);

      skipalloc:
	$virtmap{$sliver_uuid}   = $node;
499
	# For wildcarded nodes in links.
500
	$namemap{$node_nickname} = $sliver_uuid
501
	    if (defined($node_nickname));
502 503
	$physmap{$phys_nickname} = $node
	    if (defined($phys_nickname));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
504
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
505

Leigh B. Stoller's avatar
Leigh B. Stoller committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    #
    # A sitevar controls how many total nodes external users can allocate.
    #
    # XXX All this policy stuff is a whack job for the initial release. 
    #
    my $max_externalnodes = 0;
    if (!TBGetSiteVar('protogeni/max_externalnodes', \$max_externalnodes)){
	# Cannot get the value, say none.
	$max_externalnodes = 0;
    }
    if (scalar(@nodeids) > $max_externalnodes) {
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
			   "Too many nodes; limited to $max_externalnodes");
    }
    # Check current usage by dipping into the libadminctrl library.
    my $curusage = libadminctrl::LoadCurrent($experiment->creator(),
					     $experiment->pid(),
					     $experiment->gid());
    if (!defined($curusage)) {
	$slice->UnLock();
	print STDERR "Could not get current usage from adminctl library\n";
	return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				    "Temporarily unavailable");
    }
    if ($curusage->{"nodes"}->{'project'} + scalar(@nodeids) >=
	$max_externalnodes) {
	$slice->UnLock();
	my $nodesleft = $max_externalnodes - $curusage->{"nodes"}->{'project'};
	return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				    "Too many nodes; limited to $nodesleft");
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
539
    # Nalloc might fail if the node gets picked up by someone else.
540
    if (@nodeids && !$impotent) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
541
	system("$NALLOC $pid $eid @nodeids");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
542
	if (($? >> 8) < 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
543 544 545 546
	    $response =
		GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				     "Allocation failure");
	    goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
547 548
	}
	elsif (($? >> 8) > 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
549 550 551 552
	    $response =
		GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				     "Could not allocate node");
	    goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
553
	}
554 555 556
	# In case the code below fails, before ticket is created.
	@dealloc = @nodeids;
    }
557 558 559
    goto skiplinks
	if (!exists($rspec->{'link'}));
    
560 561 562 563 564 565 566 567 568 569 570
    #
    # Now deal with links for wildcarded nodes. We need to fill in the
    # node_uuid.
    #
    foreach my $linkname (keys(%{$rspec->{'link'}})) {
	my $linkref = $rspec->{'link'}->{$linkname};

	foreach my $ref (@{$linkref->{'linkendpoints'}}) {
	    my $node_uuid     = $ref->{'node_uuid'};
	    my $node_nickname = $ref->{'node_nickname'};
	    my $iface_name    = $ref->{'iface_name'};
571 572
	    my $istunnel      = (exists($linkref->{'link_type'}) &&
				 $linkref->{'link_type'} eq "tunnel");
573

574
	    if (!defined($node_nickname)) {
575
		$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
576
						 "Need nickname for links");
577 578 579
		goto bad;
	    }

580 581 582
	    # XXX No wildcarding for tunnels unless its a node from above.
	    if ($istunnel) {
		if ($node_uuid eq "*" && !exists($namemap{$node_nickname})) {
583 584 585 586
		    $response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					 "Tunnels cannot be wildcarded");
		    goto bad;
		}
587 588 589
		# Not a local node, so skip.
		next
		    if (!exists($namemap{$node_nickname}));
590
	    }
591

592 593 594 595
	    # Map the nickname to the actual sliver (node) request.
	    my $sliver_uuid = $namemap{$node_nickname};
	    my $node = $virtmap{$sliver_uuid};

596
	    #
597
	    # Fill in the physnode if its wildcarded.
598 599 600 601
 	    #
	    if ($node_uuid eq "*") {
		$ref->{'node_uuid'} = $node->uuid();
	    }
602 603
	    # and the sliver_uuid we assigned above.
	    $ref->{'sliver_uuid'} = $sliver_uuid;
604 605 606

	    next
		if ($istunnel);
607
	    
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
	    #
	    # Now do wildcarded interfaces.
	    #
	    if ($iface_name eq "*") {
		my @interfaces;
		if ($node->AllInterfaces(\@interfaces) != 0) {
		    $response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				     "Could not get interfaces for $node");
		    goto bad;
		}
		foreach my $interface (@interfaces) {
		    next
			if (!defined($interface->switch_id()));
		    next
			if ($interface->role() ne "expt");

		    $ref->{'iface_name'} = $interface->iface();
		    last;
		}
	    }
	}
    }
630
  skiplinks:
631 632 633 634 635 636 637 638 639 640
    
    #
    # Create the ticket. 
    #
    my $ticket = GeniTicket->Create($slice, $user, $rspec);
    if (!defined($ticket)) {
	$response =
	    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "Could not create GeniTicket object");
	goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
641
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
642
    if ($ticket->Sign() != 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
643 644 645
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					 "Could not sign Ticket");
	goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
646
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
647
    $slice->UnLock();
648
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $ticket->asString());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
649
  bad:
650 651
    # Release will free the nodes.
    if (defined($ticket)) {
652
	$ticket->Release(TICKET_PURGED);
653 654 655 656
    }
    elsif (@dealloc) {
	system("export NORELOAD=1; $NFREE -x -q $pid $eid @dealloc");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
657 658 659
    $slice->UnLock()
	if (defined($slice));
    return $response;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
660 661 662 663 664
}

#
# Create a sliver.
#
665
sub RedeemTicket($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
666 667
{
    my ($argref) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
668
    my $ticket     = $argref->{'ticket'};
669
    my $impotent   = $argref->{'impotent'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
670
    my $keys       = $argref->{'keys'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
671
    my $extraargs  = $argref->{'extraargs'};
672 673 674

    $impotent = 0
	if (!defined($impotent));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
675 676 677 678 679 680 681 682 683 684 685 686

    if (! (defined($ticket) &&
	   !TBcheck_dbslot($ticket, "default", "text",
			   TBDB_CHECKDBSLOT_ERROR))) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "ticket: ". TBFieldErrorString());
    }
    $ticket = GeniTicket->CreateFromSignedTicket($ticket);
    if (!defined($ticket)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniTicket object");
    }
687 688 689 690 691 692 693
    
    #
    # Make sure the credential was issued to the caller.
    #
    if ($ticket->owner_uuid() ne $ENV{'GENIUUID'}) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "This is not your credential!");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
694
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
695 696 697 698 699 700 701 702 703 704 705 706 707

    my $slice = GeniSlice->Lookup($ticket->slice_uuid());
    if (!defined($slice)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "No slice record for slice");
    }
    if ($slice->Lock() != 0) {
	return GeniResponse->BusyResponse();
    }
    #
    # Do not redeem an expired ticket, kill it now.
    #
    if ($ticket->Expired()) {
708
	$ticket->Release(TICKET_EXPIRED);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
709 710 711 712
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_EXPIRED, undef,
				    "Ticket has expired");
    }
713 714 715 716 717 718
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
719 720 721 722 723 724

    #
    # For now, ther can be only a single toplevel aggregate per slice.
    #
    my $aggregate = GeniAggregate->SliceAggregate($slice);
    if (defined($aggregate)) {
725
	$ticket->Release(TICKET_EXPIRED);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
726 727 728 729 730 731 732
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Already have an aggregate for slice");
    }
    my $response = ModifySliver(undef, $slice, $ticket,
				$ticket->rspec(), $impotent, $keys);
    $slice->UnLock();
733 734 735 736
    if ($response->{'code'} != GENIRESPONSE_SUCCESS) {
	# So we get email.
        print STDERR Dumper($ticket->rspec());
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
737
    return $response;
738
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
739

740 741 742 743 744 745 746 747 748
#
# Update a sliver with a different resource set.
#
sub UpdateSliver($)
{
    my ($argref) = @_;
    my $cred        = $argref->{'credential'};
    my $rspec       = $argref->{'rspec'};
    my $impotent    = $argref->{'impotent'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
749 750
    my $keys        = $argref->{'keys'};
    my $extraargs   = $argref->{'extraargs'};
751 752 753 754 755 756 757 758 759 760

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

    if (!defined($cred)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS);
    }
    if (! (defined($rspec) && ($rspec =~ /^[-\w]+$/))) {
	GeniResponse->Create(GENIRESPONSE_BADARGS, undef, "Improper rspec");
    }
761
    $rspec = XMLin($rspec, ForceArray => ["node", "link", "linkendpoints"]);
762 763 764

    my $credential = GeniCredential->CreateFromSigned($cred);
    if (!defined($credential)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
765
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
766 767
				    "Could not create GeniCredential object");
    }
768
    my $sliver_uuid = $credential->target_uuid();
769
    my $user_uuid   = $credential->owner_uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
770

771 772 773 774 775 776 777
    #
    # 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!");
    }
778 779 780 781 782 783
    $credential->HasPrivilege( "pi" ) or
	$credential->HasPrivilege( "instantiate" ) or
	$credential->HasPrivilege( "control" ) or
	return GeniResponse->Create( GENIRESPONSE_FORBIDDEN, undef,
				     "Insufficient privilege" );

784 785 786 787
    my $sliver = GeniSliver->Lookup($sliver_uuid);
    if (defined($sliver)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Only aggregates for now");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
788
    }
789 790 791 792 793
    my $aggregate = GeniAggregate->Lookup($sliver_uuid);
    if (!defined($aggregate)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "No such aggregate $sliver_uuid");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
794 795 796 797 798 799 800 801
    my $slice = GeniSlice->Lookup($aggregate->slice_uuid());
    if (!defined($slice)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "No slice record for slice");
    }
    if ($slice->Lock() != 0) {
	return GeniResponse->BusyResponse();
    }
802 803 804 805 806 807
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
808 809 810 811

    my $response = ModifySliver($aggregate, $slice,
				$credential, $rspec, $impotent, $keys);
    $slice->UnLock();
812 813 814 815
    if ($response->{'code'} != GENIRESPONSE_SUCCESS) {
	# So we get email.
        print STDERR Dumper($rspec);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
816
    return $response;
817
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
818

819 820 821
#
# Utility function for above routines.
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
822
sub ModifySliver($$$$$$)
823
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
824
    my ($object, $slice, $credential, $rspec, $impotent, $keys) = @_;
825 826 827 828 829

    my $owner_uuid = $credential->owner_uuid();
    my $message    = "Error creating sliver/aggregate";
    my $aggregate;
    
830
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
831
    # Create the user.
832 833 834
    #
    my $owner = GeniUser->Lookup($owner_uuid);
    if (!defined($owner)) {
835
	$owner = CreateUserFromCertificate($credential->owner_cert());
836 837 838 839 840
	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");
	}
841
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
842 843 844
    if (!$owner->IsLocal() && defined($keys)) {
	$owner->Modify(undef, undef, $keys);
    }
845

846
    my $experiment = GeniExperiment($slice);
847 848 849 850 851 852 853 854 855 856 857
    if (!defined($experiment)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "No local experiment for slice");
    }

    #
    # Figure out what nodes to allocate or free. 
    #
    my %nodelist = ();
    my %linklist = ();
    my %toalloc  = ();
858
    my @allocated= ();
859 860 861
    my @tofree   = ();
    my $pid      = $experiment->pid();
    my $eid      = $experiment->eid();
862
    my $needplabslice = 0;
863
    my $didfwsetup = 0;
864 865 866 867 868

    #
    # Find current nodes and record their uuids. 
    #
    if (defined($object)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
869
	if ($object->type() ne "Aggregate") {
870 871 872 873 874 875 876 877 878
	    return GeniResponse->Create(GENIRESPONSE_UNSUPPORTED, undef,
					"Only node aggregates allowed");
	}
	my @slivers;
	if ($object->SliverList(\@slivers) != 0) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef);
	}
	foreach my $s (@slivers) {
	    if (ref($s) eq "GeniSliver::Node") {
879
		$nodelist{$s->uuid()} = $s;
880
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
881 882
	    elsif (ref($s) eq "GeniAggregate::Link" ||
		   ref($s) eq "GeniAggregate::Tunnel") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
883 884 885
		# XXX See the constructor in GeniAggregate.
		my ($linkname) = ($s->hrn() =~ /\.([-\w]*)$/);
		$linklist{$linkname} = $s;
886 887 888 889 890 891 892 893
	    }
	    else {
		return GeniResponse->Create(GENIRESPONSE_UNSUPPORTED, undef,
					    "Only nodes or links allowed");
	    }
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    #
    # 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:.\/]+/)) {
	    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");
	}
	if ($slice->SetExpiration($when) != 0) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not set expiration time");
	}
    }

925 926 927 928 929 930 931 932 933 934 935
    #
    # Figure out what nodes need to be allocated.
    #
    foreach my $ref (@{$rspec->{'node'}}) {
	my $resource_uuid = $ref->{'uuid'};
	my $node = Node->Lookup($resource_uuid);
	if (!defined($node)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Bad resource_uuid $resource_uuid");
	}

936 937 938 939 940 941 942 943 944 945 946 947 948
	#
	# Widearea nodes do not need to be allocated, but for now all
	# I allow is a plabdslice node.
	#
	if ($node->isremotenode()) {
	    if (! $node->isplabphysnode()) {
		return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					    "Only plab widearea nodes");
	    }
	    $needplabslice = 1;
	    next;
	}

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 989 990 991 992 993 994 995 996 997 998 999
	#
	# See if the node is already reserved. 
	#
	my $reservation = $node->Reservation();
	if (defined($reservation)) {
	    # Reserved during previous operation on the sliver.
	    next
		if ($reservation->SameExperiment($experiment));
	    
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
				"$resource_uuid ($node) is not available");
	}
	#
	# Sanity check on the list of already allocated nodes.
	#
	foreach my $s (values(%nodelist)) {
	    if ($resource_uuid eq $s->resource_uuid()) {
		print STDERR
		    "$resource_uuid is not supposed to be allocated\n";
		return GeniResponse->Create(GENIRESPONSE_ERROR, undef);
	    }
	}
	$toalloc{$resource_uuid} = $node->node_id();
    }

    #
    # What nodes need to be released?
    #
    foreach my $s (values(%nodelist)) {
	my $node_uuid = $s->resource_uuid();
	my $node      = Node->Lookup($node_uuid);
	my $needfree  = 1;
	
	foreach my $ref (@{$rspec->{'node'}}) {
	    my $resource_uuid = $ref->{'uuid'};
	    if ($node_uuid eq $resource_uuid) {
		$needfree = 0;
		last;
	    }
	}
	if ($needfree) {
	    #
	    # Not yet.
	    #
	    my @dlist;
	    if ($s->DependentSlivers(\@dlist) != 0) {
		return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					    "Could not get DependentSlivers");
	    }
	    if (@dlist) {
		return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
1000
				    "Must tear down dependent slivers first");
1001 1002 1003 1004 1005
	    }
	    push(@tofree, $s);
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1006 1007 1008 1009 1010 1011
    #
    # Create an emulab nonlocal user for tmcd.
    #
    $owner->BindToSlice($slice) == 0
	or return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				       "Error binding user to slice");
1012

1013

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1014
    # Bind the other users too.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1015 1016 1017
    # XXX Need to figure out where these come from.
    my @userbindings = ();

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1018 1019
    foreach my $otheruuid (@userbindings) {
	my $otheruser = GeniUser->Lookup($otheruuid);
1020
	if (!defined($otheruser)) {
1021
	    $otheruser = CreateUserFromCertificate($otheruuid);
1022 1023 1024 1025 1026
	    if (!defined($otheruser)) {
		print STDERR "No user $otheruser, cannot bind to slice\n";
		next;
	    }
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1027
	if ($otheruser->BindToSlice($slice) != 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1028 1029 1030 1031
	    print STDERR "Could not bind $otheruser to $slice\n";
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1032
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1033
    # We are actually an Aggregate, so return an aggregate of slivers,
1034
    # even if there is just one node. This makes sliceupdate easier.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1035
    #
1036 1037 1038 1039
    if (defined($object)) {
	$aggregate = $object;
    }
    else {
1040 1041 1042 1043 1044 1045 1046
	#
	# Form the hrn from the slicename.
	#
	my $hrn = "${OURDOMAIN}." . $slice->slicename();
	
	$aggregate = GeniAggregate->Create($slice, $owner, "Aggregate",
					   $hrn, $slice->hrn());
1047 1048
	if (!defined($aggregate)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
				"Could not create GeniAggregate object");
	}
    }

    # Nalloc might fail if the node gets picked up by someone else.
    if (values(%toalloc) && !$impotent) {
	my @list = values(%toalloc);
	system("$NALLOC $pid $eid @list");
	if ($?) {
	    # Nothing to deallocate if this fails.
	    %toalloc = undef;
	    $message = "Allocation failure";
	    goto bad;
1062
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1063
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1064

1065 1066 1067 1068
    #
    # We need to tear down links that are no longer in the rspec or
    # have changed.
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1069
    foreach my $linkname (keys(%linklist)) {
1070 1071
	if (!exists($rspec->{'link'}) ||
	    !exists($rspec->{'link'}->{$linkname})) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1072
	    my $s = $linklist{$linkname};
1073
	    $s->UnProvision();
1074
	    $s->Delete(0);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1075
	    delete($linklist{$linkname});
1076 1077 1078 1079
	    next;
	}
    }
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1080
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1081 1082
    # Now for each resource (okay, node) in the ticket create a sliver and
    # add it to the aggregate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1083
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1084 1085
    my %slivers   = ();
    my @plabnodes = ();
1086
    foreach my $ref (@{$rspec->{'node'}}) {
1087
	my $resource_uuid = $ref->{'uuid'};
1088 1089
	my $sliver_uuid   = $ref->{'sliver_uuid'};
	
1090 1091
	# Already in the aggregate?
	next
1092
	    if (grep {$_ eq $sliver_uuid} keys(%nodelist));
1093
	
1094 1095 1096
	my $node = Node->Lookup($resource_uuid);
	if (!defined($node)) {
	    $message = "Unknown resource_uuid in ticket: $resource_uuid";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1097 1098
	    goto bad;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1099
	my $sliver = GeniSliver::Node->Create($slice,
1100
					      $owner,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1101
					      $resource_uuid,
1102
					      $sliver_uuid,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1103
					      $ref);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1104 1105 1106 1107
	if (!defined($sliver)) {
	    $message = "Could not create GeniSliver object for $resource_uuid";
	    goto bad;
	}
1108
	$slivers{$sliver_uuid} = $sliver;
1109 1110 1111 1112 1113 1114 1115

	#
	# Remove this from %toalloc; if there is an error, the slivers are
	# deleted and the node released there. We only delete nodes that
	# have not turned into slivers yet. Ick.
	#
	delete($toalloc{$resource_uuid});
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1116

1117
	# Used below.
1118 1119 1120 1121 1122 1123 1124 1125
	push(@allocated, $node)
	    if (! grep {$_->node_id() eq $node->node_id()} @allocated);

	# Add to the aggregate.
	if ($sliver->SetAggregate($aggregate) != 0) {
	    $message = "Could not set aggregate for $sliver to $aggregate";
	    goto bad;
	}
1126

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1127 1128 1129 1130 1131 1132 1133 1134 1135
	# See below; setup all pnodes at once.
	if ($node->isremotenode()) {
	    my $vnode = Node->Lookup($sliver->uuid());
	    if (!defined($vnode)) {
		print STDERR "Could not locate vnode $sliver\n";
		goto bad;
	    }
	    push(@plabnodes, $vnode);
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1136
    }