GeniCM.pm.in 209 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2008-2015 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
29 30 31 32 33 34 35 36 37 38 39
#
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);

40 41
@ISA    = qw(Exporter);
@EXPORT = qw();
Leigh Stoller's avatar
Leigh Stoller committed
42 43 44

use GeniDB;
use Genixmlrpc;
Leigh Stoller's avatar
Leigh Stoller committed
45 46
use GeniResponse;
use GeniTicket;
Leigh Stoller's avatar
Leigh Stoller committed
47
use GeniCredential;
48
use GeniCertificate;
Leigh Stoller's avatar
Leigh Stoller committed
49
use GeniSlice;
Leigh Stoller's avatar
Leigh Stoller committed
50
use GeniAggregate;
51
use GeniAuthority;
Leigh Stoller's avatar
Leigh Stoller committed
52
use GeniSliver;
Leigh Stoller's avatar
Leigh Stoller committed
53
use GeniUser;
Leigh Stoller's avatar
Leigh Stoller committed
54
use GeniRegistry;
55
use GeniUtil;
56
use GeniHRN;
57
use GeniXML;
58
use GeniStitch;
59
use GeniUsage;
60
use GeniImage;
61
use libtestbed;
62
use emutil;
63 64
use EmulabConstants;
use libEmulab;
65
use Lan;
66
use User;
67
use Experiment;
68
use NodeType;
69
use Node;
Leigh Stoller's avatar
Leigh Stoller committed
70 71
use English;
use Data::Dumper;
Leigh Stoller's avatar
Leigh Stoller committed
72
use XML::Simple;
73
use XML::LibXML;
Leigh Stoller's avatar
Leigh Stoller committed
74
use Date::Parse;
75
use POSIX qw(strftime tmpnam ceil);
Leigh Stoller's avatar
Leigh Stoller committed
76
use Time::Local;
77
use Compress::Zlib;
78
use File::Temp qw(tempfile);
79
use MIME::Base64;
80
use Digest::SHA1 qw(sha1_hex);
81
use POSIX ":sys_wait_h";
Leigh Stoller's avatar
Leigh Stoller committed
82 83 84 85 86 87

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
88 89
my $TBBASE         = "@TBBASE@";
my $TBDOCBASE      = "@TBDOCBASE@";
Leigh Stoller's avatar
Leigh Stoller committed
90 91
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
92
my $MAINSITE       = @TBMAINSITE@;
93
my $ELABINELAB     = @ELABINELAB@;
94
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
95
my $PROTOUSER 	   = "elabman";
Leigh Stoller's avatar
Leigh Stoller committed
96
my $CREATEEXPT     = "$TB/bin/batchexp";
97
my $ENDEXP         = "$TB/bin/endexp";
98
my $NFREE	   = "$TB/bin/nfree";
Leigh Stoller's avatar
Leigh Stoller committed
99
my $AVAIL	   = "$TB/sbin/avail";
100
my $PTOPGEN	   = "$TB/libexec/ptopgen";
Leigh Stoller's avatar
Leigh Stoller committed
101 102
my $TBSWAP	   = "$TB/bin/tbswap";
my $SWAPEXP	   = "$TB/bin/swapexp";
Leigh Stoller's avatar
Leigh Stoller committed
103 104
my $PLABSLICE	   = "$TB/sbin/plabslicewrapper";
my $NAMEDSETUP     = "$TB/sbin/named_setup";
105
my $EXPORTS_SETUP  = "$TB/sbin/exports_setup";
Leigh Stoller's avatar
Leigh Stoller committed
106 107
my $VNODESETUP     = "$TB/sbin/vnode_setup";
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
108
my $IPASSIGN       = "$TB/libexec/ipassign_wrapper";
109
my $TARFILES_SETUP = "$TB/bin/tarfiles_setup";
Leigh Stoller's avatar
Leigh Stoller committed
110 111
my $MAPPER         = "$TB/bin/mapper";
my $VTOPGEN        = "$TB/bin/vtopgen";
112
my $SNMPIT         = "$TB/bin/snmpit_test";
113
my $RESERVEVLANS   = "$TB/sbin/protogeni/reservevlans";
114
my $NEWGROUP       = "$TB/bin/newgroup";
115 116
my $NEWPROJECT     = "$TB/sbin/newproj";
my $MAKEPROJECT    = "$TB/sbin/mkproj";
Leigh Stoller's avatar
Leigh Stoller committed
117
my $PRERENDER      = "$TB/libexec/vis/prerender";
118 119
my $SUDO           = "/usr/local/bin/sudo";
my $WAP            = "$TB/sbin/withadminprivs";
120
my $XMLLINT	   = "/usr/local/bin/xmllint";
121
my $ADDAUTHORITY   = "$TB/sbin/protogeni/addauthority";
122
my $EMULAB_PEMFILE = "@prefix@/etc/genicm.pem";
123
my $TARINSTALL     = "/usr/local/bin/install-tarfile";
124
my $IMAGE_SETUP    = "$TB/sbin/image_setup";
125
my $IMAGE_IMPORT   = "$TB/sbin/image_import";
126
my $SHAREVLAN      = "$TB/sbin/sharevlan";
127
my $FWNAME	   = "fw";
128
my $API_VERSION    = 1;
129 130
my $PROTOGENI_LOCALUSER   = @PROTOGENI_LOCALUSER@;
my $PROTOGENI_NONFSMOUNTS = @PROTOGENI_NONFSMOUNTS@;
131

132 133 134 135 136
# For location info.
my $default_longitude = undef;
my $default_latitude  = undef;
my $default_country   = undef;

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

Leigh Stoller's avatar
Leigh Stoller committed
147
#
Leigh Stoller's avatar
Leigh Stoller committed
148
# Respond to a Resolve request. 
Leigh Stoller's avatar
Leigh Stoller committed
149 150 151 152 153 154
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
155 156
    my $type       = lc( $argref->{'type'} );
    my $hrn        = $argref->{'hrn'};
Leigh Stoller's avatar
Leigh Stoller committed
157 158 159 160

    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
    }
161 162 163 164
    if (defined($uuid) && GeniHRN::IsValid($uuid)) {
	$hrn  = $uuid;
	$uuid = undef;
    }
165 166 167 168 169 170 171 172 173 174 175 176
    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 Stoller's avatar
Leigh Stoller committed
177 178 179
	return GeniResponse->MalformedArgsResponse();
    }
    # Allow lookup by uuid or hrn.
180
    if (! defined($uuid) && !defined( $hrn ) ) {
Leigh Stoller's avatar
Leigh Stoller committed
181 182 183 184 185 186
	return GeniResponse->MalformedArgsResponse();
    }
    if (defined($uuid) && !($uuid =~ /^[-\w]*$/)) {
	return GeniResponse->MalformedArgsResponse();
    }

187
    my $credential = GeniCredential::CheckCredential($cred);
188 189 190
    return $credential
	if (GeniResponse::IsResponse($credential));

191
    if ($type eq "node") {
192
	require Interface;
Leigh Stoller's avatar
Leigh Stoller committed
193 194 195
	my $node;
	
	if (defined($uuid)) {
196
	    $node= GeniUtil::LookupNode($uuid);
Leigh Stoller's avatar
Leigh Stoller committed
197 198
	}
	else {
199
	    $node= GeniUtil::LookupNode($hrn);
Leigh Stoller's avatar
Leigh Stoller committed
200
	}
201
	if (! defined($node)) {
Leigh Stoller's avatar
Leigh Stoller committed
202 203 204
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
					undef, "Nothing here by that name");
	}
205

206
	my $rspec = GetAdvertisement(0, $node->node_id(), "0.1", undef);
207 208 209 210
	if (! defined($rspec)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not start avail");
	}
Leigh Stoller's avatar
Leigh Stoller committed
211 212
	
	# Return a blob.
213
	my $blob = { "hrn"          => "${PGENIDOMAIN}." . $node->node_id(),
Leigh Stoller's avatar
Leigh Stoller committed
214
		     "uuid"         => $node->uuid(),
215
		     "role"	    => $node->role(),
216 217
		     "hostname"     =>
			 GeniUtil::FindHostname($node->node_id()),
218 219
		     "physctrl"     => 
			 Interface->LookupControl( $node->phys_nodeid() )->IP(),
220 221
		     "urn"          => GeniHRN::Generate( $OURDOMAIN,
							  "node",
222 223
							  $node->node_id() ),
		     "rspec"        => $rspec
Leigh Stoller's avatar
Leigh Stoller committed
224 225 226 227 228 229 230
		   };

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

Leigh Stoller's avatar
Leigh Stoller committed
231 232 233 234 235 236
#
# Discover resources on this component, returning a resource availablity spec
#
sub DiscoverResources($)
{
    my ($argref) = @_;
237
    my $credstr   = $argref->{'credential'};
238
    my $available = $argref->{'available'} || 0;
239
    my $compress  = $argref->{'compress'} || 0;
240
    my $version   = $argref->{'rspec_version'} || undef;
241

242
    my $credential = GeniCredential::CheckCredential($credstr);
243 244
    return $credential
	if (GeniResponse::IsResponse($credential));
Leigh Stoller's avatar
Leigh Stoller committed
245

246 247
    return DiscoverResourcesAux($available,
				$compress, $version, [$credential]);
248 249
}
# Helper function for V2.
250
sub DiscoverResourcesAux($$$$)
251
{
252
    my ($available, $compress, $version, $credentials) = @_;
253
    my $user_urn  = $ENV{'GENIRN'};
254
    $version   = "2"
255 256 257
	if (!defined($version));

    # Sanity check since this can come from client.
258
    if (! ($version eq "0.1" || $version eq "0.2" || $version eq "2"
259 260 261
	   || $version eq "3"
	   || $version eq "PG 0.1" || $version eq "PG 0.2"
	   || $version eq "PG 2")) {
262 263 264
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Improper version request");
    }
Leigh Stoller's avatar
Leigh Stoller committed
265

266 267 268
    # 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.
269 270 271 272 273 274
    if (defined($available) && ref($available) eq 'Frontier::RPC2::Boolean') {
	$available = $available->value;
    }
    if (defined($compress) && ref($compress) eq 'Frontier::RPC2::Boolean') {
	$compress = $compress->value;
    }
275

Leigh Stoller's avatar
Leigh Stoller committed
276 277 278 279
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
280
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
281 282
	      # Cannot get the value, say no.
	      $allow_externalusers = 0;
Leigh Stoller's avatar
Leigh Stoller committed
283
    }
284 285 286 287 288 289 290

    # Figure out if user has a credentials that exempts him
    # from the following policy. If external users are blocked access
    # and he presents a credential that exempts him from it, 
    # then he should get access.
    my $isExempted = 0;
    foreach my $credential (@$credentials) {
291
        if (GeniXML::PolicyExists('allow_externalusers', $credential) == 1) {
292 293 294 295 296 297
        $isExempted = 1;
        last;
      }
    }

    if (!$allow_externalusers && !$isExempted) {
298
	my $user = GeniUser->Lookup($user_urn, 1);
Leigh Stoller's avatar
Leigh Stoller committed
299 300 301 302 303 304 305
	# No record means the user is remote.
	if (!defined($user) || !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
					"External users temporarily denied");
	}
    }

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    #
    # See if one of the credentials is a slice credential. If it is, and
    # that slice is active, pass it to ptopgen so that it includes the current
    # resources as available.
    #
    my $experiment = undef;
    foreach my $credential (@$credentials) {
	my ($auth, $type, $id) = GeniHRN::Parse($credential->target_urn());
	if ($type eq "slice") {
	    # Might not exist here yet.
	    my $slice = GeniSlice->Lookup($credential->target_urn());
	    if (defined($slice)) {
		# See if the local experiment exists yet.
		$experiment = Experiment->Lookup($slice->uuid());
	    }
	    last;
	}
    }

Leigh Stoller's avatar
Leigh Stoller committed
325
    #
326
    # Acquire the advertisement from ptopgen and compress it if requested.
Leigh Stoller's avatar
Leigh Stoller committed
327
    #
328
    my $xml = GetAdvertisement($available, undef, $version, $experiment);
329
    if (! defined($xml)) {
Leigh Stoller's avatar
Leigh Stoller committed
330 331 332 333
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }

334 335 336 337 338 339
    if( $compress ) {
	my $coder = Frontier::RPC2->new();
	my $base64 = encode_base64( compress( $xml ) );
	$xml = $coder->base64( $base64 );	
    }

Leigh Stoller's avatar
Leigh Stoller committed
340 341
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $xml);
}
Leigh Stoller's avatar
Leigh Stoller committed
342

343 344 345
#
# Use ptopgen in xml mode to spit back an xml file. 
#
346
sub GetAdvertisement($$$$)
347
{
348
    my ($available, $pc, $version, $experiment) = @_;
349
    my $xml = undef;
350 351
    my $gotlock = 0;
    my $filename = "/var/tmp/protogeni_resources.xml";
352

353 354 355 356 357 358 359
    $version = "0.1"
	if ($version eq "PG 0.1");
    $version = "0.2"
	if ($version eq "PG 0.2");
    $version = "2"
	if ($version eq "PG 2");

360
    my $invocation = "$PTOPGEN -x -g $version -r -f";
361 362 363 364
    if (defined($experiment)) {
	my $eid = $experiment->eid();
	$invocation .= " -e $eid";
    }
365 366 367 368
    $invocation .= " -a" unless $available;
    if (defined($pc)) {
	$invocation .= " -1 $pc";
    }
369 370 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 396 397 398 399 400 401 402 403 404 405 406 407
    if (!defined($pc)) {
      again:
	#
	# Grab a global script lock. This will ensure that only one ptopgen
	# runs at a time, and everyone else who comes along while that first
	# one is running, will share the same results file.
	#
	# Need to use a well known name, unless we want to share that name
	# via the DB. Lets be simple about it for now.
	#
	if ((my $locked = TBScriptLock("discover", 1)) != TBSCRIPTLOCK_OKAY()) {
	    if ($locked == TBSCRIPTLOCK_IGNORE) {
		#
		# Previous locker finished ptopgen.
		# Grab the file if it exists (small race), otherwise
		# try again from the top.
		#
		if (open(AVAIL, "$filename")) {
		    $xml = "";
		    while (<AVAIL>) {
			$xml .= $_;
		    }
		    close(AVAIL);
		    return $xml;
		}
		goto again;
	    }
	    else {
		print STDERR "Could not get ptopgen lockfile\n";
		return undef;
	    }
	}
	else {
	    #
	    # We got the lock so we get to run ptopgen.
	    #
	    $gotlock = 1;
	}
    }
408
    if (open(AVAIL, "$invocation |")) {
409
	$xml = "";
410 411 412 413 414
	while (<AVAIL>) {
	    $xml .= $_;
	}
	close(AVAIL);
    }
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    #
    # The lock holder has to create the new version of the file for
    # anyone waiting. Need to do this atomically so that anyone still
    # reading the previous version does not get inconsistent data.
    #
    if ($gotlock) {
	my ($fh, $tempname) = tempfile(UNLINK => 0, DIR => "/var/tmp");
	if (!defined($fh)) {
	    print STDERR "Could not create temporary file: $!\n";
	    $xml = undef;
	}
	else {
	    print $fh $xml;
	    close($fh);
	    if (! rename($tempname, $filename)) {
		print STDERR "Could not rename temporary file: $!\n";
		$xml = undef;
	    }
	}
	TBScriptUnlock();
    }
436 437 438
    return $xml;
}

Leigh Stoller's avatar
Leigh Stoller committed
439
#
440
# Update a ticket with a new rspec.
Leigh Stoller's avatar
Leigh Stoller committed
441
#
442
sub UpdateTicket($)
Leigh Stoller's avatar
Leigh Stoller committed
443 444
{
    my ($argref) = @_;
445 446 447 448 449 450 451 452 453 454

    return GetTicket($argref, 1);
}

#
# Respond to a GetTicket request. 
#
sub GetTicket($;$)
{
    my ($argref, $isupdate) = @_;
455
    my $rspecstr   = $argref->{'rspec'};
Leigh Stoller's avatar
Leigh Stoller committed
456
    my $impotent   = $argref->{'impotent'};
457 458
    my $credstr    = $argref->{'credential'};
    my $tickstr    = $argref->{'ticket'};
459 460 461 462 463 464 465
    my $ticket;

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

467
    if (! defined($credstr)) {
468
	return GeniResponse->MalformedArgsResponse();
Leigh Stoller's avatar
Leigh Stoller committed
469
    }
470
    if (!defined($rspecstr)) {
471 472
	return GeniResponse->MalformedArgsResponse();
    }
473 474 475 476
    if (! ($rspecstr =~ /^[\040-\176\012\015\011]+$/)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Improper characters in rspec");
    }
477
    my $credential = GeniCredential::CheckCredential($credstr);
478 479 480
    return $credential
	if (GeniResponse::IsResponse($credential));

481
    if ($isupdate) {
482
	$ticket = CheckTicket($tickstr, $credential->target_urn());
483 484
	return $ticket
	    if (GeniResponse::IsResponse($ticket));
485
    }
486
    return GetTicketAux($credential,
487
			$rspecstr, $isupdate, $impotent, 0, 1, 0, $ticket);
488
}
489

490
sub GetTicketAux($$$$$$$$$@)
491
{
492
    my ($credential, $rspecstr, $isupdate, $impotent, $v2, $level, $usetracker,
493
	$ticket, $speaksfor, @morecreds) = @_;
494
    
495 496 497 498 499 500
    defined($credential) &&
	($credential->HasPrivilege( "pi" ) or
	 $credential->HasPrivilege( "instantiate" ) or
	 $credential->HasPrivilege( "bind" ) or
	 return GeniResponse->Create( GENIRESPONSE_FORBIDDEN, undef,
				      "Insufficient privilege" ));
501
    
502 503
    my $slice_urn = $credential->target_urn();
    my $user_urn  = $credential->owner_urn();
504
    
Leigh Stoller's avatar
Leigh Stoller committed
505
    #
506
    # Create user from the certificate.
Leigh Stoller's avatar
Leigh Stoller committed
507
    #
508
    my $user = CreateUserFromCertificate($credential);
509 510
    return $user
	if (GeniResponse::IsResponse($user));
511 512 513

    # Bump activity. Does not matter if request fails ...
    $user->BumpActivity();
514
    
Leigh Stoller's avatar
Leigh Stoller committed
515
    #
516
    # Create slice from the certificate.
Leigh Stoller's avatar
Leigh Stoller committed
517
    #
518 519
    my $slice = GeniSlice->Lookup($slice_urn);
    if (!defined($slice)) {
520
	if ($isupdate) {
521
	    print STDERR "Could not locate slice $slice_urn for Update\n";
522
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
523 524 525
					"No slice found for UpdateTicket");
	}
	$slice = CreateSliceFromCertificate($credential, $user);
526 527
	return $slice
	    if (GeniResponse::IsResponse($slice));
Leigh Stoller's avatar
Leigh Stoller committed
528
    }
529 530 531
    $slice->SetSpeaksFor($speaksfor)
	if (defined($speaksfor));
	
532
    main::AddLogfileMetaDataFromSlice($slice);
533
    
534
    return GetTicketAuxAux($slice, $user, $rspecstr,
535 536
			   $isupdate, $impotent, $v2, $level, $usetracker,
			   $ticket, [$credential, @morecreds], $speaksfor);
537
}
538
sub GetTicketAuxAux($$$$$$$$$$$)
539
{
540
    my ($slice, $user, $rspecstr, $isupdate,
541 542
	$impotent, $v2, $level, $usetracker,
	$ticket, $credentials, $speaksfor) = @_;
543 544 545
    my $response    = undef;
    my $restorevirt = 0;	# Flag to restore virtual state
    my $restorephys = 0;	# Flag to restore physical state
546
    require OSinfo;
547
    require Image;
548
    require VirtExperiment;
549 550 551 552 553 554

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

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
    #
    # Run xmllint on the rspec to catch format errors.
    #
    my ($fh, $filename) = tempfile(UNLINK => 0);
    if (!defined($fh)) {
	print STDERR "Could not create temp file for rspec\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
    print $fh $rspecstr;
    close($fh);
    my $xmlerrors = `$XMLLINT --noout $filename 2>&1`;
    unlink($filename);
    if ($?) {
	return GeniResponse->Create(GENIRESPONSE_ERROR,
				    $xmlerrors,
				    "rspec is not well formed");
    }

577 578
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
579
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
580
				    "Error Parsing rspec XML");
581
    }
Leigh Stoller's avatar
Leigh Stoller committed
582

583 584 585 586 587 588
    my $rspecVersion = GeniXML::GetXmlVersion($rspec);
    if (! defined($rspecVersion)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Unknown RSpec Version");
    }

Leigh Stoller's avatar
Leigh Stoller committed
589 590 591 592
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
593
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
594 595 596 597
	    # Cannot get the value, say no.
	    $allow_externalusers = 0;
    }

598 599 600 601 602 603 604 605 606 607 608
    # Image tracker.
    my $use_imagetracker;
    if (!GetSiteVar('protogeni/use_imagetracker', \$use_imagetracker)) {
	# Cannot get the value, say no.
	$use_imagetracker = 0;
    }
    # But the Portal is currently the one telling us to use the tracker
    # for specific slices.
    $use_imagetracker = 1
	if ($use_imagetracker && $usetracker);

609 610 611 612 613 614 615 616 617 618
    # Figure out if user has a credentials that exempts him
    # from the following policy. If external users are blocked access
    # and he presents a credential that exempts him from it, 
    # then he should get access.
    my $isExempted = 0;
    foreach my $credential (@$credentials) {
      if (1 == GeniXML::PolicyExists('allow_externalusers', $credential)) {
        $isExempted = 1;
        last;
      }
Leigh Stoller's avatar
Leigh Stoller committed
619
    }
620 621 622

    if (!$allow_externalusers && !$isExempted && !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
Leigh Stoller's avatar
Leigh Stoller committed
623 624 625 626
				    "External users temporarily denied");
    }
    
    #
627
    # For now all tickets expire very quickly (minutes), but once the
Leigh Stoller's avatar
Leigh Stoller committed
628
    # ticket is redeemed, it will expire according to the rspec request.
629 630
    # If nothing specified in the rspec, then it will expire when the
    # slice record expires, which was given by the expiration time of the
631 632
    # slice credential, or the local policy max_sliver_lifetime. See
    # CreateSliceFromCertificate() in this file.
Leigh Stoller's avatar
Leigh Stoller committed
633
    #
634
    my $expires = GeniXML::GetExpires($rspec);
635
    if (defined($expires)) {
636 637
	if (GeniResponse::IsResponse($expires)) {
	    return $expires;
Leigh Stoller's avatar
Leigh Stoller committed
638
	}
639 640
	# Note "checkonly" flag; we do not actually change the slice
	# until the ticket is redeemed. 
641
	my $tmp = SetSliceExpiration($slice, $expires, 1, 0, @{ $credentials });
642 643
	if (GeniResponse::IsResponse($tmp)) {
	    return $tmp;
644
	}
Leigh Stoller's avatar
Leigh Stoller committed
645
    }
646 647 648 649 650 651 652

    #
    # Lock the ticket so it cannot be released.
    #
    if (defined($ticket) && $ticket->stored() && $ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
    }
653 654 655
    if (defined($ticket)) {
	$ticket->SetSlice($slice);
    }
Leigh Stoller's avatar
Leigh Stoller committed
656 657 658 659 660 661
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
662 663 664
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh Stoller's avatar
Leigh Stoller committed
665
    }
666 667 668
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
669 670
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
671 672 673
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
674 675 676 677 678 679 680 681
    # Ditto for expired.
    if ($slice->IsExpired()) {
	$slice->UnLock();
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
				    "Slice has expired");
    }
Leigh Stoller's avatar
Leigh Stoller committed
682

683
    #
Leigh Stoller's avatar
Leigh Stoller committed
684
    # For now, there can be only a single toplevel aggregate per slice.
685
    # The existence of an aggregate means the slice is active here. 
Leigh Stoller's avatar
Leigh Stoller committed
686
    #
687
    my $aggregate = GeniAggregate->SliceAggregate($slice);
688 689 690 691 692
    if (!$isupdate) {
	if (defined($aggregate)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Already have an aggregate for slice");
	    goto bad;
693 694
	}
    }
695 696 697 698 699
    elsif ($v2 && $level && !defined($ticket) && !defined($aggregate)) {
	print STDERR "No aggregate for $slice in version two API\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
700

701
    #
Leigh Stoller's avatar
Leigh Stoller committed
702
    # We need this now so we can form a virtual topo.
703
    #
704 705 706 707 708 709 710 711 712 713 714
    my $slice_experiment = GeniExperiment($slice, $user);
    if (GeniResponse::IsResponse($slice_experiment)) {
	$response = $slice_experiment;
	$slice_experiment = undef;
	goto bad;
    }
    my $realuser = FlipToUser($slice, $user);
    if (! (defined($realuser) && $realuser)) {
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					 "FlipToUser Error");
	print STDERR "Error flipping to real user\n";
Leigh Stoller's avatar
Leigh Stoller committed
715 716 717 718
	goto bad;
    }
    my $pid = $slice_experiment->pid();
    my $eid = $slice_experiment->eid();
719 720 721 722 723

    #
    # Mark the experiment locally as coming from the cooked interface.
    # This changes what tmcd returns to the local nodes.
    #
724
    my $generated_by = GeniXML::GetText("generated_by", $rspec);
725 726
    if (defined($generated_by) &&
	$generated_by eq "libvtop") {
727 728 729 730
	$slice_experiment->Update({"geniflags" =>
				       $Experiment::EXPT_GENIFLAGS_EXPT|
				       $Experiment::EXPT_GENIFLAGS_COOKED});
    }
Leigh Stoller's avatar
Leigh Stoller committed
731 732 733 734 735 736 737 738 739 740 741 742 743
    
    #
    # 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);
744
    $virtexperiment->multiplex_factor(10);
745

746 747 748 749 750 751 752 753 754 755
    #
    # Add global vtypes.
    #
    my $vtypes_result =
	emdb::DBQueryWarn("select * from global_vtypes");
    if (!$vtypes_result) {
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
    while (my $row = $vtypes_result->fetchrow_hashref()) {
756
	$virtexperiment->NewTableRow("virt_vtypes",
757 758 759 760
				     {"name"     => $row->{'vtype'},
				      "members"  => $row->{'types'},
				      "weight"   => $row->{'weight'}
				     });
761
    }
762

763 764 765 766 767
    # Need to move this someplace else; the parser adds a bunch.
    $virtexperiment->NewTableRow("virt_agents",
				 {"vnode"      => "*",
				  "vname"      => "ns",
				  "objecttype" => "6"});
768

769 770 771
    #
    # Look for toplevel address pools
    #
772 773 774 775 776 777 778 779 780 781 782 783 784
    if (Node::HaveExperimentNodes()) {
	my $address_pools = GeniXML::GetAddressPools($rspec);
	foreach my $pool (@{ $address_pools }) {
	    if (! defined($pool->{'cmurn'}) ||
		$pool->{'cmurn'} eq $ENV{'MYURN'})
	    {
		if ($pool->{'type'} ne "any") {
		    $response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
		     "Only public address pools of type any are supported");
		    goto bad;
		}
		print STDERR 'DEBUG: Adding row to virt_address_allocation';
		$virtexperiment->NewTableRow("virt_address_allocation",
785 786 787 788
					 {"pool_id" => $pool->{'client_id'},
					  "count" => $pool->{'count'},
					  "restriction" => $pool->{'type'},
					  "version" => "ipv4" });
789
	    }
790 791 792
	}
    }

793 794 795 796 797 798 799 800 801 802 803 804
    #
    # Look for toplevel elabinelab section.
    #
    my $elabinelab_settings = GeniXML::GetElabInElabSettings($rspec);
    if (defined($elabinelab_settings)) {
	$virtexperiment->elab_in_elab(1);
	if (exists($elabinelab_settings->{'singlenet'})) {
	    $virtexperiment->elabinelab_singlenet(1);
	}
	if (exists($elabinelab_settings->{'xen'})) {
	    $virtexperiment->multiplex_factor(2);
	}
805 806 807
    }
    if ($PROTOGENI_NONFSMOUNTS) {
	$virtexperiment->nonfsmounts(1);
808 809
    }

Leigh Stoller's avatar
Leigh Stoller committed
810
    #
Leigh Stoller's avatar
Leigh Stoller committed
811 812
    # An rspec is a structure that requests specific nodes. If those
    # nodes are available, then reserve it. Otherwise the ticket
Leigh Stoller's avatar
Leigh Stoller committed
813 814
    # cannot be granted.
    #
815 816 817
    my %namemap  = ();
    my %colomap  = ();
    my %ifacemap = ();
818
    my %iface2node = ();
819
    my %vportmap = ();
Leigh Stoller's avatar
Leigh Stoller committed
820
    my %nodemap  = ();
821
    my %bridgemap= ();
822
    my @nodeids  = ();
823
    my %lannodes = ();
824
    # For stitching, keep track of external nodes and links.
825 826 827
    my %external_nodemap  = ();
    my %external_linkmap  = ();
    my %external_vportmap = ();
828
    my %external_lanrefs  = ();
829

830 831 832
    # Always do this to avoid buildup.
    $slice_experiment->ClearBackupState();
    
833 834 835 836 837 838 839
    #
    # 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 Stoller's avatar
Leigh Stoller committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
	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;
	}
857 858 859 860 861 862 863
	my $oldrspec;
	if ($v2 && defined($aggregate)) {
	    $oldrspec = $aggregate->GetManifest(0);
	}
	else {
	    $oldrspec = $ticket->rspec();
	}
Leigh Stoller's avatar
Leigh Stoller committed
864
	
865
	foreach my $ref (GeniXML::FindNodes("n:node",
866
					    $oldrspec)->get_nodelist()) {
867
	    # Let remote nodes pass through.
868
	    next
869
		if (!GeniXML::IsLocalNode($ref));
870

871 872
	    # Skip lan nodes; they are fake.
	    next
873
		if (GeniXML::IsLanNode($ref));
874

875
	    my $node_nickname = GeniXML::GetVirtualId($ref);
876
	    my $colocate      = GeniXML::GetColocate($ref);
877
	    my $component_id  = GeniXML::GetNodeId($ref);
878 879
	    my $vnode_id      = GeniXML::GetVnodeId($ref);
	    my $node = GeniUtil::LookupNode($vnode_id);
880 881
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
882
				 "Bad resource $component_id in ticket");
883 884
		goto bad;
	    }
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	    #
	    # Is the node a virtual node? Must be an update to an
	    # existing sliver/ticket, since we now return the node_id
	    # of the allocated virtual node, not the physical node.
	    #
	    if ($node->isvirtnode()) {
		my $pnode = Node->Lookup($node->phys_nodeid());
		if (!defined($pnode)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "No physical resource for $component_id");
		    goto bad;
		}
		$node = $pnode;
	    }
900 901 902 903 904
	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
905

906
    print GeniXML::Serialize($rspec);
Leigh Stoller's avatar
Leigh Stoller committed
907

908 909
    my %nodeexistsmap = ();

910
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
911
	my $component_id  = GeniXML::GetNodeId($ref);
912
	my $vnode_id      = GeniXML::GetVnodeId($ref);
913
	my $manager_id    = GeniXML::GetManagerId($ref);
914
	my $node_nickname = GeniXML::GetVirtualId($ref);
915 916 917 918
	my $colocate      = GeniXML::GetColocate($ref);
	my $subnode_of    = GeniXML::GetSubnodeOf($ref);
	my $virtualization_type = GeniXML::GetVirtualizationType($ref);
	
919
	my $virtualization_subtype
920 921
                          = GeniXML::GetVirtualizationSubtype($ref);
	my $exclusive     = GeniXML::GetExclusive($ref);
922
	my $tarfiles      = GeniXML::GetTarball($ref);
923
	my $pctype;
924
	my ($osname, $osinfo);
925
	my $parent_osname;
Leigh Stoller's avatar
Leigh Stoller committed
926
	my $node;
927 928
	my $isbridge    = 0;
	my $isfirewall  = 0;
Leigh Stoller's avatar
Leigh Stoller committed
929
	my $xensettings;
930
	my $fwsettings;
931
	
932
	if (exists($nodeexistsmap{lc($node_nickname)})) {
933 934 935 936 937
	    $response =
		GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Duplicate node $node_nickname");
	    goto bad;
	}
938
	$nodeexistsmap{lc($node_nickname)} = 1;
939

940 941 942 943 944
	# Always populate iface2node mapping, even if we let the node
	# pass through.
	foreach my $linkref (GeniXML::FindNodes("n:interface",
						$ref)->get_nodelist()) {
	    my $virtual_id   = GeniXML::GetInterfaceId($linkref);
945 946 947 948 949 950 951
	    if (exists($iface2node{$virtual_id})) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Duplicate interface $virtual_id on ".
					 "node $node_nickname");
		goto bad;
	    }
952 953 954
	    $iface2node{$virtual_id} = $node_nickname;
	}

955
	# Let remote nodes pass through.
956 957 958 959
	if (! GeniXML::IsLocalNode($ref)) {
	    $external_nodemap{$node_nickname} = $ref;
	    next;
	}
960

961
	#
962 963 964 965 966
	#
	# 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. 
	#
967
	if (GeniXML::IsLanNode($ref)) {
968 969 970 971
	    $lannodes{$node_nickname} = $ref;
	    next;
	}

972 973 974 975 976 977 978 979
	#
	# Check for total hostname length > 63 characters. This
	# breaks a lot of clients. Do this until we have a plan
	# for dealing with it on the clients. Why 63 instead of 64?
	# Cause of a bug in the event library code, that is now fixed,
	# but will not make it out to all images for a while. 
	#
	my $fullhostname = $node_nickname . ".${eid}.${pid}.${OURDOMAIN}";
980
	if (0 && length($fullhostname) > 63) {
981 982 983 984
	    $response = GeniResponse->Create(GENIRESPONSE_TOOBIG, undef,
				     "Hostname > 63 characters: $fullhostname");
	    goto bad;
	}
985 986 987
	#
	# Check for disk_image request. Specified as a URN. 
	#
988
	my $diskref = GeniXML::GetDiskImage($ref);
989 990
	if (defined($diskref)) {
	    my $dname = GeniXML::GetText("name", $diskref);
991
	    my $url   = GeniXML::GetText("url", $diskref);
992

993 994 995 996 997
	    # url is deprecated; name can be anything.
	    if (defined($dname) && $dname =~ /^http/) {
		$url = $dname;
	    }

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	    if (defined($url)) {
		if (! TBcheck_dbslot($url, "virt_nodes", "osname",
				 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)){
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					     "Invalid disk image url: $url");
		    goto bad;
		}
		#
		# Pass it right through; we load them later.
		# There is no osinfo, but see below. 
		#
		$osname = $url;
	    }
	    elsif (defined($dname)) {
1013 1014 1015 1016 1017 1018 1019
		if (! GeniHRN::IsValid($dname)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
		my ($auth,$type,$id) = GeniHRN::Parse($dname);
1020 1021
		my ($ospid,$os,undef,$vers) =
		    ($id =~ m{([^/]+)//([^/]+)(//(\d+))?});		
1022 1023 1024 1025 1026 1027
		if ($type ne "image" || !defined($ospid) || !defined($os)){
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
1028
		$osinfo = OSinfo->Lookup($ospid, $os, $vers);
1029
		if (!defined($osinfo)) {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
		    if ($use_imagetracker) {
			my $image = GeniImage::MapToLocalImage($dname, $pid);
			if (GeniResponse::IsError($image)) {
			    $response = $image;
			    goto bad;
			}
			$osname = ($image->IsLocal() ?
				   $image->versname() :
				   $image->metadata_url());
		    }
		    else {
			$response =
			    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
						 "Unknown image URN: $dname");
			goto bad;
		    }
1046
		}
1047 1048 1049 1050 1051 1052 1053 1054 1055
		else {
		    #
		    # The OS must be in the current project, or it must
		    # be global (okay, shared).
		    #
		    if (! ($osinfo->shared() ||
			   $osinfo->pid() eq $slice_experiment->pid())) {
			$response =
			    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1056
				 "Insufficient permission to use $osinfo");
1057 1058
			goto bad;
		    }
1059
		
1060 1061 1062 1063 1064 1065
		    #
		    # This is only going to be used in raw mode. 
		    #
		    $osname  = "$ospid/$os";
		    $osname .= ":${vers}" if (defined($vers));
		}
1066 1067 1068
	    }
	}

Leigh Stoller's avatar
Leigh Stoller committed
1069 1070 1071
	if (defined($virtualization_type)) {
	    if ($virtualization_type eq "emulab-vnode") {
		if (defined($virtualization_subtype)) {
1072 1073
		    $pctype = "pcvm";
		    
Leigh Stoller's avatar
Leigh Stoller committed
1074 1075 1076 1077
		    if ($virtualization_subtype eq "emulab-jail") {
			$osname = "FBSD-JAIL";
		    }
		    elsif ($virtualization_subtype eq "emulab-openvz") {
1078 1079 1080 1081 1082 1083 1084 1085
			# Allow caller to set the image to use, but also
			# trick to set the parent. 
			if (defined($osinfo)) {
			    if (! $osinfo->IsSubOS()) {
				$parent_osname = $osname;
				$osname = "OPENVZ-STD";
			    }
			}
1086 1087
			elsif (!defined($osname)) {
			    # Allow for url above.
1088 1089
			    $osname = "OPENVZ-STD";
			}
Leigh Stoller's avatar
Leigh Stoller committed
1090
		    }
1091 1092
		    elsif ($virtualization_subtype eq "emulab-xen" ||
			   $virtualization_subtype eq "default-vm") {
1093 1094 1095 1096 1097
			# Allow caller to set the image to use, but also
			# trick to set the parent. 
			if (defined($osinfo)) {
			    if (! $osinfo->IsSubOS()) {
				$parent_osname = $osname;
1098
				$osname = "UBUNTU12-64-STD";
1099 1100 1101 1102
			    }
			}
			elsif (!defined($osname)) {
			    # Allow for url above.
1103
			    $osname = "UBUNTU12-64-STD";
1104
			}
Leigh Stoller's avatar
Leigh Stoller committed
1105 1106 1107 1108 1109 1110
			#
			# Look for the knobs
			#
			if (GeniXML::HasXenSettings($ref)) {
			    $xensettings = GeniXML::GetXenSettings($ref);
			}
1111 1112 1113
			my $ptype = GeniXML::XenPtype($ref);
			$pctype = $ptype
			    if (defined($ptype));
1114
			$virtexperiment->encap_style("vlan");
1115 1116 1117 1118 1119 1120 1121

			#
			# Per-vnode firewall options.
			#
			if (GeniXML::HasFirewallSettings($ref)) {
			    $fwsettings = GeniXML::GetFirewallSettings($ref);
			}
1122
		    }
1123 1124 1125 1126
		    elsif ($virtualization_subtype eq "emulab-spp") {
			$osname = "SPPVM-FAKE";
			$pctype = "sppvm";
			# Lets force to shared node.
1127
			if (! GeniXML::SetExclusive($ref, 0)) {
1128 1129 1130
			    $response
				= GeniResponse->Create(GENIRESPONSE_BADARGS,
						       undef,
1131 1132
				       "Malformed rspec: ".
				       "Cannot set exclusive tag to false");
1133 1134 1135
			    goto bad;
			}
			$exclusive = 0;
1136 1137
			# Kludge for libvtop.
			$virtexperiment->multiplex_factor(1);
1138
			$virtexperiment->encap_style("vlan");
1139
		    }
1140 1141 1142 1143 1144 1145
		    elsif ($virtualization_subtype eq "emulab-bbg") {
			$osname = "BBGENIVM-FAKE";
			$pctype = "bbgenivm";
			# Lets force to shared node.
			GeniXML::SetExclusive($ref, 0);
			$exclusive = 0;
1146
			$virtexperiment->multiplex_factor(5);
1147 1148
			$virtexperiment->encap_style("vlan");
		    }
1149 1150 1151 1152
		    elsif ($virtualization_subtype eq "emulab-blockstore") {
			$osname = "BLOCKSTORE-VM";
			$pctype = "blockstore";
		    }
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
		    elsif ($virtualization_subtype eq "emulab-connect") {
			$osname = "GENERICDEV-VM";
			$pctype = "interconnect-vm";
			# Lets force to shared node.
			GeniXML::SetExclusive($ref, 0);
			$exclusive = 0;
			# Kludge for libvtop.
			$virtexperiment->multiplex_factor(5);
			$virtexperiment->encap_style("vlan");
		    }
1163 1164
		    elsif ($virtualization_subtype eq "raw"
			   || $virtualization_subtype eq "raw-pc") {
1165 1166 1167
			$pctype = undef;
			goto raw;
		    }
1168 1169 1170 1171
		    elsif ($virtualization_subtype eq "delay") {
			$isbridge = 1;
			$pctype   = undef;
		    }
1172 1173 1174 1175 1176 1177
		    elsif ($virtualization_subtype eq "firewall") {
			$isfirewall = 1;
			$osname     = "FW-IPFW2";
			$pctype     = "pc";
			goto raw;
		    }
1178 1179 1180 1181 1182 1183 1184 1185
		    else {
			$response
			    = GeniResponse->Create(GENIRESPONSE_BADARGS,
						   undef,
				       "Malformed rspec: ".
				       "Unknown virtualization_subtype");
			goto bad;
		    }
Leigh Stoller's avatar
Leigh Stoller committed
1186 1187 1188 1189 1190 1191 1192 1193
		}
		else {
		    goto raw;
		}
	    }
	    else {
	      raw:
		# Lets force to exclusive real node.
1194
		if (! GeniXML::SetExclusive($ref, 1)) {
1195 1196
		    $response = GeniResponse->Create(GENIRESPONSE_BADARGS,
						     undef,
1197
			"Malformed rspec: Cannot set exclusive tag to true");
1198 1199 1200
		    goto bad;
		}
		$exclusive = 1;
1201 1202 1203 1204 1205
		my $subtype = "raw-pc";
		if (GeniXML::IsVersion0($ref)) {
		    $subtype = "raw";
		}
		if (! GeniXML::SetVirtualizationSubtype($ref, $subtype)) {
1206 1207
		    $response = GeniResponse->Create(GENIRESPONSE_BADARGS,
						     undef,
1208
			"Malformed rspec: Cannot set virtualization_type to raw");
1209 1210
		    goto bad;
		}
Leigh Stoller's avatar
Leigh Stoller committed
1211 1212 1213 1214
	    }
	}
	else {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1215
				     "Must provide a virtualization_type");
Leigh Stoller's avatar
Leigh Stoller committed
1216 1217 1218
	    goto bad;

	}
1219 1220 1221 1222 1223 1224
	if (!defined($node_nickname)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Must provide a virtual_id for nodes");
	    goto bad;
	}

Leigh Stoller's avatar
Leigh Stoller committed
1225
	#
Leigh Stoller's avatar
Leigh Stoller committed
1226
	# Allow wildcarding.
Leigh Stoller's avatar
Leigh Stoller committed
1227
	#
1228
	if (!defined($component_id) || $component_id eq "*") {
1229 1230 1231 1232 1233
	    if (defined($colocate) && exists($colomap{$colocate})) {
		$node = $colomap{$colocate};
	    }
	    elsif ($isupdate && exists($namemap{$node_nickname})) {
		$node = $namemap{$node_nickname};
1234
	    }
1235 1236
	    # If the node still isn't bound and doesn't have a pctype,
	    # use the user-specified one.
1237 1238 1239 1240 1241 1242 1243 1244 1245
	    if (GeniXML::IsVersion0($ref)) {
		if (! defined($node) && ! defined($pctype)) {
		    my $usertype = GeniXML::FindFirst("n:node_type", $ref);
		    if (defined($usertype)) {
			$pctype = GeniXML::GetText("type_name", $usertype);
		    }
		}
	    } else {
		my $usertype = GeniXML::FindFirst("n:hardware_type", $ref);
1246
		if (defined($usertype)) {
1247 1248 1249 1250 1251 1252
		    #
		    # Watch for pcvm type set above. If the user specified
		    # a hardware type for their VMs, then form a proper
		    # hardware specific pcvm type. 
		    #
		    my $pt = GeniXML::GetText("name", $usertype);
Leigh Stoller's avatar
Leigh Stoller committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
		    if (!defined($pt)) {
			$response =
			    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
						 "Bad hardware_type");
			goto bad;
		    }
		    if (defined($pctype) && $pctype eq "pcvm") {
			$pctype = "${pt}-vm";
		    }
		    else {
			$pctype = $pt;
		    }
1265 1266
		}
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1267 1268
	}
	else {
1269
	    $node = GeniUtil::LookupNode($vnode_id);
Leigh Stoller's avatar
Leigh Stoller committed
1270 1271 1272 1273

	    if (!defined($node)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1274
					 "Bad resource $component_id");
Leigh Stoller's avatar
Leigh Stoller committed
1275 1276
		goto bad;
	    }
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
	    #
	    # Is the node a virtual node? Must be an update to an
	    # existing sliver/ticket, since we now return the node_id
	    # of the allocated virtual node, not the physical node.
	    #
	    if ($node->isvirtnode()) {
		if (!$isupdate ||
		    !exists($namemap{$node_nickname})) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Bad resource for $node_nickname");
		    goto bad;
		}
		$node = $namemap{$node_nickname};
	    }
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
	    #
	    # Watch for pcvm type set above. If the user specified
	    # a hardware type for their VMs, then form a proper
	    # hardware specific pcvm type.
	    #
	    if (defined($pctype) && $pctype eq "pcvm" &&
		(my $usertype =
		 GeniXML::FindFirst("n:hardware_type", $ref))) {
		my $htype = GeniXML::GetText("name", $usertype);
		if (defined($htype)) {
		    $pctype = "${htype}-vm";
		}
	    }
1305 1306
	    $pctype = $node->type()
		if (!defined($pctype));
1307
	}
1308

1309
	#
1310
	# If no osname, check for protogeni default osname
1311
	#
1312
	if (! defined($osname)) {
1313
	    my $protogeni_os = undef;
1314
	    if (GetSiteVar('protogeni/default_osname', \$protogeni_os)
1315 1316
		&& $protogeni_os ne ""
		&& (! defined($pctype) || $pctype ne "bbgeni")) {
1317
		$osname = $protogeni_os;
1318 1319 1320 1321 1322 1323 1324 1325
	    }
	}

	#
	# If no osname by this point, try for the default.
	#
	if (defined($node) && !defined($osname)) {
	    if (defined($node->default_osid())) {
1326 1327 1328
		my $default_osinfo = OSinfo->Lookup($node->default_osid());
		$osname = $default_osinfo->osname()
		    if (defined($default_osinfo));
1329
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1330
	}
1331 1332 1333
	# The slot does not like to be NULL.
	$osname = ""
	    if (!defined($osname));
1334
	
1335 1336 1337
	# Need some kind of default.
	$pctype = "pc"
	    if (!defined($pctype));
1338
	
1339 1340 1341 1342 1343
	my $nodeblob = {"vname"   => $node_nickname,
			"type"    => $pctype,
			"osname"  => $osname,
			"ips"     => '', # deprecated
			"cmd_line"=> '', # bogus
1344
			"routertype" => "static-ddijk",
Leigh Stoller's avatar
Leigh Stoller committed
1345 1346
			"fixed"   => (defined($subnode_of) ? $subnode_of :
				      defined($node) ? $node->node_id() : ""),
1347
			    
1348
			};
1349 1350 1351 1352
	
	if (defined($parent_osname)) {
	    $nodeblob->{'parent_osname'} = "$parent_osname";
	}
1353 1354 1355
	if ($isbridge) {
	    $nodeblob->{'role'} = "bridge";
	}
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
	elsif ($isfirewall) {
	    if ($slice->SetFirewallFlag(1) != 0) {
		$response = GeniResponse->Create(GENIRESPONSE_ERROR);
		goto bad;
	    }
	    $nodeblob->{'cmd_line'} = '/kernel.fw';
	    if (!defined($virtexperiment->NewTableRow("virt_firewalls",
						  {"fwname" => $node_nickname,
						   "type"   => "ipfw2-vlan",
						   "style"  => "basic"}))) {
		$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				     "Error creating firewall definition");
		goto bad;
	    }
	}
1371
	# Tarball and startup command.
1372
	if (defined($tarfiles)) {
1373
	    if (! TBcheck_dbslot($tarfiles, "virt_nodes", "tarfiles",
1374
				 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)){
1375 1376
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1377
			 "Invalid tarfiles: " . TBFieldErrorString());
1378 1379
		goto bad;
	    }
1380
	    $nodeblob->{'tarfiles'} = $tarfiles;
1381
	}
1382 1383 1384 1385
	if (GeniXML::IsVersion0($ref)) {
	    my $startupcmd = GeniXML::GetStartupCommand($ref);
	    if (defined($startupcmd)) {
		if (! TBcheck_dbslot($startupcmd, "virt_nodes", "startupcmd",
1386
				TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
1387 1388
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1389
			   "Invalid startup command: " . TBFieldErrorString());
1390 1391 1392 1393 1394 1395
		    goto bad;
		}
		$nodeblob->{'startupcmd'} = $startupcmd;
	    }
	}
	elsif (my @services = GeniXML::GetServices($ref)) {
1396 1397 1398 1399
	    my $startupCommand = undef;
	    my $startupCount = 0;
	    foreach my $service (@services) {
		if ($service->{'type'} eq "execute") {
1400 1401 1402 1403 1404 1405 1406
		    if (!defined($service->{'cmd'}) ||
			$service->{'cmd'} eq "") {
			$response =
			    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
			     "Invalid service command: no command provided");
			goto bad;
		    }
1407 1408 1409 1410 1411 1412 1413 1414
		    if ($startupCount == 0) {
			$startupCommand = $service->{'cmd'};
		    }
		    ++$startupCount;
		}
	    }

	    if ($startupCount == 1 && defined($startupCommand)) {
1415
		if (! TBcheck_dbslot($startupCommand, "virt_nodes","startupcmd",
1416 1417 1418
				TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1419
			   "Invalid startup command: " . TBFieldErrorString());
1420 1421 1422 1423 1424
		    goto bad;
		}
		$nodeblob->{'startupcmd'} = $startupCommand;

	    } else { # BEGIN TEMPORARY ELSE
1425
	    my $count = 0;
1426 1427
	    my $startfile = $slice_experiment->UserDir() .
		"/geni_startup." . $node_nickname;
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
	    $nodeblob->{'startupcmd'} = $startfile;
	    
	    if (!open(STARTUP, ">$startfile")) {
		$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
						 "Error creating startfile");
		goto bad;
	    }
	    print STARTUP "#!/bin/sh\n\n";
	    print STARTUP "# Redirect all output to a file\n";
	    print STARTUP "exec &> /var/tmp/startup.log\n\n";

	    #
	    # It would be nice to interleave "install" with "execute", but
	    # Emulab's tarfiles support arranges to copy the files locally,
	    # and rewrites the names. Need to hook into that support somehow,
	    # but for now tarfiles are all installed as a block above. 
	    #
	    foreach my $service (@services) {
		my $type = $service->{'type'};

		if ($type eq "execute") {
		    my $shell = $service->{'shell'};
		    my $cmd   = $service->{'cmd'};
		    my $log   = "/var/tmp/startup-${count}.txt";
		    my $stat  = "/var/tmp/startup-${count}.status";

		    #
		    # Support only sh and csh. Maybe perl later.
		    #
1457 1458 1459
		    if (! (defined($shell) &&
			   ($shell eq "csh" || $shell eq "sh" ||
			    $shell eq "/bin/csh" || $shell eq "/bin/sh"))) {
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
			$response =
			    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
						 "Invalid shell in execute");
			goto bad;
		    }
		    if (! ($shell =~ /bin/)) {
			$shell = "/bin/$shell";
		    }
		    print STARTUP "echo -n 'Services execution $count at '\n";
		    print STARTUP "date\n\n";
		    print STARTUP "$shell -c \"$cmd\" >$log 2>&1\n";
		    print STARTUP "status=\$?\n";
		    print STARTUP "echo \"\$status\" > $stat\n";
		    print STARTUP
		      "echo \"Execution $count exited with status \$status\"\n";
		    print STARTUP "echo '----------------------------------'\n";
		    $count++;
		}
	    }
	    print STARTUP "exit 0\n";
	    close(STARTUP);
	    chmod(0755, $startfile);
1482
	    } # END TEMPORARY ELSE
1483
	}
1484

1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
	my $elabsettings = GeniXML::GetElabInElabSettings($ref);
	if (defined($elabsettings)) {
	    my $extradisksize;
	    my $extradiskmnts;
	    
	    if (exists($elabsettings->{'role'})) {
		my $erole =