GeniCM.pm.in 196 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 133 134 135 136 137

#
# 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
138
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
139
# Respond to a Resolve request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
140 141 142 143 144 145
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
146 147
    my $type       = lc( $argref->{'type'} );
    my $hrn        = $argref->{'hrn'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
148 149 150 151

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

178
    my $credential = GeniCredential::CheckCredential($cred);
179 180 181
    return $credential
	if (GeniResponse::IsResponse($credential));

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

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

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

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

233
    my $credential = GeniCredential::CheckCredential($credstr);
234 235
    return $credential
	if (GeniResponse::IsResponse($credential));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
236

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

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

257 258 259
    # 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.
260 261 262 263 264 265
    if (defined($available) && ref($available) eq 'Frontier::RPC2::Boolean') {
	$available = $available->value;
    }
    if (defined($compress) && ref($compress) eq 'Frontier::RPC2::Boolean') {
	$compress = $compress->value;
    }
266

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

    # 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) {
282
        if (GeniXML::PolicyExists('allow_externalusers', $credential) == 1) {
283 284 285 286 287 288
        $isExempted = 1;
        last;
      }
    }

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

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

325 326 327 328 329 330
    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
331 332
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $xml);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
333

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

344 345 346 347 348 349 350
    $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");

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
430
#
431
# Update a ticket with a new rspec.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
432
#
433
sub UpdateTicket($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
434 435
{
    my ($argref) = @_;
436 437 438 439 440 441 442 443 444 445

    return GetTicket($argref, 1);
}

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

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

472
    if ($isupdate) {
473
	$ticket = CheckTicket($tickstr, $credential->target_urn());
474 475
	return $ticket
	    if (GeniResponse::IsResponse($ticket));
476
    }
477
    return GetTicketAux($credential,
478
			$rspecstr, $isupdate, $impotent, 0, 1, $ticket);
479
}
480

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

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

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

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    #
    # 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");
    }

567 568
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
569
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
570
				    "Error Parsing rspec XML");
571
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
572

573 574 575 576 577 578
    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
579 580 581 582
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
583
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
584 585 586 587 588 589 590 591 592 593 594 595 596 597
	    # 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
598
    }
599 600 601

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

    #
    # Lock the ticket so it cannot be released.
    #
    if (defined($ticket) && $ticket->stored() && $ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
    }
632 633 634
    if (defined($ticket)) {
	$ticket->SetSlice($slice);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
635 636 637 638 639 640
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
641 642 643
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
644
    }
645 646 647
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
648 649
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
650 651 652
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
653 654 655 656 657 658 659 660
    # 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
661

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

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

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

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

742 743 744 745 746
    # Need to move this someplace else; the parser adds a bunch.
    $virtexperiment->NewTableRow("virt_agents",
				 {"vnode"      => "*",
				  "vname"      => "ns",
				  "objecttype" => "6"});
747

748 749 750 751 752 753 754 755 756 757 758 759 760 761
    #
    # 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
762
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
763 764
    # 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
765 766
    # cannot be granted.
    #
767 768 769
    my %namemap  = ();
    my %colomap  = ();
    my %ifacemap = ();
Jonathon Duerig's avatar
Jonathon Duerig committed
770
    my %iface2node = ();
771
    my %vportmap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
772
    my %nodemap  = ();
773
    my %bridgemap= ();
774
    my @nodeids  = ();
775
    my %lannodes = ();
776
    # For stitching, keep track of external nodes and links.
777 778 779
    my %external_nodemap  = ();
    my %external_linkmap  = ();
    my %external_vportmap = ();
780

781 782 783
    # Always do this to avoid buildup.
    $slice_experiment->ClearBackupState();
    
784 785 786 787 788 789 790
    #
    # 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
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
	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;
	}
808 809 810 811 812 813 814
	my $oldrspec;
	if ($v2 && defined($aggregate)) {
	    $oldrspec = $aggregate->GetManifest(0);
	}
	else {
	    $oldrspec = $ticket->rspec();
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
815
	
816
	foreach my $ref (GeniXML::FindNodes("n:node",
817
					    $oldrspec)->get_nodelist()) {
818
	    # Let remote nodes pass through.
819
	    next
820
		if (!GeniXML::IsLocalNode($ref));
821

822 823
	    # Skip lan nodes; they are fake.
	    next
824
		if (GeniXML::IsLanNode($ref));
825

826
	    my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
827
	    my $colocate      = GeniXML::GetColocate($ref);
828
	    my $component_id  = GeniXML::GetNodeId($ref);
829 830
	    my $vnode_id      = GeniXML::GetVnodeId($ref);
	    my $node = GeniUtil::LookupNode($vnode_id);
831 832
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
833
				 "Bad resource $component_id in ticket");
834 835
		goto bad;
	    }
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
	    #
	    # 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;
	    }
851 852 853 854 855
	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
856

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

859 860
    my %nodeexistsmap = ();

861
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
862
	my $component_id  = GeniXML::GetNodeId($ref);
863
	my $vnode_id      = GeniXML::GetVnodeId($ref);
864
	my $manager_id    = GeniXML::GetManagerId($ref);
865
	my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
866 867 868 869
	my $colocate      = GeniXML::GetColocate($ref);
	my $subnode_of    = GeniXML::GetSubnodeOf($ref);
	my $virtualization_type = GeniXML::GetVirtualizationType($ref);
	
870
	my $virtualization_subtype
Jonathon Duerig's avatar
Jonathon Duerig committed
871 872
                          = GeniXML::GetVirtualizationSubtype($ref);
	my $exclusive     = GeniXML::GetExclusive($ref);
873
	my $tarfiles      = GeniXML::GetTarball($ref);
874
	my $pctype;
875
	my ($osname, $osinfo);
876
	my $parent_osname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
877
	my $node;
878 879
	my $isbridge    = 0;
	my $isfirewall  = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
880
	my $xensettings;
881
	my $fwsettings;
882
	
883
	if (exists($nodeexistsmap{lc($node_nickname)})) {
884 885 886 887 888
	    $response =
		GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Duplicate node $node_nickname");
	    goto bad;
	}
889
	$nodeexistsmap{lc($node_nickname)} = 1;
890

891 892 893 894 895
	# 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);
896 897 898 899 900 901 902
	    if (exists($iface2node{$virtual_id})) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Duplicate interface $virtual_id on ".
					 "node $node_nickname");
		goto bad;
	    }
903 904 905
	    $iface2node{$virtual_id} = $node_nickname;
	}

906
	# Let remote nodes pass through.
907 908 909 910
	if (! GeniXML::IsLocalNode($ref)) {
	    $external_nodemap{$node_nickname} = $ref;
	    next;
	}
911

912
	#
913 914 915 916 917
	#
	# 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. 
	#
918
	if (GeniXML::IsLanNode($ref)) {
919 920 921 922
	    $lannodes{$node_nickname} = $ref;
	    next;
	}

923 924 925 926 927 928 929 930 931 932 933 934 935
	#
	# 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;
	}
936 937 938
	#
	# Check for disk_image request. Specified as a URN. 
	#
939
	my $diskref = GeniXML::GetDiskImage($ref);
940 941
	if (defined($diskref)) {
	    my $dname = GeniXML::GetText("name", $diskref);
942
	    my $url   = GeniXML::GetText("url", $diskref);
943

944 945 946 947 948
	    # url is deprecated; name can be anything.
	    if (defined($dname) && $dname =~ /^http/) {
		$url = $dname;
	    }

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
	    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)) {
964 965 966 967 968 969 970 971 972 973 974 975 976 977
		if (! GeniHRN::IsValid($dname)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
		my ($auth,$type,$id) = GeniHRN::Parse($dname);
		my ($ospid,$os) = ($id =~ m{(.*)//(.*)});
		if ($type ne "image" || !defined($ospid) || !defined($os)){
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
978
		$osinfo = OSinfo->Lookup($ospid, $os);
979
		if (!defined($osinfo)) {
980 981
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
982
					     "Unknown image URN: $dname");
983 984
		    goto bad;
		}
985 986 987 988 989 990
		#
		# The OS must be in the current project, or it must
		# be global (okay, shared).
		#
		if (! ($osinfo->shared() ||
		       $osinfo->pid() eq $slice_experiment->pid())) {
991 992
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
993
				 "Insufficient permission to use $osinfo");
994 995
		    goto bad;
		}
996
		
997 998 999
		#
		# This is only going to be used in raw mode. 
		#
1000
		$osname = "$ospid/$os";
1001 1002 1003
	    }
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1004 1005 1006
	if (defined($virtualization_type)) {
	    if ($virtualization_type eq "emulab-vnode") {
		if (defined($virtualization_subtype)) {
1007 1008
		    $pctype = "pcvm";
		    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1009 1010 1011 1012
		    if ($virtualization_subtype eq "emulab-jail") {
			$osname = "FBSD-JAIL";
		    }
		    elsif ($virtualization_subtype eq "emulab-openvz") {
1013 1014 1015 1016 1017 1018 1019 1020
			# 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";
			    }
			}
1021 1022
			elsif (!defined($osname)) {
			    # Allow for url above.
1023 1024
			    $osname = "OPENVZ-STD";
			}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1025
		    }
1026 1027
		    elsif ($virtualization_subtype eq "emulab-xen" ||
			   $virtualization_subtype eq "default-vm") {
1028 1029 1030 1031 1032
			# Allow caller to set the image to use, but also
			# trick to set the parent. 
			if (defined($osinfo)) {
			    if (! $osinfo->IsSubOS()) {
				$parent_osname = $osname;
1033
				$osname = "UBUNTU12-64-STD";
1034 1035 1036 1037
			    }
			}
			elsif (!defined($osname)) {
			    # Allow for url above.
1038
			    $osname = "UBUNTU12-64-STD";
1039
			}
Leigh B Stoller's avatar
Leigh B Stoller committed
1040 1041 1042 1043 1044 1045
			#
			# Look for the knobs
			#
			if (GeniXML::HasXenSettings($ref)) {
			    $xensettings = GeniXML::GetXenSettings($ref);
			}
1046 1047 1048
			my $ptype = GeniXML::XenPtype($ref);
			$pctype = $ptype
			    if (defined($ptype));
1049
			$virtexperiment->encap_style("vlan");