GeniCM.pm.in 105 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.
39 40
use libdb qw(TBGetSiteVar EXPTSTATE_SWAPPED EXPTSTATE_ACTIVE TBOPSPID
	     TBDB_NODESTATE_TBFAILED);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
41
use User;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
42
use Node;
43
use OSinfo;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
44
use Image;
45
use Interface;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
46 47
use English;
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
use XML::Simple;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
49
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
50
use POSIX qw(strftime tmpnam);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
51
use Time::Local;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
52
use Experiment;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
53
use VirtExperiment;
54
use Firewall;
55 56
use Compress::Zlib;
use MIME::Base64;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
57 58 59 60 61 62 63 64

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

86 87 88 89 90 91 92 93 94 95 96 97
my $API_VERSION = 1;

#
# Tell the client what API revision we support.  The correspondence
# between revision numbers and API features is to be specified elsewhere.
# No credentials are required.
#
sub GetVersion()
{
    return GeniResponse->Create( GENIRESPONSE_SUCCESS, $API_VERSION );
}

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
# 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
128
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
129
# Respond to a Resolve request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
130 131 132 133 134 135
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
136 137
    my $type       = lc( $argref->{'type'} );
    my $hrn        = $argref->{'hrn'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
138 139 140 141

    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
    }
142 143 144 145
    if (defined($uuid) && GeniHRN::IsValid($uuid)) {
	$hrn  = $uuid;
	$uuid = undef;
    }
146 147 148 149 150 151 152 153 154 155 156 157
    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
158 159 160
	return GeniResponse->MalformedArgsResponse();
    }
    # Allow lookup by uuid or hrn.
161
    if (! defined($uuid) && !defined( $hrn ) ) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	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!");
    }
182
    if ($type eq "node") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
183 184 185
	my $node;
	
	if (defined($uuid)) {
186
	    $node= LookupNode($uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
187 188
	}
	else {
189
	    $node= LookupNode($hrn);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
190
	}
191
	if (! defined($node)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
192 193 194
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
					undef, "Nothing here by that name");
	}
195 196 197 198 199 200

	my $rspec = GetAdvertisement(0, $node->node_id());
	if (! defined($rspec)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not start avail");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
201 202
	
	# Return a blob.
203
	my $blob = { "hrn"          => "${PGENIDOMAIN}." . $node->node_id(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
204
		     "uuid"         => $node->uuid(),
205
		     "role"	    => $node->role(),
206
		     "hostname"     => $node->node_id() . ".${OURDOMAIN}",
207 208
		     "physctrl"     => 
			 Interface->LookupControl( $node->phys_nodeid() )->IP(),
209 210
		     "urn"          => GeniHRN::Generate( $OURDOMAIN,
							  "node",
211 212
							  $node->node_id() ),
		     "rspec"        => $rspec
Leigh B. Stoller's avatar
Leigh B. Stoller committed
213 214 215 216 217 218 219
		   };

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
220 221 222 223 224 225 226
#
# Discover resources on this component, returning a resource availablity spec
#
sub DiscoverResources($)
{
    my ($argref) = @_;
    my $credential = $argref->{'credential'};
227 228
    my $available = $argref->{'available'} || 0;
    my $compress = $argref->{'compress'} || 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
229 230 231 232 233 234 235 236
    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.
237
    if ($user_uuid ne $credential->owner_uuid()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
238 239 240 241
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Invalid credentials for operation");
    }

242 243 244
    # Oh, for $*%(s sake.  Frontier::RPC2 insists on representing a
    # Boolean as its own object type -- which Perl always interprets as
    # true, regardless of the object's value.  Undo all of that silliness.
245 246 247 248 249 250
    if (defined($available) && ref($available) eq 'Frontier::RPC2::Boolean') {
	$available = $available->value;
    }
    if (defined($compress) && ref($compress) eq 'Frontier::RPC2::Boolean') {
	$compress = $compress->value;
    }
251

Leigh B. Stoller's avatar
Leigh B. Stoller committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    #
    # 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
269
    #
270
    # Acquire the advertisement from ptopgen and compress it if requested.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
271
    #
272 273
    my $xml = GetAdvertisement($available, undef);
    if (! defined($xml)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
274 275 276 277
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }

278 279 280 281 282 283
    if( $compress ) {
	my $coder = Frontier::RPC2->new();
	my $base64 = encode_base64( compress( $xml ) );
	$xml = $coder->base64( $base64 );	
    }

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

287 288 289 290 291 292 293 294 295 296 297 298 299 300
#
# Use ptopgen in xml mode to spit back an xml file. 
#
sub GetAdvertisement($$)
{
    my ($available, $pc) = @_;
    my $xml = undef;

    my $invocation = "$PTOPGEN -x -g -r -p GeniSlices";
    $invocation .= " -a" unless $available;
    if (defined($pc)) {
	$invocation .= " -1 $pc";
    }
    if (open(AVAIL, "$invocation |")) {
301
	$xml = "";
302 303 304 305 306 307 308 309
	while (<AVAIL>) {
	    $xml .= $_;
	}
	close(AVAIL);
    }
    return $xml;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
310
#
311
# Update a ticket with a new rspec.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
312
#
313
sub UpdateTicket($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
314 315
{
    my ($argref) = @_;
316 317 318 319 320 321 322 323 324 325

    return GetTicket($argref, 1);
}

#
# Respond to a GetTicket request. 
#
sub GetTicket($;$)
{
    my ($argref, $isupdate) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
326
    my $rspec      = $argref->{'rspec'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
327
    my $impotent   = $argref->{'impotent'};
328
    my $cred       = $argref->{'credential'};
329 330
    my $tick       = $argref->{'ticket'};
    my $uuid       = $argref->{'uuid'};
331
    my $vtopo      = $argref->{'virtual_topology'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
332
    my $owner_uuid = $ENV{'GENIUSER'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
333
    my $response   = undef;
334
    my $didfwsetup = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
335 336
    my $restorevirt = 0;	# Flag to restore virtual state
    my $restorephys = 0;	# Flag to restore physical state
337 338 339 340 341 342 343
    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
344

345 346
    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
347
    }
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    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");
	}
364 365 366 367 368 369 370 371 372
	$rspec =
	    eval { XMLin($rspec, KeyAttr => [],
			 ForceArray => ["node", "link", "interface",
					"interface_ref", "linkendpoints"]) };
	if ($@) {
	    print STDERR "XMLin error: $@\n";
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"XML error in rspec");
	}
373 374 375 376
    }
    else {
	return GeniResponse->MalformedArgsResponse();
    }
377
    my $credential = GeniCredential->CreateFromSigned($cred);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
378 379 380 381
    if (!defined($credential)) {
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not create GeniCredential object");
    }
382
    my $slice_uuid = $credential->target_uuid();
383
    my $user_uuid  = $credential->owner_uuid();
384
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
385 386
    print STDERR $credential->target_cert() . "\n";
    print STDERR $credential->owner_cert() . "\n";
387

388 389 390
    #
    # Make sure the credential was issued to the caller.
    #
391
    if ($user_uuid ne $ENV{'GENIUUID'}) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
392
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
393
				    "This is not your credential!");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
394
    }
395
    
396 397 398 399 400 401 402 403 404
    if ($isupdate) {
	$ticket = GeniTicket->CreateFromSignedTicket($tick);
	if (!defined($ticket)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not create GeniTicket object");
	}
	$ticket->SetSlice($slice_uuid);
    }

405 406 407 408 409 410
    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
411

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    #
    # 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);
    }
436

Leigh B. Stoller's avatar
Leigh B. Stoller committed
437
    #
438
    # Create slice from the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
439 440 441
    #
    my $slice = GeniSlice->Lookup($slice_uuid);
    if (!defined($slice)) {
442 443 444 445 446
	if ($isupdate) {
	    print STDERR "Could not locate slice $slice_uuid for Update\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No slice found for UpdateTicket");
	}
447
	$slice = CreateSliceFromCertificate($credential);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
448
	if (!defined($slice)) {
449
	    print STDERR "Could not create $slice_uuid\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
450
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
451
					"Could not create slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
452
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
453 454
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
455
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
456 457
    # Ditto the user.
    #
458
    my $user = GeniUser->Lookup($user_uuid, 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
459
    if (!defined($user)) {
460 461 462 463 464
	if ($isupdate) {
	    print STDERR "Could not locate $user_uuid for UpdateTicket\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"No user found for UpdateTicket");
	}
465
	$user = CreateUserFromCertificate($credential->owner_cert());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
466
	if (!defined($user)) {
467
	    print STDERR "No user $user_uuid in the ClearingHouse\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
468 469 470 471 472
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
			    "Could not get user info from ClearingHouse");
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486
    #
    # 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");
    }
    
    #
487
    # For now all tickets expire very quickly (minutes), but once the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    # 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");
	}
	
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
505
	# No more then 25 hours out ... Needs to be a sitevar?
Leigh B. Stoller's avatar
Leigh B. Stoller committed
506 507
	#
	my $diff = $when - time();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
508
	if ($diff < (60 * 15) || $diff > (3600 * 25)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
509 510 511 512 513 514 515 516 517
	    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)));
    }
518 519 520 521 522 523 524

    #
    # 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
525 526 527 528 529 530
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
531 532 533
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
534
    }
535 536 537
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
538 539
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
540 541 542
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
543

544
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
545
    # For now, there can be only a single toplevel aggregate per slice.
546
    # The existence of an aggregate means the slice is active here. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
547
    #
548 549 550 551 552 553
    if (!$isupdate) {
	my $aggregate = GeniAggregate->SliceAggregate($slice);
	if (defined($aggregate)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Already have an aggregate for slice");
	    goto bad;
554 555 556 557 558 559 560 561
	}
    }

    #
    # Firewall hack; just a flag in the rspec for now.
    #
    if (exists($rspec->{'needsfirewall'}) && $rspec->{'needsfirewall'}) {
	if ($slice->SetFirewallFlag($rspec->{'needsfirewall'}) != 0) {
562 563
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
564 565
	}
    }
566 567

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
568
    # We need this now so we can form a virtual topo.
569
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
570 571 572 573 574 575 576 577
    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();
578 579 580 581 582 583 584 585 586 587 588

    #
    # Mark the experiment locally as coming from the cooked interface.
    # This changes what tmcd returns to the local nodes.
    #
    if (exists($rspec->{'generated_by'}) &&
	$rspec->{'generated_by'} eq "libvtop") {
	$slice_experiment->Update({"geniflags" =>
				       $Experiment::EXPT_GENIFLAGS_EXPT|
				       $Experiment::EXPT_GENIFLAGS_COOKED});
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
589 590 591 592 593 594 595 596 597 598 599 600 601
    
    #
    # 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);
602 603

    # This is where nodes are parked until a ticket is redeemed.
604
    # This experiment no longer has to exist.
605
    my $reserved_holding = Experiment->Lookup("GeniSlices", "reservations");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
606

Leigh B. Stoller's avatar
Leigh B. Stoller committed
607
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
608 609
    # 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
610 611
    # cannot be granted.
    #
612 613 614
    my %namemap  = ();
    my %colomap  = ();
    my %ifacemap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
615
    my %nodemap  = ();
616
    my @nodeids  = ();
617
    my %lannodes = ();
618
    my @dealloc;
619 620 621 622 623 624 625 626

    #
    # 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
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
	$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;
	}
	
646 647 648 649 650 651 652
	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.
653
	    next
654 655 656
		if (defined($manager_uuid) &&
		    !GeniHRN::Equal( $manager_uuid, $ENV{'MYURN'} ) &&
		    $manager_uuid ne $ENV{'MYUUID'});
657

658 659 660 661 662 663
	    # Skip lan nodes; they are fake.
	    next
		if (exists($ref->{'node_type'}) &&
		    exists($ref->{'node_type'}->{'type_name'}) &&
		    $ref->{'node_type'}->{'type_name'} eq "lan");

664
	    my $node = LookupNode($resource_uuid);
665 666
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
667
				 "Bad resource $resource_uuid in ticket");
668 669 670
		goto bad;
	    }

671 672 673 674 675 676
	    #
	    # Grab the reservation. For backwards compatibility, we want
	    # to find nodes in the reservations holding area, and move them
	    # into the slice experiment. The holding area is no longer going
	    # to be used, at least not until we have a reservations system.
	    #
677
	    my $reservation = $node->Reservation();
678
	    if (defined($reservation) &&
679
		defined($reserved_holding) &&
680 681 682 683 684 685
		$reservation->SameExperiment($reserved_holding)) {
		if ($node->MoveReservation($slice_experiment)) {
		    print STDERR "Could not move $node to $slice_experiment\n";
		    goto bad;
		}
		$node->Refresh();
686 687 688 689 690 691
	    }
	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
692

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

695
    foreach my $ref (@{$rspec->{'node'}}) {
696 697 698 699
	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'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
700 701 702
	my $virtualization_type    = $ref->{'virtualization_type'};
	my $virtualization_subtype = $ref->{'virtualization_subtype'};
	my $exclusive     = $ref->{'exclusive'};
703
	my $pctype;
704
	my $osname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
705 706
	my $node;

707
	# Let remote nodes pass through.
708
	next
709 710 711
	    if (defined($manager_uuid) &&
		!GeniHRN::Equal( $manager_uuid, $ENV{'MYURN'} ) &&
		$manager_uuid ne $ENV{'MYUUID'});
712

713 714 715 716 717 718 719 720 721 722 723 724
	#
	# Lan nodes are fake and do not go into the virt topo. Need
	# to remember them though, for when we do the links below.
	# They are still in the returned ticket though. 
	#
	if (exists($ref->{'node_type'}) &&
	    exists($ref->{'node_type'}->{'type_name'}) &&
	    $ref->{'node_type'}->{'type_name'} eq "lan") {
	    $lannodes{$node_nickname} = $ref;
	    next;
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
725 726 727 728 729 730 731 732 733
	if (defined($virtualization_type)) {
	    if ($virtualization_type eq "emulab-vnode") {
		if (defined($virtualization_subtype)) {
		    if ($virtualization_subtype eq "emulab-jail") {
			$osname = "FBSD-JAIL";
		    }
		    elsif ($virtualization_subtype eq "emulab-openvz") {
			$osname = "OPENVZ-STD";
		    }
734
		    $pctype = "pcvm";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748
		}
		else {
		    goto raw;
		}
	    }
	    else {
	      raw:
		# Lets force to exclusive real node.
		$ref->{'exclusive'} = $exclusive = 1;
		$ref->{'virtualization_type'} = "raw";
	    }
	}
	else {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
749
				     "Must provide a virtualization_type");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
750 751 752
	    goto bad;

	}
753 754 755 756 757 758
	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
759
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
760
	# Allow wildcarding.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
761
	#
762 763 764 765 766 767
	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};
768
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
769 770
	}
	else {
771
	    $node = LookupNode($resource_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
772 773 774 775 776 777 778

	    if (!defined($node)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Bad resource $resource_uuid");
		goto bad;
	    }
779 780
	    $pctype = $node->type()
		if (!defined($pctype));
781 782
	}
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
783
	# If no osname by this point, try for the default.
784 785
	#
	if (defined($node) && !defined($osname)) {
786 787 788 789 790
	    if (defined($node->default_osid())) {	    
		my $osinfo = OSinfo->Lookup($node->default_osid());
		$osname = $osinfo->osname()
		    if (defined($osinfo));
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
791
	}
792 793 794
	# The slot does not like to be NULL.
	$osname = ""
	    if (!defined($osname));
795
	
796 797 798
	# Need some kind of default.
	$pctype = "pc"
	    if (!defined($pctype));
799
	
800 801 802 803 804 805 806 807 808
	my $nodeblob = {"vname"   => $node_nickname,
			"type"    => $pctype,
			"osname"  => $osname,
			"ips"     => '', # deprecated
			"cmd_line"=> '', # bogus
			"fixed"   => (defined($node) ?
				      $node->node_id() : "")};

	# Tarball and startup command.
809
	if (exists($ref->{'startup_command'})) {
810 811 812 813 814 815 816 817 818 819 820 821 822 823
	    my $startupcmd = $ref->{'startup_command'};
	    
	    if (! TBcheck_dbslot($startupcmd, "virt_nodes", "startupcmd",
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Invalid startup command");
		goto bad;
	    }
	    $nodeblob->{'startupcmd'} = $startupcmd;
	}
	if (exists($ref->{'tarfiles'})) {
	    my $tarfiles = $ref->{'tarfiles'};
	    
824
	    if (! TBcheck_dbslot($tarfiles, "virt_nodes", "tarfiles",
825 826 827 828 829 830
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Invalid tarfiles");
		goto bad;
	    }
831
	    $nodeblob->{'tarfiles'} = $tarfiles;
832 833 834 835 836 837 838 839
	}

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
841 842 843 844 845 846 847 848 849 850
	$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};
	
851 852 853 854
	#
	# Look for interface forward declarations that will be used later
	# in the link specifications. 
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
855 856 857
	next
	    if (!exists($ref->{'interface'}));
	
858 859 860 861 862 863 864 865 866 867 868 869 870
	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
871 872 873
	    # port counter.
	    my $vport = scalar(keys(%{ $ifacemap{$node_nickname} }));

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
878 879
	    # 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
880
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
881 882
    }

883 884 885
    goto skiplinks
	if (!exists($rspec->{'link'}));
    
886 887 888 889
    #
    # Now deal with links for wildcarded nodes. We need to fill in the
    # node_uuid.
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
890 891
    my $linknum = 1;
    
892
    foreach my $linkref (@{$rspec->{'link'}}) {
893
	my $lanname    = $linkref->{"nickname"} || $linkref->{"virtual_id"};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
894 895
	my $istunnel   = (exists($linkref->{'link_type'}) &&
			  $linkref->{'link_type'} eq "tunnel");
896 897
	my $interfaces = $linkref->{'linkendpoints'} ||
	    $linkref->{'interface_ref'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
898
	my $ifacenum   = 1;
899

900
	if (!defined($lanname)) {
901 902 903 904
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Must provide a virtual_id for links");
	    goto bad;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
905

906 907 908 909 910 911 912
	#
	# Ick. Before we create the virt_lan_lans entry, we have to check
	# inside to see if one of the interfaces is connected to a lan
	# node. In this case, we want to reuse (if its been created) the
	# lan name, rather then a bunch of links with one interface, which
	# would result in a bogus topology. 
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
913
	if (!$istunnel) {
914 915 916 917 918 919 920 921 922 923 924 925
	    foreach my $ref (@{ $interfaces }) {
		my $node_nickname = $ref->{'virtual_node_id'} ||
		    $ref->{'node_nickname'};

		if (exists($lannodes{$node_nickname})) {
		    $lanname = $node_nickname;
		}
	    }
	    if (!defined($virtexperiment->Find("virt_lan_lans", $lanname))) {
		$virtexperiment->NewTableRow("virt_lan_lans",
					     {"vname" => $lanname});
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
926
	}
927 928 929 930 931 932
	
	foreach my $ref (@{ $interfaces }) {
	    my $node_nickname = $ref->{'virtual_node_id'} ||
		$ref->{'node_nickname'};
	    my $iface_id     = $ref->{'virtual_interface_id'} ||
		$ref->{'iface_name'};
933

934
	    if (!defined($node_nickname)) {
935 936
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
937
				 "$lanname: Need node id for links");
938 939 940 941 942
		goto bad;
	    }
	    if (!defined($iface_id)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
943
				 "$lanname: Need interface id for links");
944 945 946
		goto bad;
	    }

947 948 949 950 951 952 953 954 955
	    #
	    # Look for links that are really lans; one of the interfaces
	    # is on a fake lan node, which we caught above. Just skip it
	    # since in the virt topo, a lan is just a link with more then
	    # two nodes.
	    #
	    next
		if (exists($lannodes{$node_nickname}));

956
	    if ($istunnel) {
957
		# Might be the other side. Skip for now; might bite later.
958 959
		next
		    if (!exists($namemap{$node_nickname}));
960

961 962 963
		# Not doing anything else.
		next;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
964
	    if (!exists($ifacemap{$node_nickname})) {
965 966
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
967
				 "$lanname: No such virtual_node_id: ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
968
				 "$node_nickname");
969
		goto bad;
970
	    }
971
	    
972
	    #
973
	    # Sanity check the interface.
974
	    #
975 976 977
	    if (!exists($ifacemap{$node_nickname}->{$iface_id})) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
978
				 "$lanname: No such interface on component: ".
979 980 981
				 "$node_nickname:$iface_id");
		goto bad;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
982 983
	    my $iface_ref   = $ifacemap{$node_nickname}->{$iface_id}->{"rspec"};
	    my $iface_name  = $iface_ref->{"component_id"} || "";
984
	    if( GeniHRN::IsValid( $iface_name ) ) {
985 986
		my ($urn_authority,$urn_node,$urn_iface) =
		    GeniHRN::ParseInterface( $iface_name );
987 988
		$iface_name = $urn_iface;
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
989 990 991 992 993 994
	    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";
995 996 997 998 999
	    my $bandwidth = 100000;

	    # Let user override.
	    $bandwidth = $linkref->{'bandwidth'}
	        if (exists($linkref->{'bandwidth'}));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1000 1001
	    
	    $virtexperiment->NewTableRow("virt_lans",
1002
					 {"vname"       => $lanname,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1003 1004
					  "vnode"       => $node_nickname,
					  "vport"       => $iface_vport,
1005
					  "trivial_ok"  => 1,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1006 1007
					  "ip"          => $ip,
					  "delay"       => 0.0,
1008
					  "bandwidth"   => $bandwidth, # kbps
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1009 1010 1011 1012
					  "lossrate"    => 0.0,
					  "member"      => $member,
					  "mask"        => $mask,
					  "rdelay"      => 0.0,
1013
					  "rbandwidth"  => $bandwidth, # kbps
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1014 1015 1016 1017 1018 1019 1020 1021
					  "rlossrate"   => 0.0,
					  "fixed_iface" => $iface_name});
	    $ifacenum++;
	}
	$linknum++;
    }
  skiplinks:
    $virtexperiment->Dump();
1022 1023 1024 1025
    if ($virtexperiment->Store()) {
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef);
	goto bad;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1026 1027 1028 1029 1030 1031

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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    #
    # 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;
    }
1052
    system("$MAPPER -n -d -v -m 3 -u -o $tmpfile $pid $eid");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1053 1054 1055 1056 1057 1058 1059 1060
    if ($?) {
	$response =
	    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				 "Could not map to resources");
	unlink($tmpfile);
	if ($isupdate) {
	    $slice_experiment->RemovePhysicalState();
	    $slice_experiment->RestorePhysicalState();
1061
	}
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	#
	# Lets dump the error log too, so it ends up in the email.
	# Have to figure out a better approach for this.
	#
	if (-e "assign.log") {
	    print STDERR "----------------------------------------------\n";
	    print STDERR "------------- Assign Error Log ---------------\n";
	    my $log = `cat assign.log`;
	    print STDERR $log . "\n";
	    print STDERR "----------------------------------------------\n";
	}	    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1073
	goto bad;
1074
    }
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    my $solution =
	eval { XMLin($tmpfile, KeyAttr => [],
		     ForceArray => ["node", "link", "interface",
				    "interface_ref", "linkendpoints"]) };
    if ($@) {
	print STDERR "XMLin error: $@\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					 "XML error in solution");
	goto bad;
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1086 1087 1088 1089 1090 1091
    unlink($tmpfile);
    print Dumper($solution);

    foreach my $ref (@{$solution->{'node'}}) {
	my $virtual_id     = $ref->{"virtual_id"};
	my $component_uuid = $ref->{"component_uuid"};
1092 1093 1094 1095 1096 1097
	if (!exists($nodemap{$virtual_id})) {
	    $response =
		GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				     "Mapper inserted nodes you did not want");
	    goto bad;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1098 1099
	my $rspec          = $nodemap{$virtual_id}->{'rspec'};
	my $virtnode       = $nodemap{$virtual_id}->{'virtnode'};
1100
	my $node           = LookupNode($component_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1101 1102
	my $colocate       = $rspec->{'colocate'} ||
	    $rspec->{'phys_nickname'};
1103 1104 1105
	my $exclusive      = $rspec->{'exclusive'};
	$exclusive = 0
	    if (!defined($exclusive));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1106
	
1107 1108
	$rspec->{'component_urn'} = GeniHRN::Generate( $OURDOMAIN, "node",
						       $node->node_id() );
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1109
	$rspec->{'component_uuid'} = $component_uuid;
1110 1111
	$rspec->{'component_manager_urn'} = $ENV{'MYURN'};
	$rspec->{'component_manager_uuid'} = $ENV{'MYUUID'};