GeniCMV2.pm.in 85.3 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2008-2013 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.
# 
# }}}
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#
package GeniCMV2;

#
# The server side of the CM interface on remote sites. Also communicates
# with the GMC interface at Geni Central as a client.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use GeniDB;
use GeniResponse;
use GeniTicket;
use GeniCredential;
use GeniCertificate;
49
use GeniComponent;
50 51 52 53
use GeniSlice;
use GeniAggregate;
use GeniSliver;
use GeniUtil;
54
use GeniCM;
55
use GeniHRN;
56
use GeniXML;
57
use GeniStitch;
58 59 60 61 62 63 64 65
use emutil;
use English;
use Data::Dumper;
use XML::Simple;
use Date::Parse;
use POSIX qw(strftime tmpnam);
use Time::Local;
use Compress::Zlib;
66
use File::Temp qw(tempfile);
67
use MIME::Base64;
68
use Errno;
69 70 71 72 73 74 75 76 77

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
78
my $ELABINELAB     = "@ELABINELAB@";
79
my $TBBASE         = "@TBBASE@";
80
my $TBDOCBASE      = "@TBDOCBASE@";
81 82 83 84
my $CREATEEXPT     = "$TB/bin/batchexp";
my $ENDEXPT        = "$TB/bin/endexp";
my $NALLOC	   = "$TB/bin/nalloc";
my $NFREE	   = "$TB/bin/nfree";
85
my $TEVC	   = "$TB/bin/tevc";
86 87 88 89 90 91 92 93 94 95 96 97
my $AVAIL	   = "$TB/sbin/avail";
my $PTOPGEN	   = "$TB/libexec/ptopgen";
my $TBSWAP	   = "$TB/bin/tbswap";
my $SWAPEXP	   = "$TB/bin/swapexp";
my $PLABSLICE	   = "$TB/sbin/plabslicewrapper";
my $NAMEDSETUP     = "$TB/sbin/named_setup";
my $VNODESETUP     = "$TB/sbin/vnode_setup";
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
my $TARFILES_SETUP = "$TB/bin/tarfiles_setup";
my $MAPPER         = "$TB/bin/mapper";
my $VTOPGEN        = "$TB/bin/vtopgen";
my $SNMPIT         = "$TB/bin/snmpit";
98 99
my $CLONEIMAGE     = "$TB/sbin/clone_image";
my $CREATEIMAGE    = "$TB/bin/create_image";
100
my $DELETEIMAGE    = "$TB/sbin/delete_image";
101
my $XMLLINT	   = "/usr/local/bin/xmllint";
102 103
my $PRERENDER      = "$TB/libexec/vis/prerender";
my $EMULAB_PEMFILE = "@prefix@/etc/genicm.pem";
104 105
# Just one of these, at Utah.
my $GENICH_PEMFILE = "@prefix@/etc/genich.pem";
106
my $API_VERSION    = 2;
107 108 109 110 111 112 113 114

#
# 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()
{
115 116
    my @input_rspec_versions = ( "0.1", "0.2", "2", "3", "PG 0.1", "PG 0.2", "PG 2" );
    my @ad_rspec_versions = ( "0.1", "0.2", "2", "3", "PG 0.1", "PG 0.2", "PG 2" );
Gary Wong's avatar
Gary Wong committed
117 118 119
    my $blob = {
	"api" => $API_VERSION,
	"level" => 1,
120
	"input_rspec" => \@input_rspec_versions,
121
	"output_rspec" => "2",
122
	"ad_rspec" => \@ad_rspec_versions
Gary Wong's avatar
Gary Wong committed
123
    };
124
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
125 126 127 128 129 130 131 132
}

#
# Respond to a Resolve request. 
#
sub Resolve($)
{
    my ($argref) = @_;
133 134
    my $credentials = $argref->{'credentials'};
    my $urn         = $argref->{'urn'};
135
    my $admin       = 0;
136
    my $isauth	    = 0;
137

138 139 140 141 142 143
    if (! (defined($credentials) && defined($urn))) {
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
    if (! GeniHRN::IsValid($urn)) {
	return GeniResponse->MalformedArgsResponse("Invalid URN");
    }
144
    my ($credential,$speaksfor) = CheckCredentials($credentials);
145 146 147
    return $credential
	if (GeniResponse::IsResponse($credential));

148 149 150
    my ($object, $type) = LookupURN($urn);
    return $object
	if (GeniResponse::IsResponse($object));
151 152 153 154

    #
    # This is a convenience for testing. If a local user and that
    # user is an admin person, then do whatever it says. This is
155 156
    # easier then trying to do this with credential privs. But,
    # watch for credentials from authorities instead of users.
157
    #
158 159
    my (undef,$callertype,$callerid) = GeniHRN::Parse($credential->owner_urn());
    if ($callertype eq "user") {
160
	my $user = GeniCM::CreateUserFromCertificate($credential);
161 162
	if (!GeniResponse::IsResponse($user) &&
	    $user->IsLocal() && $user->admin()) {
163 164 165
	    $admin = 1;
	}
    }
166 167
    elsif ($callertype eq "authority" &&
	   ($callerid eq "cm" || $callerid eq "sa")) {
168
	$isauth = 1;
169
    }
170 171
    
    if ($type eq "node") {
172
	my $node  = $object;
173 174 175 176 177
	# Not sure about this, but I do know that Resolving a virtnode
	# is not useful right now. 
	if ($node->isvirtnode()) {
	    $node = Node->Lookup($node->phys_nodeid());
	}
178
	my $rspec = GeniCM::GetAdvertisement(0, $node->node_id(), "0.1", undef);
179
	if (! defined($rspec)) {
180
	    print STDERR "Could not get advertisement for $node!\n";
181
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
182
					"Error getting advertisement");
183
	}
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	my $me = GeniAuthority->Lookup($ENV{'MYURN'});
	if (!defined($me)) {
	    print STDERR
		"Could not find local authority object for $ENV{'MYURN'}\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Error getting advertisement");
	}
	my $myurn = GeniHRN::Generate($OURDOMAIN, "node", $node->node_id());
	my $myhrn = "${PGENIDOMAIN}." . $node->node_id();

	#
	# See if the component object exists; if not create it.
	#
	my $component = GeniComponent->Lookup($node->uuid());
	if (!defined($component)) {
	    my $certificate = GeniCertificate->Lookup($node->uuid());
	    if (!defined($certificate)) {
		$certificate =
		    GeniCertificate->Create({'urn'  => $myurn,
					     'hrn'  => $myhrn,
					     'email'=> $TBOPS,
					     'uuid' => $node->uuid(),
					     'url'  => $me->url()});
		if (!defined($certificate)) {
		    print STDERR "Could not generate certificate for $node\n";
		    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					    "Error getting advertisement");
		}
	    }
	    $component = GeniComponent->Create($certificate, $me);
	    if (!defined($component)) {
		print STDERR "Could not create component for $node\n";
		return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					    "Error getting advertisement");
	    }
	}
220
	# Return a blob.
221
	my $blob = { "hrn"          => $myhrn,
222 223
		     "uuid"         => $node->uuid(),
		     "role"	    => $node->role(),
224 225
		     "hostname"     =>
			 GeniUtil::FindHostname($node->node_id()),
226 227
		     "physctrl"     => 
			 Interface->LookupControl($node->phys_nodeid())->IP(),
228 229 230 231
		     "urn"          => $myurn,
		     "rspec"        => $rspec,
		     "url"          => $me->url(),
		     "gid"          => $component->cert(),
232 233 234 235
		   };

	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
236
    if ($type eq "slice") {
237 238
	my $slice = $object;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
239 240 241 242
	#
	# In this implementation, the caller must hold a valid slice
	# credential for the slice being looked up. 
	#
243 244
	if (! ($isauth || $admin ||
	       $slice->urn() eq $credential->target_urn())) {
245 246
	    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
					"No permission to resolve $slice\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
247 248 249 250 251 252
	}
	# Return a blob.
	my $blob = { "urn"          => $urn };

	my $aggregate = GeniAggregate->SliceAggregate($slice);
	if (defined($aggregate)) {
253
	    $blob->{'sliver_urn'} = $aggregate->urn();
254 255 256 257
	    my $manifest = $aggregate->GetManifest(1);
	    if (defined($manifest)) {
		$blob->{'manifest'}   = $manifest;
	    }
258 259 260 261 262 263 264 265 266 267 268
	    # For key bindings.
	    my $slice_experiment = $slice->GetExperiment();
	    if (!defined($slice_experiment)) {
		print STDERR "*** No Experiment for $slice\n";
	    }
	    else {
		my $bindings;
		if ($slice_experiment->NonLocalUsers(\$bindings)) {
		    print STDERR "*** No bindings for $slice_experiment\n";
		}
		elsif (@{ $bindings }) {
269
		    $blob->{'users'} = $bindings;
270 271
		}
	    }
272 273 274
	    $blob->{'public_url'} =
		"$TBDOCBASE/showslicepub.php?publicid=" . $slice->publicid()
		if (defined($slice->publicid()));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
275 276 277
	}
	my $ticket = GeniTicket->SliceTicket($slice);
	if (defined($ticket)) {
278
	    $blob->{'ticket_urn'} = $ticket->urn();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
279 280 281 282
	}
	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
    }
    if ($type eq "sliver") {
283
	my $sliver = $object;
284 285 286
	my $slice  = $sliver->GetSlice();
	return GeniResponse->Create(GENIRESPONSE_ERROR)
	    if (!defined($slice));
287

Leigh B. Stoller's avatar
Leigh B. Stoller committed
288 289 290 291
	#
	# In this implementation, the caller must hold a valid slice
	# or sliver credential for the slice being looked up. 
	#
292
	if (! ($admin || $isauth ||
293
	       $sliver->urn() eq $credential->target_urn() ||
294 295 296 297 298
	       $slice->urn() eq $credential->target_urn())) {
	    print STDERR $sliver->urn() . "\n";
	    print STDERR $slice->urn() . "\n";
	    print STDERR $credential->target_urn() . "\n";
	    print STDERR $ENV{'MYURN'} . "\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
299 300
	    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN);
	}
301 302
	my $manifest = $sliver->GetManifest(1);
	if (!defined($manifest)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
303 304 305 306 307 308
	    return GeniResponse->Create(GENIRESPONSE_ERROR);
	}
	# Return a blob.
	my $blob = { "urn"          => $urn,
		     "manifest"     => $manifest,
		 };
309 310 311 312
	$blob->{'public_url'} =
	    "$TBDOCBASE/showslicepub.php?publicid=" . $slice->publicid()
	    if (defined($slice->publicid()));
	
313 314 315 316 317 318 319 320 321 322 323
	# For key bindings.
	my $slice_experiment = $slice->GetExperiment();
	if (!defined($slice_experiment)) {
	    print STDERR "*** No Experiment for $slice\n";
	}
	else {
	    my $bindings;
	    if ($slice_experiment->NonLocalUsers(\$bindings)) {
		print STDERR "*** No bindings for $slice_experiment\n";
	    }
	    elsif (@{ $bindings }) {
324
		$blob->{'users'} = $bindings;
325 326
	    }
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
327 328 329
	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
    }
    if ($type eq "ticket") {
330 331
	my $ticket = $object;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
332 333 334 335
	#
	# In this implementation, the caller must hold a valid slice
	# or sliver credential to get the ticket.
	#
336
	my $slice = GeniSlice->Lookup($ticket->slice_urn());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
337 338 339 340
	if (!defined($slice)) {
	    print STDERR "Could not find slice for $ticket\n";
	    return GeniResponse->Create(GENIRESPONSE_ERROR);
	}
341
	if (! ($admin || $slice->urn() eq $credential->target_urn())) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
342 343 344 345 346
	    #
	    # See if its the sliver credential. 
	    #
	    my $aggregate = GeniAggregate->SliceAggregate($slice);
	    if (!defined($aggregate) ||
347
		$aggregate->urn() ne $credential->target_urn()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
348 349 350 351 352
		return GeniResponse->Create(GENIRESPONSE_FORBIDDEN());
	    }
	}
	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $ticket->asString());
    }
353 354
    return GeniResponse->Create(GENIRESPONSE_UNSUPPORTED, undef,
				"Cannot resolve $type at this authority");
355 356 357 358 359 360 361 362
}

#
# Discover resources on this component, returning a resource availablity spec
#
sub DiscoverResources($)
{
    my ($argref) = @_;
363 364 365
    my $credentials = $argref->{'credentials'};
    my $available   = $argref->{'available'} || 0;
    my $compress    = $argref->{'compress'} || 0;
366
    my $version     = $argref->{'rspec_version'} || undef;
367 368 369 370

    if (! (defined($credentials))) {
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
371
    my ($credential,$speaksfor,@morecreds) = CheckCredentials($credentials);
372 373
    return $credential
	if (GeniResponse::IsResponse($credential));
374

375
    return GeniCM::DiscoverResourcesAux($available, $compress,
376
        $version, [$credential, @morecreds]);
377 378 379 380 381 382 383 384
}

#
# Create a Sliver.
#
sub CreateSliver($)
{
    my ($argref) = @_;
385 386 387 388 389
    my $slice_urn    = $argref->{'slice_urn'};
    my $rspecstr     = $argref->{'rspec'};
    my $credentials  = $argref->{'credentials'};
    my $keys         = $argref->{'keys'};
    my $impotent     = $argref->{'impotent'} || 0;
390 391
    require Node;
    require Experiment;
392 393
    require libtestbed;
    require libaudit;
394

395
    # For now, I am not worrying about the slice_urn argument.
396 397
    if (! (defined($credentials) &&
	   defined($slice_urn) && defined($rspecstr))) {
398 399
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
400 401 402 403 404 405
    if (! ($rspecstr =~ /^[\040-\176\012\015\011]+$/)) {
	return GeniResponse->MalformedArgsResponse("Bad characters in rspec");
    }
    if (! GeniHRN::IsValid($slice_urn)) {
	return GeniResponse->MalformedArgsResponse("Bad characters in URN");
    }
406
    my ($credential,$speaksfor) = CheckCredentials($credentials);
407 408
    return $credential
	if (GeniResponse::IsResponse($credential));
409

410 411
    main::AddLogfileMetaData("slice_urn", $slice_urn);
    
412 413 414 415 416 417 418
    #
    # In this implementation, the user must provide a slice credential,
    # so we ignore the slice_urn. For CreateSliver(), the slice must not
    # be instantiated.
    #
    my ($slice,$aggregate) = Credential2SliceAggregate($credential);
    if (defined($slice)) {
419 420 421
	return $slice
	    if (GeniResponse::IsResponse($slice));

422 423 424 425
	if ($slice_urn ne $slice->urn()) {
	    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
					"Credential does not match the URN");
	}
426
	main::AddLogfileMetaDataFromSlice($slice);
427
	
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
	#
	# Watch for a placeholder slice and update it.
	#
	if ($slice->isplaceholder()) {
	    if ($slice->Lock() != 0) {
		return GeniResponse->BusyResponse();
	    }
	    #
	    # Confirm that the slice certificate is the same.
	    #
	    if ($slice->cert() ne $credential->target_cert()->cert()) {
		$slice->UnLock();
		return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
					    "Slice certificate mismatch");
	    }
	    my $user =
444
		GeniCM::CreateUserFromCertificate($credential);
445
	    if (GeniResponse::IsResponse($user)) {	    
446
		$slice->UnLock();
447
		return $user;
448 449 450 451 452 453 454 455
	    }
	    if ($slice->ConvertPlaceholder($user) != 0) {
		$slice->UnLock();
		return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					    "Could not convert placeholder");
	    }
	    $slice->UnLock();
	}
456 457 458 459 460
	if (defined($aggregate)) {
	    return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
					"Must delete existing slice first");
	}
    }
461 462
    my $rspec = GeniCM::GetTicketAux($credential, $rspecstr,
				     0, $impotent, 1, 0, undef, $speaksfor);
463 464 465
    return $rspec
	if (GeniResponse::IsResponse($rspec));

Leigh B Stoller's avatar
Leigh B Stoller committed
466
    $slice = GeniSlice->Lookup($credential->target_urn());
467 468 469 470
    if (!defined($slice)) {
	print STDERR "CreateSliver: Could not find slice for $credential\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,"Internal Error");
    }
471
    main::AddLogfileMetaDataFromSlice($slice);
472

473 474 475 476
    # Make sure that the next phase sees all changes.
    Experiment->FlushAll();
    Node->FlushAll();

477 478
    my $response = GeniCM::SliverWorkAux($credential, $rspec,
					 $keys, 0, $impotent, 1, 0, $speaksfor);
479

480 481 482 483 484 485 486
    if (GeniResponse::IsError($response)) {
	#
	# We have to make sure there is nothing left over since there
	# is no actual ticket, so the resources will not get cleaned
	# up by the daemon. This is mostly cause I am reaching into
	# the V1 code, and its messy.
	#
487
	$slice = GeniSlice->Lookup($credential->target_urn());
488
	if (defined($slice)) {
489 490 491 492 493
	    if ($slice->Lock() != 0) {
		print STDERR
		    "CreateSliver: Could not lock $slice before delete\n";
		return $response;
	    }
494 495
	    GeniCM::CleanupDeadSlice($slice, 1);
	}
496
	return $response;
497
    }
498
    my ($sliver_credential, $sliver_manifest) = @{ $response->{'value'} };
499

500 501 502
    #
    # Leave the slice intact on error, so we can go look at it. 
    #
503
    if ($slice->WaitForLock(30) != 0) {
504 505 506 507
	print STDERR "CreateSliver: Could not lock $slice before start\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Internal Error");
    }
508
    $aggregate = GeniAggregate->SliceAggregate($slice);
509 510 511 512 513
    if (!defined($aggregate)) {
	print STDERR "CreateSliver: Could not find aggregate for $slice\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Internal Error");
    }
514

515 516
    #
    # At this point we want to return and let the startsliver proceed
517
    # in the background. Parent never returns, just the child.
518
    #
519
    my $mypid = main::WrapperFork();
520 521 522 523
    if ($mypid) {
	return GeniResponse->Create(GENIRESPONSE_SUCCESS,
				    [$sliver_credential, $sliver_manifest]);
    }
524

525 526 527 528
    # Make sure that the next phase sees all changes.
    Experiment->FlushAll();
    Node->FlushAll();

529 530 531 532 533 534 535
    #
    # The callee might also do a wrapper fork, so remember our PID
    # to make sure we unlock properly in only the parent side of the
    # fork. Child runs with slice unlocked for now. 
    #
    $mypid = $PID;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
536
    if ($aggregate->Start($API_VERSION, 0) != 0) {
537 538 539 540 541 542 543
	if ($PID == $mypid) {
	    $slice->UnLock();
	    print STDERR "Could not start sliver.\n";
	}
	else {
	    print STDERR "Error waiting for nodes.\n";
	}
544
	return -1;
545
    }
546 547 548
    if ($PID == $mypid) {
	$slice->UnLock();
    }
549
    return 0;
550 551 552 553 554 555
}

#
# Delete a Sliver.
#
sub DeleteSliver($)
556 557 558 559 560 561 562 563 564 565 566 567
{
    my ($argref) = @_;
    my $sliver_urn   = $argref->{'sliver_urn'};
    my $credentials  = $argref->{'credentials'};
    my $impotent     = $argref->{'impotent'} || 0;

    if (! (defined($credentials) && defined($sliver_urn))) {
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
    if (! GeniHRN::IsValid($sliver_urn)) {
	return GeniResponse->MalformedArgsResponse("Bad characters in URN");
    }
568
    my ($credential,$speaksfor) = CheckCredentials($credentials);
569 570 571 572 573 574 575 576
    return $credential
	if (GeniResponse::IsResponse($credential));

    #
    # In this implementation, the user must provide a slice or sliver
    # credential
    #
    my ($slice, $aggregate) = Credential2SliceAggregate($credential);
577 578 579
    return $slice
	if (defined($slice) && GeniResponse::IsResponse($slice));
    
580 581 582 583 584 585 586 587 588
    if (! (defined($slice) && defined($aggregate))) {
	return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED, undef,
				    "Sliver does not exist");
    }
    if ($sliver_urn ne $aggregate->urn()) {
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
				    "Credential does not match the URN");
    }

589 590 591 592 593 594 595 596
    # If a monitor process is running, we are "busy".
    if ($slice->monitor_pid()) {
	return GeniResponse->MonitorResponse();
    }
    
    main::AddLogfileMetaData("sliver_urn", $sliver_urn);
    main::AddLogfileMetaDataFromSlice($slice);
    
597 598 599 600 601
    #
    # We need this below to sign the ticket.
    #
    my $authority = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
    if (!defined($authority)) {
602
	print STDERR " Could not load $EMULAB_PEMFILE\n";
603 604 605 606 607 608
	return GeniResponse->Create(GENIRESPONSE_ERROR);
	
    }
    #
    # We need the user to sign the new ticket to. 
    #
609
    my $user = GeniCM::CreateUserFromCertificate($credential);
610 611
    return $user
	if (GeniResponse::IsResponse($user));
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    
    my $response = GeniCM::DeleteSliverAux($credential, $impotent, 1);
    return $response
	if (GeniResponse::IsResponse($response));

    #
    # In the v2 API, return a new ticket for the resources
    # (which were not released). As with all tickets, it will
    # expire very quickly. 
    #
    #
    # Create a new ticket from the manifest.
    #
    my $manifest = $aggregate->GetManifest(0);
    if (!defined($manifest)) {
	print STDERR "No manifest found for $aggregate\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
631 632
    my $ticket = GeniTicket->Create($authority, $user,
				    GeniXML::Serialize($manifest));
633 634 635 636 637
    if (!defined($ticket)) {
	print STDERR "Could not create new ticket for $slice\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
638
    $ticket->SetSlice($slice);
639 640
    $ticket->SetSpeaksFor($speaksfor)
	if (defined($speaksfor));
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    
    if ($ticket->Sign()) {
	$ticket->Delete();
	print STDERR "Could not sign new ticket $ticket\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
    if ($ticket->Store()) {
	$ticket->Delete();
	print STDERR "Could not store new ticket $ticket\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
    my $slice_uuid = $slice->uuid();
    DBQueryWarn("delete from geni_manifests ".
		"where slice_uuid='$slice_uuid'");
    $slice->UnLock();
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $ticket->asString());

  bad:
    if (GeniCM::CleanupDeadSlice($slice) != 0) {
	print STDERR "Could not cleanup slice\n";
    }
    return $response;
}

#
# Delete a Slice
#
sub DeleteSlice($)
671 672
{
    my ($argref) = @_;
673 674 675 676
    my $slice_urn    = $argref->{'slice_urn'};
    my $credentials  = $argref->{'credentials'};
    my $impotent     = $argref->{'impotent'} || 0;

677
    if (! (defined($credentials) && defined($slice_urn))) {
678 679
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
680 681 682
    if (! GeniHRN::IsValid($slice_urn)) {
	return GeniResponse->MalformedArgsResponse("Bad characters in URN");
    }
683
    my ($credential,$speaksfor) = CheckCredentials($credentials);
684 685
    return $credential
	if (GeniResponse::IsResponse($credential));
686

687 688 689 690
    #
    # In this implementation, the user must provide a slice credential.
    #
    my ($slice, $aggregate) = Credential2SliceAggregate($credential);
691 692 693
    return $slice
	if (defined($slice) && GeniResponse::IsResponse($slice));

694 695 696 697
    if (! defined($slice)) {
	return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED, undef,
				    "No such slice here");
    }
698
    main::AddLogfileMetaDataFromSlice($slice);
699
    
700 701 702 703 704 705 706
    if ($slice_urn ne $slice->urn()) {
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
				    "Credential does not match the URN");
    }
    if ($slice->Lock() != 0) {
	return GeniResponse->BusyResponse();
    }
707 708 709 710 711 712 713 714 715 716 717 718 719 720

    #
    # If a monitor process is running, then cancel it so that
    # we do not leave it behind on a slice/experiment that is
    # now gone.
    #
    if ($slice->monitor_pid()) {
	my $response = GeniCM::KillMonitor($slice);
	if (GeniResponse::IsResponse($response)) {
	    $slice->UnLock();
	    return $response;
	}
    }
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
721
    if (GeniCM::CleanupDeadSlice($slice, 1) != 0) {
722 723 724
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not cleanup slice");
    }
725
  done:
726
    return GeniResponse->Create(GENIRESPONSE_SUCCESS);
727 728 729 730 731 732 733 734
}

#
# Get a Sliver (credential)
#
sub GetSliver($)
{
    my ($argref) = @_;
735 736
    my $slice_urn    = $argref->{'slice_urn'};
    my $credentials  = $argref->{'credentials'};
737

738
    if (! (defined($credentials) && defined($slice_urn))) {
739 740
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
741 742 743
    if (! GeniHRN::IsValid($slice_urn)) {
	return GeniResponse->MalformedArgsResponse("Bad characters in URN");
    }
744
    my ($credential,$speaksfor) = CheckCredentials($credentials);
745 746 747
    return $credential
	if (GeniResponse::IsResponse($credential));

748 749 750 751
    #
    # In this implementation, the user must provide a slice credential.
    #
    my ($slice, $aggregate) = Credential2SliceAggregate($credential);
752 753 754
    return $slice
	if (defined($slice) && GeniResponse::IsResponse($slice));

755
    if (! (defined($slice) && defined($aggregate))) {
756
	return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED, undef,
757 758 759 760 761 762
				    "No slice or aggregate here");
    }
    if ($slice_urn ne $slice->urn()) {
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
				    "Credential does not match the URN");
    }
763
    return GeniCM::GetSliverAux($credential);
764 765 766
}

#
767
# Start a sliver (not sure what this means yet, so reboot for now).
768
#
769
sub StartSliver($)
770 771
{
    my ($argref) = @_;
772
    my $slice_urn    = $argref->{'slice_urn'};
773
    my $sliver_urns  = $argref->{'sliver_urns'} || $argref->{'component_urns'};
774
    my $credentials  = $argref->{'credentials'};
775
    my $manifest     = $argref->{'manifest'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
776
    
777 778
    return SliverAction("start",
			$slice_urn, $sliver_urns, $credentials, $manifest);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
779 780 781 782 783 784
}

sub StopSliver($)
{
    my ($argref) = @_;
    my $slice_urn    = $argref->{'slice_urn'};
785
    my $sliver_urns  = $argref->{'sliver_urns'} || $argref->{'component_urns'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
786 787
    my $credentials  = $argref->{'credentials'};

788 789
    return SliverAction("stop",
			$slice_urn, $sliver_urns, $credentials, undef);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
790 791 792 793 794 795
}

sub RestartSliver($)
{
    my ($argref) = @_;
    my $slice_urn    = $argref->{'slice_urn'};
796
    my $sliver_urns  = $argref->{'sliver_urns'} || $argref->{'component_urns'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
797
    my $credentials  = $argref->{'credentials'};
798
    my $manifest     = $argref->{'manifest'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
799

800 801
    return SliverAction("restart",
			$slice_urn, $sliver_urns, $credentials, $manifest);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
802
}
803

804
sub SliverAction($$$$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
805
{
806
    my ($action, $slice_urn, $sliver_urns, $credentials, $manifest) = @_;
807
    my $response;
808
    my $isasync = 0;
809

810 811
    if (! (defined($credentials) &&
	   (defined($slice_urn) || defined($sliver_urns)))) {
812 813
	return GeniResponse->MalformedArgsResponse("Missing arguments");
    }
814
    my ($credential,$speaksfor) = CheckCredentials($credentials);
815 816 817 818 819 820 821 822
    return $credential
	if (GeniResponse::IsResponse($credential));

    $credential->HasPrivilege( "pi" ) or
	$credential->HasPrivilege( "info" ) or
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Insufficient privilege");

823 824 825 826 827 828 829 830 831
    if (defined($manifest)) {
	$manifest = GeniXML::Parse($manifest);
	if (!defined($manifest)) {
	    print STDERR "Error reading manifest\n";
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Bad manifest");
	}
    }
    
832 833 834
    #
    # For now, only allow top level aggregate or the slice
    #
835
    my ($slice, $aggregate) = Credential2SliceAggregate($credential);
836 837
    return $slice
	if (defined($slice) && GeniResponse::IsResponse($slice));
Srikanth's avatar
Srikanth committed
838

839 840 841 842 843
    if ( (!defined($slice)) && 
          ($credential->target_urn() =~ /\+authority\+cm$/)) {
          # administrative credentials are presented.
          my $cm_urn = GeniHRN::Generate($OURDOMAIN, "authority", "cm");
          if ($cm_urn != $credential->target_urn()) {
Srikanth's avatar
Srikanth committed
844
            return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
845 846 847 848
                      "Credential target does not match CM URN");
          }

      if (!defined($slice_urn)) {
Srikanth's avatar
Srikanth committed
849 850
          return GeniResponse->MalformedArgsResponse("Missing arguments");
      }       
851 852 853 854 855 856 857 858
      $slice = GeniSlice->Lookup($slice_urn);
      return GeniResponse->Create(GENIRESPONSE_ERROR, undef, 
                "No Slice with urn $slice_urn here")
          if (!defined($slice));
      $aggregate = GeniAggregate->SliceAggregate($slice);
      return GeniResponse->Create(GENIRESPONSE_ERROR, undef, 
                      "No Aggregate here")
          if (!defined($aggregate));
Srikanth's avatar
Srikanth committed
859
    } 
860

861 862 863 864
    if (! (defined($slice) && defined($aggregate))) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "No slice or aggregate here");
    }
865 866 867 868 869 870 871
    main::AddLogfileMetaDataFromSlice($slice);

    # If a monitor process is running, we are "busy".
    if ($slice->monitor_pid()) {
	return GeniResponse->MonitorResponse();
    }
    
872 873
    if (defined($slice_urn)) {
	if (! GeniHRN::IsValid($slice_urn)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
874 875
	    return
		GeniResponse->MalformedArgsResponse("Bad characters in URN");
876
	}
877 878 879
	if ($slice_urn ne $slice->urn()) {
	    return GeniResponse->Create(GENIRESPONSE_FORBIDDEN(), undef,
					"Credential does not match the URN");
880
	}
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
    }
    if ($slice->Lock() != 0) {
	return GeniResponse->BusyResponse();
    }
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
    if ($aggregate->ComputeState()) {
	$slice->UnLock();
	print STDERR "Could not determine current state\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
    my $CheckState = sub {
	my ($object, $action) = @_;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
899
	if ($action eq "start") {
900 901
	    if ($object->state() ne "stopped" && $object->state() ne "new"
		&& $object->state() ne "mixed") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
902 903 904 905 906
		return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
					    "Sliver is not stopped (yet)");
	    }
	}
	elsif ($action eq "stop") {
907
	    if ($object->state() ne "started" && $object->state() ne "mixed") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
908 909 910 911 912
		return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
					    "Sliver is not started (yet)");
	    }
	}
	elsif ($action eq "restart") {
913
	    if ($object->state() ne "started" && $object->state() ne "mixed") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
914 915 916
		return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
					    "Sliver is not started (yet)");
	    }
917 918 919 920 921 922
	}
	return 0;
    };
    my $PerformAction = sub {
	my ($object, $action) = @_;

923 924
	my $exitval = 0;

925
	if ($action eq "start") {
926
	    $exitval = $object->Start($API_VERSION, 0);
927
	}
928
	elsif ($action eq "stop") {
929
	    $exitval = $object->Stop($API_VERSION);
930 931
	}
	elsif ($action eq "restart") {
932
	    $exitval = $object->Start($API_VERSION, 1);
933
	}
934 935 936 937
	return GeniResponse->Create(GENIRESPONSE_ERROR, 
				    "Could not $action sliver")
	    if ($exitval);
	
938 939 940
	return 0;
    };

941 942 943 944 945 946 947 948 949 950 951
    my $user = GeniCM::CreateUserFromCertificate($credential);
    return $user
	if (GeniResponse::IsResponse($user));

    my $realuser = GeniCM::FlipToUser($slice, $user);
    if (! (defined($realuser) && $realuser)) {
	print STDERR "Error flipping to real user\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "FlipToUser Error");
    }

952 953 954 955 956
    if (defined($slice_urn)) {
	$response = &$CheckState($aggregate, $action);
	goto bad
	    if (GeniResponse::IsResponse($response));
	    
957 958 959
	if ($action eq "start" || $action eq "restart") {
	    if (defined($manifest) &&
		$aggregate->ProcessManifest($manifest)) {
960 961 962 963 964
		$response = GeniResponse->Create(GENIRESPONSE_ERROR,
						 undef,
						 "Error processing manifest");
		goto bad;
	    }
965 966 967 968
	    #
	    # At this point we want to return and let the startsliver proceed
	    # in the background
	    #
969
	    my $mypid = main::WrapperFork();
970 971 972
	    if ($mypid) {
		return GeniResponse->Create(GENIRESPONSE_SUCCESS);
	    }
973 974
	    # Remember our pid in case callee wrapper forks again.
	    $isasync = $PID;
975
	}
976 977 978 979
	$response = &$PerformAction($aggregate, $action);
	goto bad
	    if (GeniResponse::IsResponse($response));

980 981 982
	if (!$isasync || $isasync == $PID) {
	    $slice->UnLock();
	}
983 984
	return ($isasync ? GENIRESPONSE_SUCCESS :
		GeniResponse->Create(GENIRESPONSE_SUCCESS));
985
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
986
    else {
987
	my @slivers = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
988

989 990 991 992 993
	#
	# Sanity check all arguments before doing anything.
	#
	foreach my $urn (@{ $sliver_urns }) {
	    my $sliver = GeniSliver->Lookup($urn);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
994 995 996 997 998 999
	    if (!defined($sliver)) {
		$response = GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
						 undef,
						 "Nothing here by that name");
		goto bad;
	    }
1000 1001 1002 1003 1004 1005 1006 1007
	    
	    $response = &$CheckState($sliver, $action);
	    goto bad
		if (GeniResponse::IsResponse($response));

	    push(@slivers, $sliver);
	}
	foreach my $sliver (@sli