GeniCM.pm.in 200 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
42 43 44

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

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

128 129 130 131 132
# For location info.
my $default_longitude = undef;
my $default_latitude  = undef;
my $default_country   = undef;

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

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

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

183
    my $credential = GeniCredential::CheckCredential($cred);
184 185 186
    return $credential
	if (GeniResponse::IsResponse($credential));

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

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

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

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

238
    my $credential = GeniCredential::CheckCredential($credstr);
239 240
    return $credential
	if (GeniResponse::IsResponse($credential));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
241

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

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

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

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

    # 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) {
287
        if (GeniXML::PolicyExists('allow_externalusers', $credential) == 1) {
288 289 290 291 292 293
        $isExempted = 1;
        last;
      }
    }

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

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    #
    # 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 B. Stoller's avatar
Leigh B. Stoller committed
321
    #
322
    # Acquire the advertisement from ptopgen and compress it if requested.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
323
    #
324
    my $xml = GetAdvertisement($available, undef, $version, $experiment);
325
    if (! defined($xml)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
326 327 328 329
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }

330 331 332 333 334 335
    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
336 337
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $xml);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
338

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

349 350 351 352 353 354 355
    $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");

356
    my $invocation = "$PTOPGEN -x -g $version -r";
357 358 359 360
    if (defined($experiment)) {
	my $eid = $experiment->eid();
	$invocation .= " -e $eid";
    }
361 362 363 364
    $invocation .= " -a" unless $available;
    if (defined($pc)) {
	$invocation .= " -1 $pc";
    }
365 366 367 368 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
    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;
	}
    }
404
    if (open(AVAIL, "$invocation |")) {
405
	$xml = "";
406 407 408 409 410
	while (<AVAIL>) {
	    $xml .= $_;
	}
	close(AVAIL);
    }
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    #
    # 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();
    }
432 433 434
    return $xml;
}

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

    return GetTicket($argref, 1);
}

#
# Respond to a GetTicket request. 
#
sub GetTicket($;$)
{
    my ($argref, $isupdate) = @_;
451
    my $rspecstr   = $argref->{'rspec'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
452
    my $impotent   = $argref->{'impotent'};
453 454
    my $credstr    = $argref->{'credential'};
    my $tickstr    = $argref->{'ticket'};
455 456 457 458 459 460 461
    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
462

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

477
    if ($isupdate) {
478
	$ticket = CheckTicket($tickstr, $credential->target_urn());
479 480
	return $ticket
	    if (GeniResponse::IsResponse($ticket));
481
    }
482
    return GetTicketAux($credential,
483
			$rspecstr, $isupdate, $impotent, 0, 1, $ticket);
484
}
485

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

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

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

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    #
    # 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");
    }

572 573
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
574
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
575
				    "Error Parsing rspec XML");
576
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
577

578 579 580 581 582 583
    my $rspecVersion = GeniXML::GetXmlVersion($rspec);
    if (! defined($rspecVersion)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Unknown RSpec Version");
    }

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

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

    if (!$allow_externalusers && !$isExempted && !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
607 608 609 610
				    "External users temporarily denied");
    }
    
    #
611
    # For now all tickets expire very quickly (minutes), but once the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
612
    # ticket is redeemed, it will expire according to the rspec request.
613 614
    # If nothing specified in the rspec, then it will expire when the
    # slice record expires, which was given by the expiration time of the
615 616
    # slice credential, or the local policy max_sliver_lifetime. See
    # CreateSliceFromCertificate() in this file.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
617
    #
Jonathon Duerig's avatar
Jonathon Duerig committed
618
    my $expires = GeniXML::GetExpires($rspec);
619
    if (defined($expires)) {
620 621
	if (GeniResponse::IsResponse($expires)) {
	    return $expires;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
622
	}
623 624
	# Note "checkonly" flag; we do not actually change the slice
	# until the ticket is redeemed. 
625
	my $tmp = SetSliceExpiration($slice, $expires, 1, 0, @{ $credentials });
626 627
	if (GeniResponse::IsResponse($tmp)) {
	    return $tmp;
628
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
629
    }
630 631 632 633 634 635 636

    #
    # Lock the ticket so it cannot be released.
    #
    if (defined($ticket) && $ticket->stored() && $ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
    }
637 638 639
    if (defined($ticket)) {
	$ticket->SetSlice($slice);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
640 641 642 643 644 645
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
646 647 648
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
649
    }
650 651 652
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
653 654
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
655 656 657
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
658 659 660 661 662 663 664 665
    # Ditto for expired.
    if ($slice->IsExpired()) {
	$slice->UnLock();
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
				    "Slice has expired");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
666

667
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
668
    # For now, there can be only a single toplevel aggregate per slice.
669
    # The existence of an aggregate means the slice is active here. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
670
    #
671
    my $aggregate = GeniAggregate->SliceAggregate($slice);
672 673 674 675 676
    if (!$isupdate) {
	if (defined($aggregate)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Already have an aggregate for slice");
	    goto bad;
677 678
	}
    }
679 680 681 682 683
    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;
    }
684

685
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
686
    # We need this now so we can form a virtual topo.
687
    #
688 689 690 691 692 693 694 695 696 697 698
    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 B. Stoller's avatar
Leigh B. Stoller committed
699 700 701 702
	goto bad;
    }
    my $pid = $slice_experiment->pid();
    my $eid = $slice_experiment->eid();
703 704 705 706 707

    #
    # Mark the experiment locally as coming from the cooked interface.
    # This changes what tmcd returns to the local nodes.
    #
708
    my $generated_by = GeniXML::GetText("generated_by", $rspec);
709 710
    if (defined($generated_by) &&
	$generated_by eq "libvtop") {
711 712 713 714
	$slice_experiment->Update({"geniflags" =>
				       $Experiment::EXPT_GENIFLAGS_EXPT|
				       $Experiment::EXPT_GENIFLAGS_COOKED});
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
715 716 717 718 719 720 721 722 723 724 725 726 727
    
    #
    # 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);
728
    $virtexperiment->multiplex_factor(10);
729

730 731 732 733 734 735 736 737 738 739
    #
    # 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()) {
740
	$virtexperiment->NewTableRow("virt_vtypes",
741 742 743 744
				     {"name"     => $row->{'vtype'},
				      "members"  => $row->{'types'},
				      "weight"   => $row->{'weight'}
				     });
745
    }
746

747 748 749 750 751
    # Need to move this someplace else; the parser adds a bunch.
    $virtexperiment->NewTableRow("virt_agents",
				 {"vnode"      => "*",
				  "vname"      => "ns",
				  "objecttype" => "6"});
752

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    #
    # Look for toplevel address pools
    #
    my $address_pools = GeniXML::GetAddressPools($rspec);
    foreach my $pool (@{ $address_pools }) {
	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",
		      {"pool_id" => $pool->{'client_id'},
		       "count" => $pool->{'count'},
		       "restriction" => $pool->{'type'},
		       "version" => "ipv4" });
    }

770 771 772 773 774 775 776 777 778 779 780 781 782 783
    #
    # 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);
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
784
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
785 786
    # 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
787 788
    # cannot be granted.
    #
789 790 791
    my %namemap  = ();
    my %colomap  = ();
    my %ifacemap = ();
Jonathon Duerig's avatar
Jonathon Duerig committed
792
    my %iface2node = ();
793
    my %vportmap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
794
    my %nodemap  = ();
795
    my %bridgemap= ();
796
    my @nodeids  = ();
797
    my %lannodes = ();
798
    # For stitching, keep track of external nodes and links.
799 800 801
    my %external_nodemap  = ();
    my %external_linkmap  = ();
    my %external_vportmap = ();
802

803 804 805
    # Always do this to avoid buildup.
    $slice_experiment->ClearBackupState();
    
806 807 808 809 810 811 812
    #
    # 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
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
	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;
	}
830 831 832 833 834 835 836
	my $oldrspec;
	if ($v2 && defined($aggregate)) {
	    $oldrspec = $aggregate->GetManifest(0);
	}
	else {
	    $oldrspec = $ticket->rspec();
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
837
	
838
	foreach my $ref (GeniXML::FindNodes("n:node",
839
					    $oldrspec)->get_nodelist()) {
840
	    # Let remote nodes pass through.
841
	    next
842
		if (!GeniXML::IsLocalNode($ref));
843

844 845
	    # Skip lan nodes; they are fake.
	    next
846
		if (GeniXML::IsLanNode($ref));
847

848
	    my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
849
	    my $colocate      = GeniXML::GetColocate($ref);
850
	    my $component_id  = GeniXML::GetNodeId($ref);
851 852
	    my $vnode_id      = GeniXML::GetVnodeId($ref);
	    my $node = GeniUtil::LookupNode($vnode_id);
853 854
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
855
				 "Bad resource $component_id in ticket");
856 857
		goto bad;
	    }
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
	    #
	    # 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;
	    }
873 874 875 876 877
	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
878

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

881 882
    my %nodeexistsmap = ();

883
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
884
	my $component_id  = GeniXML::GetNodeId($ref);
885
	my $vnode_id      = GeniXML::GetVnodeId($ref);
886
	my $manager_id    = GeniXML::GetManagerId($ref);
887
	my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
888 889 890 891
	my $colocate      = GeniXML::GetColocate($ref);
	my $subnode_of    = GeniXML::GetSubnodeOf($ref);
	my $virtualization_type = GeniXML::GetVirtualizationType($ref);
	
892
	my $virtualization_subtype
Jonathon Duerig's avatar
Jonathon Duerig committed
893 894
                          = GeniXML::GetVirtualizationSubtype($ref);
	my $exclusive     = GeniXML::GetExclusive($ref);
895
	my $tarfiles      = GeniXML::GetTarball($ref);
896
	my $pctype;
897
	my ($osname, $osinfo);
898
	my $parent_osname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
899
	my $node;
900 901
	my $isbridge    = 0;
	my $isfirewall  = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
902
	my $xensettings;
903
	my $fwsettings;
904
	
905
	if (exists($nodeexistsmap{lc($node_nickname)})) {
906 907 908 909 910
	    $response =
		GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Duplicate node $node_nickname");
	    goto bad;
	}
911
	$nodeexistsmap{lc($node_nickname)} = 1;
912

913 914 915 916 917
	# 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);
918 919 920 921 922 923 924
	    if (exists($iface2node{$virtual_id})) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Duplicate interface $virtual_id on ".
					 "node $node_nickname");
		goto bad;
	    }
925 926 927
	    $iface2node{$virtual_id} = $node_nickname;
	}

928
	# Let remote nodes pass through.
929 930 931 932
	if (! GeniXML::IsLocalNode($ref)) {
	    $external_nodemap{$node_nickname} = $ref;
	    next;
	}
933

934
	#
935 936 937 938 939
	#
	# 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. 
	#
940
	if (GeniXML::IsLanNode($ref)) {
941 942 943 944
	    $lannodes{$node_nickname} = $ref;
	    next;
	}

945 946 947 948 949 950 951 952 953 954 955 956 957
	#
	# 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}";
	if (length($fullhostname) > 63) {
	    $response = GeniResponse->Create(GENIRESPONSE_TOOBIG, undef,
				     "Hostname > 63 characters: $fullhostname");
	    goto bad;
	}
958 959 960
	#
	# Check for disk_image request. Specified as a URN. 
	#
961
	my $diskref = GeniXML::GetDiskImage($ref);
962 963
	if (defined($diskref)) {
	    my $dname = GeniXML::GetText("name", $diskref);
964
	    my $url   = GeniXML::GetText("url", $diskref);
965

966 967 968 969 970
	    # url is deprecated; name can be anything.
	    if (defined($dname) && $dname =~ /^http/) {
		$url = $dname;
	    }

971 972 973 974 975 976 977 978 979 980