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

#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

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

use GeniDB;
Leigh Stoller's avatar
Leigh Stoller committed
41
use GeniComponent;
Leigh Stoller's avatar
Leigh Stoller committed
42
use GeniSlice;
Leigh Stoller's avatar
Leigh Stoller committed
43
use GeniCredential;
44
use GeniCertificate;
Leigh Stoller's avatar
Leigh Stoller committed
45
use GeniAggregate;
46
use GeniUsage;
47
use GeniHRN;
48
use GeniXML;
49
use GeniEvent;
50
use emutil;
51
use Node;
Leigh Stoller's avatar
Leigh Stoller committed
52
use English;
Leigh Stoller's avatar
Leigh Stoller committed
53
use XML::Simple;
Leigh Stoller's avatar
Leigh Stoller committed
54 55
use Data::Dumper;
use File::Temp qw(tempfile);
Leigh Stoller's avatar
Leigh Stoller committed
56
use overload ('""' => 'Stringify');
Leigh Stoller's avatar
Leigh Stoller committed
57 58 59 60 61 62 63 64

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
65
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh Stoller's avatar
Leigh Stoller committed
66
my $SIGNCRED	   = "$TB/sbin/signgenicred";
Leigh Stoller's avatar
Leigh Stoller committed
67 68 69
my $AVAIL	   = "$TB/sbin/avail";
my $NALLOC	   = "$TB/bin/nalloc";
my $NFREE	   = "$TB/bin/nfree";
Leigh Stoller's avatar
Leigh Stoller committed
70
my $NODEREBOOT	   = "$TB/bin/node_reboot";
71
my $NAMEDSETUP     = "$TB/sbin/named_setup";
Leigh Stoller's avatar
Leigh Stoller committed
72 73
my $PLABNODE       = "$TB/sbin/plabnodewrapper";
my $VNODESETUP     = "$TB/sbin/vnode_setup";
74
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
75
my $POWER          = "$TB/bin/power";
76
my $OSLOAD         = "$TB/bin/os_load";
Leigh Stoller's avatar
Leigh Stoller committed
77 78 79

# Cache of instances to avoid regenerating them.
my %slivers      = ();
80
BEGIN { use GeniUtil; GeniUtil::AddCache(\%slivers); }
Leigh Stoller's avatar
Leigh Stoller committed
81 82

#
83
# Lookup by URN, idx, or uuid.
Leigh Stoller's avatar
Leigh Stoller committed
84 85 86 87 88
#
sub Lookup($$)
{
    my ($class, $token) = @_;
    my $query_result;
Leigh Stoller's avatar
Leigh Stoller committed
89
    my $idx;
Leigh Stoller's avatar
Leigh Stoller committed
90

91 92 93
    if (GeniHRN::IsValid($token)) {
	my ($authority, $type, $id) = GeniHRN::Parse($token);
	return undef if $type ne "sliver";
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

	if( GeniHRN::Authoritative($token, "@OURDOMAIN@") ) {
	    # Very simple: we put the index of our own slivers right
	    # in the name.
	    $idx = $id;
	} else {
	    # Look up the slivers's certificate.
	    $token = GeniHRN::Normalise( $token );
	    $query_result = DBQueryWarn(
		"SELECT geni_slivers.idx FROM geni_slivers, " .
		"geni_certificates WHERE geni_slivers.uuid = " .
		"geni_certificates.uuid AND " .
		"geni_certificates.urn='$token';" );

	    return undef if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
	}
112 113
    }
    elsif ($token =~ /^\d+$/) {
Leigh Stoller's avatar
Leigh Stoller committed
114
	$idx = $token;
Leigh Stoller's avatar
Leigh Stoller committed
115 116 117
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$query_result =
Leigh Stoller's avatar
Leigh Stoller committed
118
	    DBQueryWarn("select idx from geni_slivers ".
Leigh Stoller's avatar
Leigh Stoller committed
119
			"where uuid='$token'");
Leigh Stoller's avatar
Leigh Stoller committed
120 121 122 123
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
Leigh Stoller's avatar
Leigh Stoller committed
124 125 126 127
    }
    else {
	return undef;
    }
Leigh Stoller's avatar
Leigh Stoller committed
128 129 130 131 132 133 134 135

    # Look in cache first
    return $slivers{"$idx"}
        if (exists($slivers{"$idx"}));

    $query_result = DBQueryWarn("select * from geni_slivers ".
				"where idx='$idx'");

Leigh Stoller's avatar
Leigh Stoller committed
136 137 138
    return undef
	if (!$query_result || !$query_result->numrows);

139 140 141 142 143 144
    my $self               = {};
    $self->{'SLIVER'}      = $query_result->fetchrow_hashref();
    $self->{'SLICE'}       = undef;	# server
    $self->{'AGGREGATE'}   = undef;	# server
    $self->{'RSPEC'}       = undef;	# server
    $self->{'CERTIFICATE'} = undef;
Leigh Stoller's avatar
Leigh Stoller committed
145

146 147 148 149
    #
    # Grab the certificate, since we will probably want it.
    #
    my $uuid = $self->{'SLIVER'}->{'uuid'};
150
    if (0) {
151 152 153 154 155 156
    my $certificate = GeniCertificate->Lookup($uuid);
    if (!defined($certificate)) {
	print STDERR "Could not find certificate for sliver $idx ($uuid)\n";
	return undef;
    }
    $self->{'CERTIFICATE'} = $certificate;
157
    }
158 159 160 161

    # Bless into sub package if called for.
    my $resource_type = $self->{'SLIVER'}->{'resource_type'};
    if (defined($resource_type) && $resource_type ne "") {
162
	bless($self, $class . "::" . $resource_type);
163 164 165 166
    }
    else {
	bless($self, $class);
    }
Leigh Stoller's avatar
Leigh Stoller committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    
    # Add to cache. 
    $slivers{$self->{'SLIVER'}->{'idx'}} = $self;
    
    return $self;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uuid = $self->uuid();
    my $idx  = $self->idx();

    return "[GeniSliver: $uuid, IDX: $idx]";
}

187 188 189 190 191 192 193 194 195 196
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

    delete($slivers{$self->idx()});
}

Leigh Stoller's avatar
Leigh Stoller committed
197
#
Leigh Stoller's avatar
Leigh Stoller committed
198
# Create a sliver record in the DB. On the client side we save the credential
Leigh Stoller's avatar
Leigh Stoller committed
199
# that allows control of it, for later operations.
Leigh Stoller's avatar
Leigh Stoller committed
200
#
201
sub Create($$$$$$$$)
Leigh Stoller's avatar
Leigh Stoller committed
202
{
203
    my ($class, $slice, $owner, 
204
	$resource_uuid, $resource_type, $resource_id,
205
	$hrn, $nickname, $rspec) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
206 207
    my @insert_data = ();

208 209 210 211 212 213 214 215 216 217 218 219
    my $urn;
    # Get sliver id from the ticket if available.
    if (defined($rspec)) {
	$urn = GeniXML::GetSliverId($rspec);
    }
    # Otherwise, generate a fresh one.
    if (! defined($urn)) {
	# Every sliver gets a new unique index.
	my $sliver_idx = TBGetUniqueIndex('next_sliver', 1);
	$urn = GeniHRN::Generate("@OURDOMAIN@", "sliver", $sliver_idx);
    }
    my (undef, undef, $idx) = GeniHRN::Parse($urn);
220

221 222
    # Sanity check.
    my $certificate = GeniCertificate->Lookup($urn);
223
    if (0) {
224 225 226 227
    if (defined($certificate)) {
	print STDERR "GeniSliver::Create: ".
	    "Already have a certificate for $hrn/$urn\n";
	return undef;
Leigh Stoller's avatar
Leigh Stoller committed
228
    }
229 230 231
    $certificate = GeniCertificate->Create({'urn'  => $urn,
					    'hrn'  => $hrn,
					    'email'=> $TBOPS});
232 233
    if (!defined($certificate)) {
	print STDERR "GeniSliver::Create: ".
234
	    "Could not generate new certificate for $hrn/$urn\n";
235
	return undef;
Leigh Stoller's avatar
Leigh Stoller committed
236
    }
237
    }
Leigh Stoller's avatar
Leigh Stoller committed
238
    my $slice_uuid     = $slice->uuid();
239
    my $owner_uuid     = $owner->uuid();
240 241
    my $sliver_uuid    = (defined($certificate) ?
			  $certificate : GeniUtil::NewUUID());
Leigh Stoller's avatar
Leigh Stoller committed
242 243 244 245

    # Now tack on other stuff we need.
    push(@insert_data, "created=now()");
    push(@insert_data, "idx='$idx'");
246 247 248
    push(@insert_data, "hrn=" . DBQuoteSpecial($hrn));
    push(@insert_data, "nickname=" . DBQuoteSpecial($nickname))
	if (defined($nickname));
249
    push(@insert_data, "uuid='$sliver_uuid'");
250 251
    push(@insert_data, "resource_uuid='$resource_uuid'");
    push(@insert_data, "resource_type='$resource_type'");
252
    push(@insert_data, "resource_id='$resource_id'");
Leigh Stoller's avatar
Leigh Stoller committed
253 254
    push(@insert_data, "creator_uuid='$owner_uuid'");
    push(@insert_data, "slice_uuid='$slice_uuid'");
255
    # Start out new slivers, as new.
256 257
    push(@insert_data, "state='new',".
	 "status_state_timestamp=unix_timestamp(now())");
Leigh Stoller's avatar
Leigh Stoller committed
258

Leigh Stoller's avatar
Leigh Stoller committed
259
    if (defined($rspec)) {
260
	my $rspec_string = GeniXML::Serialize($rspec);
Leigh Stoller's avatar
Leigh Stoller committed
261 262 263 264 265
	my $safe_rspec   = DBQuoteSpecial($rspec_string);

	push(@insert_data, "rspec_string=$safe_rspec");
    }

Leigh Stoller's avatar
Leigh Stoller committed
266
    # Insert into DB.
267 268
    if (!DBQueryWarn("insert into geni_slivers set " .
		     join(",", @insert_data))) {
269 270
	$certificate->Delete()
	    if (defined($certificate));
Leigh Stoller's avatar
Leigh Stoller committed
271 272 273
	return undef;
    }

Leigh Stoller's avatar
Leigh Stoller committed
274 275 276
    my $sliver = GeniSliver->Lookup($idx);
    return undef
	if (!defined($sliver));
277

278 279 280 281 282
    # This is lazy, but since we have it, keep it. 
    $sliver->{'RSPEC'}     = $rspec;
    $sliver->{'AGGREGATE'} = undef;
    $sliver->{'SLICE'}     = undef;

283 284 285 286
    if (GeniUsage->NewSliver($sliver, $slice, $owner)) {
	print STDERR
	    "GeniSliver::Create: GeniUsage->NewSliver($sliver) failed\n";
    }
Leigh Stoller's avatar
Leigh Stoller committed
287 288

    return $sliver;
Leigh Stoller's avatar
Leigh Stoller committed
289 290 291 292 293
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'SLIVER'}->{$_[1]}); }
sub idx($)		{ return field($_[0], "idx"); }
sub uuid($)		{ return field($_[0], "uuid"); }
294 295
sub hrn($)		{ return field($_[0], "hrn"); }
sub nickname($)		{ return field($_[0], "nickname"); }
Leigh Stoller's avatar
Leigh Stoller committed
296 297 298
sub slice_uuid($)	{ return field($_[0], "slice_uuid"); }
sub creator_uuid($)	{ return field($_[0], "creator_uuid"); }
sub created($)		{ return field($_[0], "created"); }
Leigh Stoller's avatar
Leigh Stoller committed
299
sub registered($)	{ return field($_[0], "registered"); }
Leigh Stoller's avatar
Leigh Stoller committed
300
sub credential_idx($)	{ return field($_[0], "credential_idx"); }
Leigh Stoller's avatar
Leigh Stoller committed
301
sub resource_uuid($)	{ return field($_[0], "resource_uuid"); }
302
sub resource_id($)	{ return field($_[0], "resource_id"); }
303
sub resource_type($)	{ return field($_[0], "resource_type"); }
Leigh Stoller's avatar
Leigh Stoller committed
304 305 306
sub component_uuid($)	{ return field($_[0], "component_uuid"); }
sub aggregate_uuid($)	{ return field($_[0], "aggregate_uuid"); }
sub rspec_string($)     { return field($_[0], "rspec_string"); }
Leigh Stoller's avatar
Leigh Stoller committed
307
sub status($)		{ return field($_[0], "status"); }
308
sub state($)		{ return field($_[0], "state"); }
309
sub status_state_timestamp($) { return field($_[0], "status_state_timestamp"); }
310
sub ErrorLog($)		{ return field($_[0], "errorlog"); }
311 312 313 314 315 316 317 318 319
sub cert($)		{ return GetCertificate($_[0])->cert(); }
# Watch for slivers that no longer get a certificate.
sub GetCertificate($)
{
    if (!defined($_[0]->{'CERTIFICATE'})) {
	print STDERR "*** No certificate for sliver: " . $_[0] . "\n";
    }
    return $_[0]->{'CERTIFICATE'};
}
Leigh Stoller's avatar
Leigh Stoller committed
320

321 322 323 324 325 326 327 328
# Return the sliver URN. 
sub sliver_urn($)
{
    my ($self)  = @_;

    return GeniHRN::Generate("@OURDOMAIN@", "sliver", $self->idx());
}

329 330 331 332 333 334 335 336 337 338 339 340 341 342
#
# Equality test. Not strictly necessary in perl, but good form.
#
sub SameSliver($$)
{
    my ($self, $other) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($other)));

    return $self->idx() == $other->idx();
}

Leigh Stoller's avatar
Leigh Stoller committed
343 344 345
#
# Delete the sliver. The sliver should not be provisioned when this done.
#
346
sub Delete($$)
Leigh Stoller's avatar
Leigh Stoller committed
347
{
348
    my ($self, $purge) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
349 350 351 352

    return -1
	if (! ref($self));

353 354
    my $idx  = $self->idx();
    my $uuid = $self->uuid();
Leigh Stoller's avatar
Leigh Stoller committed
355

356 357 358 359
    if (GeniUsage->DestroySliver($self, $purge)) {
	print STDERR
	    "GeniSliver::Delete: GeniUsage->DestroySliver($self) failed\n";
    }
360 361
    DBQueryWarn("delete from geni_credentials where this_uuid='$uuid'")
	or return -1;
362 363
    DBQueryWarn("delete from geni_certificates where uuid='$uuid'")
	or return -1;
Leigh Stoller's avatar
Leigh Stoller committed
364 365
    DBQueryWarn("delete from geni_slivers where idx='$idx'")
	or return -1;
366

367 368 369
    # Delete from cache. 
    delete($slivers{$idx});
    
Leigh Stoller's avatar
Leigh Stoller committed
370 371 372
    return 0;
}

373 374 375 376 377 378 379 380 381
#
# Annotate the rspec with the proper information to become
# a manifest. Returns undef because type is unknown
#
sub AnnotateManifest($)
{
    return undef;
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
#
# Get the manifest for an aggregate. Returns the XML string.
#
sub GetManifest($$)
{
    my ($self, $asxml) = @_;

    return undef
	if (! ref($self));

    my $manifest = $self->rspec();

    return $manifest
	if (!$asxml);
    
397
    my $xml = GeniXML::Serialize($self->rspec());
398 399 400
    return $xml;
}

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
#
# Lets create this lazily, these XML objects are really big and we do not
# need them very often.
#
sub rspec($)
{
    my ($self) = @_;

    return $self->{'RSPEC'}
        if (defined($self->{'RSPEC'}));

    my $rspec_string = $self->{'SLIVER'}->{'rspec_string'};
    return undef
	if (!defined($rspec_string) || $rspec_string eq "");
    
    my $rspec = GeniXML::Parse($rspec_string);
    return undef
	if (!defined($rspec));
    
    $self->{'RSPEC'} = $rspec;
    return $rspec;
}

#
# Purge all the rspecs from the cached slivers. 
#
sub PurgeRspecs($)
{
    foreach my $sliver (values(%slivers)) {
	$sliver->{'RSPEC'} = undef;
    }
}

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
#
# Store the rspec/manifest string.
#
sub UpdateRspec($$)
{
    my ($self, $rspec) = @_;

    my $idx          = $self->idx();
    my $rspec_string = GeniXML::Serialize($rspec);
    my $safe_rspec   = DBQuoteSpecial($rspec_string);

    return -1
	if (!DBQueryWarn("update geni_slivers set ".
			 "  rspec_string=$safe_rspec ".
			 "where idx='$idx'"));
    
    $self->{'RSPEC'} = $rspec;
451
    $self->{'SLIVER'}->{'rspec_string'} = $rspec_string;
452 453 454
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
455 456 457 458 459 460 461 462 463 464
#
# Set the aggregate for a sliver.
#
sub SetAggregate($$)
{
    my ($self, $aggregate) = @_;

    return -1
	if (! (ref($self) && ref($aggregate)));

Leigh Stoller's avatar
Leigh Stoller committed
465 466
    my $idx      = $self->idx();
    my $agg_uuid = $aggregate->uuid();
Leigh Stoller's avatar
Leigh Stoller committed
467 468 469

    return -1
	if (!DBQueryWarn("update geni_slivers set ".
Leigh Stoller's avatar
Leigh Stoller committed
470
			 "  aggregate_uuid='$agg_uuid' ".
Leigh Stoller's avatar
Leigh Stoller committed
471 472
			 "where idx='$idx'"));
    
473 474 475 476 477 478 479
    if (!DBQueryWarn("update sliver_history set ".
		     "  aggregate_uuid='$agg_uuid' ".
		     "where idx='$idx'")) {
	print STDERR "GeniSliver::SetAggregate: ".
	    "Failed to update sliver_history for $self\n";
    }

Leigh Stoller's avatar
Leigh Stoller committed
480
    $self->{'SLIVER'}->{'aggregate_uuid'} = $agg_uuid;
Leigh Stoller's avatar
Leigh Stoller committed
481 482 483 484
    $self->{'AGGREGATE'} = $aggregate;
    return 0;
}

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
#
# And clear the aggregate.
#
sub ClearAggregate($$)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $idx      = $self->idx();

    return -1
	if (!DBQueryWarn("update geni_slivers set ".
			 "  aggregate_uuid=NULL ".
			 "where idx='$idx'"));
    
    $self->{'SLIVER'}->{'aggregate_uuid'} = undef;
    $self->{'AGGREGATE'} = undef;
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
507 508 509 510 511 512 513 514 515 516 517 518
#
# Get the aggregate for a sliver.
#
sub GetAggregate($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    return $self->{'AGGREGATE'} if (defined($self->{'AGGREGATE'}));
    return undef
Leigh Stoller's avatar
Leigh Stoller committed
519
	if (!defined($self->aggregate_uuid()));
Leigh Stoller's avatar
Leigh Stoller committed
520

Leigh Stoller's avatar
Leigh Stoller committed
521
    my $aggregate = GeniAggregate->Lookup($self->aggregate_uuid());
Leigh Stoller's avatar
Leigh Stoller committed
522 523 524 525 526 527 528 529
    if (!defined($aggregate)) {
	print STDERR "Could not get aggregate object associated with $self\n";
	return undef;
    }
    $self->{'AGGREGATE'} = $aggregate;
    return $aggregate;
}

530 531 532 533 534 535 536 537 538 539 540 541 542 543
#
# Set the status for the sliver.
#
sub SetStatus($$)
{
    my ($self, $status) = @_;

    return undef
	if (! ref($self));

    my $idx = $self->idx();
    
    return -1
	if (!DBQueryWarn("update geni_slivers set ".
544 545
			 "  status='$status', ".
			 "  status_state_timestamp=unix_timestamp(now()) ".
546 547 548 549 550 551
			 "where idx='$idx'"));
    
    $self->{'SLIVER'}->{'status'} = $status;
    return 0;
}

552 553 554 555 556 557 558 559 560 561 562 563 564 565
#
# Set the state for the sliver.
#
sub SetState($$)
{
    my ($self, $state) = @_;

    return undef
	if (! ref($self));

    my $idx = $self->idx();
    
    return -1
	if (!DBQueryWarn("update geni_slivers set ".
566 567
			 "  state='$state', ".
			 "  status_state_timestamp=unix_timestamp(now()) ".
568 569 570 571 572 573
			 "where idx='$idx'"));
    
    $self->{'SLIVER'}->{'state'} = $state;
    return 0;
}

574 575 576 577 578 579 580 581
#
# Generate the blob for status. Redefined below.
#
sub GenerateStatusBlob($)
{
    return undef;
}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
#
# And the ErrorLog. These are intended to be short ...
#
sub SetErrorLog($$)
{
    my ($self, $log) = @_;
    my $safe_log = DBQuoteSpecial($log);

    return undef
	if (! ref($self));

    my $idx = $self->idx();
    
    return -1
	if (!DBQueryWarn("update geni_slivers set ".
			 "  errorlog=$safe_log ".
			 "where idx='$idx'"));
    
    $self->{'SLIVER'}->{'errorlog'} = $log;
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
604 605 606 607 608 609
#
# Get the experiment for the slice this sliver belongs to.
#
sub GetExperiment($)
{
    my ($self) = @_;
610
    require Experiment;
Leigh Stoller's avatar
Leigh Stoller committed
611 612 613 614 615 616 617

    return undef
	if (! ref($self));

    return Experiment->Lookup($self->slice_uuid());
}

Leigh Stoller's avatar
Leigh Stoller committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
#
# Get the slice for the sliver.
#
sub GetSlice($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    return $self->{'SLICE'} if (defined($self->{'SLICE'}));

    if (!defined($self->slice_uuid())) {
	print STDERR "No slice associated with $self\n";
	return undef;
    }
    my $slice = GeniSlice->Lookup($self->slice_uuid());
    if (!defined($slice)) {
	print STDERR "Could not get slice object associated with $self\n";
	return undef;
    }
    $self->{'SLICE'} = $slice;
    return $slice;
}

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
#
# The expiration time for a sliver is when the slice expires.
# The DB field is ignored.
#
sub expires($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    my $slice = $self->GetSlice();
    return undef
	if (!defined($slice));

    return $slice->expires();
}

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
#
# Look up a list of slivers for a locally instantiated slice. 
# Used by the CM.
#
sub SliceSlivers($$$)
{
    my ($class, $slice, $pref) = @_;

    my $slice_uuid = $slice->uuid();
    my @result = ();

    my $query_result =
	DBQueryWarn("select idx from geni_slivers ".
		    "where slice_uuid='$slice_uuid'");
    return -1
	if (!$query_result);

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $sliver = GeniSliver->Lookup($idx);
	return -1
	    if (!defined($sliver));
	push(@result, $sliver);
    }
    @$pref = @result;
    return 0;
}

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
#
# Find slivers "dependent" on this sliver, as for interfaces on nodes.
#
sub DependentSlivers($$)
{
    my ($self, $pref) = @_;

    return -1
	if (! (ref($self) && ref($pref)));
    @$pref = ();

    my $idx = $self->idx();
    my $resource_uuid = $self->resource_uuid();

    my $query_result =
	DBQueryWarn("select idx from geni_slivers ".
		    "where idx!='$idx' and resource_uuid='$resource_uuid'");
    return -1
	if (!$query_result);

    my @result = ();
    while (my ($idx) = $query_result->fetchrow_array()) {
	my $sliver = GeniSliver->Lookup($idx);
	if (!defined($sliver)) {
	    print STDERR "Could not get sliver object for $idx\n";
	    return -1;
	}
	push(@result, $sliver);
    }
    @$pref = @result;
    return 0;
}

721 722 723 724 725 726 727 728 729 730 731 732 733
############################################################################
#
# The server side methods are in packages which inherit from above.
#
package GeniSliver::Node;
use vars qw(@ISA);
@ISA = "GeniSliver";

use GeniDB;
use GeniComponent;
use GeniSlice;
use GeniCredential;
use GeniCertificate;
734
use GeniUtil;
735
use emutil;
Leigh Stoller's avatar
Leigh Stoller committed
736
use XML::Simple;
737
use Data::Dumper;
738
use libdb qw(TBDB_ALLOCSTATE_RES_INIT_DIRTY TBDB_NODESTATE_SHUTDOWN
739
	     TBResolveNextOSID TBDB_NODESTATE_ISUP TBDB_NODESTATE_TBFAILED
740
             TBDB_NODESTATE_RELOADFAILED TBDB_NODESTATE_PXEWAIT);
741

742 743 744 745 746 747 748 749 750 751
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if (0);
    return system($command);
}

752 753
# Error log for local physical node. This overrides the default method above,
# since it is stored in the node.
754 755 756 757 758
sub ErrorLog($)
{
    my ($self)  = @_;
    my $bootlog = "";

759
    my $node = Node->Lookup($self->resource_id());
760 761 762 763 764 765 766 767 768 769
    if (!defined($node)) {
	print STDERR "Could not map node $self to its object\n";
	return "";
    }
    if ($node->GetBootLog(\$bootlog)) {
	print STDERR "Could not get bootlog for $self ($node)\n";
	return "";
    }
    return $bootlog;
}
770

771 772 773
# Return the resource URN. This is how a resource is resolved.
# Resource urns may differ from component_urns (pcvm201-1 rather than pc201).
sub resource_urn($)
774 775 776 777 778 779
{
    my ($self)  = @_;

    return GeniHRN::Generate("@OURDOMAIN@", "node", $self->resource_id())
}

780
sub Create($$$$$;$)
781
{
782
    # $rspec is a LibXML element representing a single node.
783 784 785 786
    my ($class, $slice, $user, $node, $rspec, $resource_type) = @_;
    $resource_type = "Node"
	if (!defined($resource_type));
    
787
    my $virtualization_type = GeniXML::GetVirtualizationType($rspec);
788
    if (!defined($virtualization_type)) {
789 790 791
	print STDERR "Node does not contain a virtualization_type\n";
	return undef;
    }
Leigh Stoller's avatar
Leigh Stoller committed
792 793 794 795

    my $experiment = $slice->GetExperiment();
    if (!defined($experiment)) {
	print STDERR "Could not map $slice to its experiment\n";
796
	return undef;
Leigh Stoller's avatar
Leigh Stoller committed
797
    }
798

799 800
    #
    # An artifact of Emulab is that for shared/remote nodes, the physical
801
    # node is already allocated, but not to the current experiment.
802 803 804
    #
    if (! ($node->sharing_mode() ||
	   ($node->isremotenode() && $node->isvirtnode()))) {
805 806 807 808 809 810
	my $reservation = $node->Reservation();
	if (!defined($reservation)) {
	    print STDERR "$node was already released from $slice\n";
	    return undef;
	}
	if (! $reservation->SameExperiment($experiment)) {
811
	    print STDERR "$node is reserved to another, not $experiment\n";
812 813 814
	    # Signal error so we can look at what happened.
	    return undef;
	}
Leigh Stoller's avatar
Leigh Stoller committed
815
    }
816
    my $nickname = GeniXML::GetVirtualId($rspec);
817
    if (!defined($nickname)) {
818 819 820
	print STDERR "Node does not contain a virtual_id\n";
	return undef;
    }
Leigh Stoller's avatar
Leigh Stoller committed
821 822 823
    my $resource_uuid = $node->uuid();
    my $resource_id   = $node->node_id();
    my $hrn           = "${PGENIDOMAIN}." . $node->node_id();
824

825 826
    my $sliver = GeniSliver->Create($slice, $user, $resource_uuid,
				    $resource_type,
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
				    $resource_id, $hrn, $nickname, $rspec);
    return undef
	if (!defined($sliver));

    return $sliver;
}

#
# Annotate the rspec of this node with the proper information to become
# a manifest. Returns LibXML tree or undef on failure.
#
sub AnnotateManifest($)
{
    my ($self) = @_;
    my $rspec = GeniXML::Parse($self->rspec_string());
    if (! defined($rspec)) {
	print STDERR "Could not parse manifest rspec for node $self\n";
	return undef;
    }
    my $node = Node->Lookup($self->resource_id());
    if (!defined($node)) {
	print STDERR "Could not map node $self to its object\n";
	return undef;
    }
851
    my $vname = $node->vname();
852 853 854 855 856
    my $user = GeniUser->Lookup($self->creator_uuid(), 1);
    if (!defined($user)) {
	print STDERR "Could not map sliver $self to its creator\n";
	return undef;
    }
857 858 859 860 861
    my $experiment = $self->GetExperiment();
    if (!defined($experiment)) {
	print STDERR "Could not lookup experiment for sliver $self\n";
	return undef;
    }
862

Leigh Stoller's avatar
Leigh Stoller committed
863 864
    my $sshdport      = 22;
    my $hostname      = GeniUtil::FindHostname($node->node_id());
865
    my $sshdhost      = $hostname;
866
    my $vhostname     = GeniUtil::FindVHostname($experiment, $node);
867
    my $component_urn = GeniHRN::Generate("@OURDOMAIN@", "node",
868
					  $node->phys_nodeid());
869
    my $ipv4;
870
    
Leigh Stoller's avatar
Leigh Stoller committed
871
    if ($node->isvirtnode()) {
872 873 874 875 876 877
	my $public_control;
	$experiment->GetVirtNodeAttribute( $vname, "routable_control_ip",
					   \$public_control );
	if( defined( $public_control ) && $public_control eq "true" ) {
	    # we've assigned a public address to this one
	    $sshdhost = $hostname;
878 879 880 881 882

	    my $interface = Interface->LookupControl($node);
	    $ipv4 = $interface->IP()
		if (defined($interface));
	    
883 884 885 886 887 888
	} else {
	    # this node has no public control address of its own -- give the
	    # sshd port on the physical host's address
	    $sshdport = $node->sshdport();
	    $sshdhost = GeniUtil::FindHostname($node->phys_nodeid());
	}
889
    }
890 891 892 893 894
    else {
	my $interface = Interface->LookupControl($node);
	$ipv4 = $interface->IP()
	    if (defined($interface));
    }
895 896 897 898

    #
    # Add this stuff to the rspec (which becomes the manifest).
    #
899
    if (GeniXML::IsVersion0($rspec)) {
900
	GeniXML::SetText("hostname", $rspec, $sshdhost);
901 902
	GeniXML::SetText("sshdport", $rspec, $sshdport)
	    if (defined($sshdport));
903 904
	GeniXML::SetText("sliver_uuid", $rspec, $self->uuid());
	GeniXML::SetText("sliver_urn", $rspec, $self->sliver_urn());
905
	GeniXML::SetText("component_urn", $rspec, $self->resource_urn());
906 907
    } else {
	GeniXML::SetText("sliver_id", $rspec, $self->sliver_urn());
908
	GeniXML::SetText("component_id", $rspec, $component_urn);
909 910 911 912 913
	my $host = GeniXML::FindFirst("n:host", $rspec);
	if (! defined($host)) {
	    $host = GeniXML::AddElement("host", $rspec);
	}
	GeniXML::SetText("name", $host, $vhostname);
914 915
	GeniXML::SetText("ipv4", $host, $ipv4)
	    if (defined($ipv4));
916
    }
917 918
    my $services = GeniXML::FindFirst("n:services", $rspec);
    
919 920 921 922 923
    if ($experiment->HasNonLocalUsers()) {
	if (! defined($services)) {
	    $services = GeniXML::AddElement("services", $rspec);
	}
	my $login = GeniXML::FindFirst("n:login", $services);
924
	while (defined($login)) {
Leigh Stoller's avatar
Leigh Stoller committed
925
	    $services->removeChild($login);
926 927 928 929 930
	    $login = GeniXML::FindFirst("n:login", $services);	    
	}
	my $nonlocalusers;
	$experiment->NonLocalUsers(\$nonlocalusers);
	foreach my $localuser (@$nonlocalusers) {
931
	    $login = GeniXML::AddElement("login", $services);
932 933 934 935 936

	    GeniXML::SetText("authentication", $login, "ssh-keys");
	    GeniXML::SetText("hostname", $login, $sshdhost);
	    GeniXML::SetText("port", $login, $sshdport);
	    GeniXML::SetText("username", $login, $localuser->{"login"});
937 938
	}
    }
939
    my $tipserver = undef;
940 941 942 943 944 945 946
    #
    # The tipline for a virtual node will not exist till its booted,
    # since the capture runs on the physical host. But thats too late,
    # it needs to be in the manifest now. So lets just say we have
    # one, expecting it to be available by the time the user might
    # want to use it.
    #
Leigh Stoller's avatar
Leigh Stoller committed
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    if (!$node->IsTainted()) {
	if ($node->TipServer(\$tipserver) == 0 && defined($tipserver) ||
	    $node->isvirtnode()) {
	    if (! defined($services)) {
		$services = GeniXML::AddElement("services", $rspec);
	    }
	    my $console = GeniXML::FindNodesNS("n:console", $services,
					       $GeniXML::EMULAB_NS)->pop();
	    if (defined($console)) {
		$services->removeChild($console);
	    }
	    $console = GeniXML::AddElement("console",
					   $services, $GeniXML::EMULAB_NS);
	    GeniXML::SetText("server", $console,
			     (defined($tipserver) ? $tipserver : $sshdhost));
	}
	if ($node->recoverymfs_osid() && !$node->isvirtnode()) {
	    if (! defined($services)) {
		$services = GeniXML::AddElement("services", $rspec);
	    }
	    my $recovery = GeniXML::FindNodesNS("n:recovery", $services,
						$GeniXML::EMULAB_NS)->pop();
	    if (!defined($recovery)) {
		$recovery = GeniXML::AddElement("recovery",
						$services, $GeniXML::EMULAB_NS);
	    }
	    GeniXML::SetText("available", $recovery, "true");
974
	}
Leigh Stoller's avatar
Leigh Stoller committed
975 976 977 978 979 980
	elsif (defined($services)) {
	    my $recovery = GeniXML::FindNodesNS("n:recovery", $services,
						$GeniXML::EMULAB_NS)->pop();
	    if (defined($recovery)) {
		$services->removeChild($recovery);
	    }
981 982
	}
    }
983

984 985 986 987 988 989 990 991 992 993 994
    my $adb_port;
    $experiment->GetVirtNodeAttribute( $vname, "adb_port",
				       \$adb_port );
    GeniXML::SetText( "adb_port", $rspec, $adb_port )
	if( defined( $adb_port ) );
    
    my $adb_target;
    $experiment->GetVirtNodeAttribute( $vname, "adb_target",
				       \$adb_target );
    GeniXML::SetText( "adb_target", $rspec, $adb_target )
	if( defined( $adb_target ) );
995 996 997 998 999 1000 1001 1002 1003 1004

    my $sim_sequence_number;
    $node->NodeAttribute( "sim_sequence_number", \$sim_sequence_number );
    GeniXML::SetText( "sim_sequence_number", $rspec, $sim_sequence_number )
	if( defined( $sim_sequence_number ) );
    
    my $sim_imsi;
    $node->NodeAttribute( "sim_imsi", \$sim_imsi );
    GeniXML::SetText( "sim_imsi", $rspec, $sim_imsi )
	if( defined( $sim_imsi ) );
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

    #
    # Add Emulab extension that says which virtnodes are instantiated
    # on this physical host.
    #
    if (!$node->isvirtnode() && $node->HasVirtualNodes()) {
	my @vnodes = ();
	if ($node->VirtualNodes(\@vnodes)) {
	    print STDERR "Could not get virtnode list for $node\n";
	    return undef;
	}
	my $vmlistref = GeniXML::FindNodesNS("n:vmlist", $rspec,
					     $GeniXML::EMULAB_NS)->pop();
	if (defined($vmlistref)) {
	    $rspec->removeChild($vmlistref);
	}
	$vmlistref = GeniXML::AddElement("vmlist", $rspec,
					 $GeniXML::EMULAB_NS);
	foreach my $child (@vnodes) {
	    my $vmref = GeniXML::AddElement("vm", $vmlistref,
					    $GeniXML::EMULAB_NS);
	    GeniXML::SetText("client_id", $vmref, $child->vname());
	    GeniXML::SetText("vnode", $vmref, $child->node_id());
	}
    }
1030
    
1031 1032 1033 1034
    if ($self->UpdateRspec($rspec)) {
	print STDERR "Could not insert annotated manifest for node $self ".
	    "into database";
	return undef;
1035
    }
1036 1037

    return $rspec;
1038 1039
}

Leigh Stoller's avatar
Leigh Stoller committed
1040 1041
#
# Provision a slice. We actually did this when the ticket was requested.
Leigh Stoller's avatar
Leigh Stoller committed
1042
# We fill in some virt table stuff so that tbswap will work.
Leigh Stoller's avatar
Leigh Stoller committed
1043
#
Leigh Stoller's avatar
Leigh Stoller committed
1044
sub Provision($;$)
Leigh Stoller's avatar
Leigh Stoller committed
1045
{
Leigh Stoller's avatar
Leigh Stoller committed
1046
    my ($self, $extraargs) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
1047 1048 1049 1050 1051 1052 1053

    return -1
	if (! ref($self));

    #
    # the node is already allocated to the sliver, but still need to enter
    # a virt_nodes entry, and possibly more virt table entries, so that the
Leigh Stoller's avatar
Leigh Stoller committed
1054
    # node will boot properly, and is otherwise controllable.
Leigh Stoller's avatar
Leigh Stoller committed
1055
    #
1056
    my $experiment = $self->GetExperiment();
Leigh Stoller's avatar
Leigh Stoller committed
1057 1058 1059 1060
    if (!defined($experiment)) {
	print STDERR "Could not map $self to its experiment\n";
	return -1;
    }
1061
    my $node_id = $self->resource_id();
Leigh Stoller's avatar
Leigh Stoller committed
1062
    return 0
1063 1064
	if (!defined($node_id));
    my $node       = Node->Lookup($node_id);
Leigh Stoller's avatar
Leigh Stoller committed
1065
    if (!defined($node)) {
1066
	print STDERR "Could not map node $node_id to its object\n";
Leigh Stoller's avatar
Leigh Stoller committed
1067 1068 1069 1070
	return -1;
    }
    my $reservation = $node->Reservation();
    if (!defined($reservation)) {
1071
	print STDERR "$node was already released from slice\n";
Leigh Stoller's avatar
Leigh Stoller committed
1072 1073
	return -1;
    }
1074
    if (! $reservation->SameExperiment($experiment)) {
1075
	print STDERR "$node is reserved to another, not $experiment\n";
1076 1077 1078 1079 1080
	# Signal error so we can look at what happened.
	return -1;
    }
    my $pid = $experiment->pid();
    my $eid = $experiment->eid();
1081

1082
    my $virt_type = GeniXML::GetVirtualizationType($self->rspec());
1083
    if (!$node->isremotenode() &&
1084
	defined($virt_type) &&
1085
	$virt_type eq "emulab-vnode") {
1086 1087 1088 1089
	my $pnode = Node->Lookup($node->phys_nodeid());
	if (!defined($pnode)) {
	    print STDERR "Could not get pnode object for $node\n";
	    return -1;
Leigh Stoller's avatar
Leigh Stoller committed
1090
	}
1091 1092 1093 1094 1095
	# This would typically happen in libvtop, but we call the mapper
	# in a way that causes it to not happen. Do not do this after
	# initial provisioning.
	$node->ResetStartStatus()
	    if (!$node->genisliver_idx());
1096

1097 1098
	# Mark
	$node->ModifyReservation({"genisliver_idx" => $self->idx()});
1099

1100
	my $subtype = GeniXML::GetVirtualizationSubtype($self->rspec());
1101
	if (defined($subtype)) {
Leigh Stoller's avatar
Leigh Stoller committed
1102
	    if (!$pnode->sharing_mode()) {
1103
		# This would typically happen in libvtop, but we call the mapper
1104 1105 1106 1107 1108 1109 1110
		# in a way that causes it to not happen. Do not do this after
		# initial provisioning.
		$pnode->ResetStartStatus()
		    if (!$pnode->genisliver_idx());

		# Mark
		$pnode->ModifyReservation({"genisliver_idx" => $self->idx()});
Leigh Stoller's avatar
Leigh Stoller committed
1111
	    }
1112
	}
Leigh Stoller's avatar
Leigh Stoller committed
1113 1114
    }
    else {
1115 1116 1117 1118
	#
	# For a "raw" node, there is no vnode, so this is the pnode
	# we need to mark for tmcd.
	#
1119 1120 1121 1122 1123 1124 1125 1126
	# This would typically happen in libvtop, but we call the mapper
	# in a way that causes it to not happen. Do not do this after
	# initial provisioning.
	#
	$node->ResetStartStatus()
	    if (!$node->genisliver_idx());

	# Mark
1127 1128 1129 1130
	if ($node->ModifyReservation({"genisliver_idx" => $self->idx()})) {
	    return -1;
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
1131 1132 1133 1134 1135 1136
    return 0;
}

#
# Unprovision a sliver. 
#
1137
sub UnProvision($;$)
Leigh Stoller's avatar
Leigh Stoller committed
1138
{
1139
    my ($self, $nophysfree) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
1140 1141 1142

    return -1
	if (! ref($self));
1143 1144
    $nophysfree = 0
	if (!defined($nophysfree));
Leigh Stoller's avatar
Leigh Stoller committed
1145

1146
    my $experiment = $self->GetExperiment();
Leigh Stoller's avatar
Leigh Stoller committed
1147 1148
    if (!defined($experiment)) {
	print STDERR "Could not map $self to its experiment\n";
Leigh Stoller's avatar
Leigh Stoller committed
1149
	return 0;
Leigh Stoller's avatar
Leigh Stoller committed
1150
    }
1151
    my $node_id = $self->resource_id();
Leigh Stoller's avatar
Leigh Stoller committed
1152
    return 0
1153 1154
	if (!defined($node_id));
    my $node       = Node->Lookup($node_id);
Leigh Stoller's avatar
Leigh Stoller committed
1155
    if (!defined($node)) {
1156 1157
	# Lets call this nonfatal since it might be a virtnode that is gone.
	print STDERR "Could not map node $node_id to its object\n";
Leigh Stoller's avatar
Leigh Stoller committed
1158
	return 0;
Leigh Stoller's avatar
Leigh Stoller committed
1159 1160 1161 1162 1163 1164 1165
    }
    my $reservation = $node->Reservation();
    if (!defined($reservation)) {
	print STDERR "$node was already released from $self\n";
	return 0;
    }
    if ($reservation->SameExperiment($experiment)) {
Leigh Stoller's avatar
Leigh Stoller committed
1166
	my $node_id = $node->node_id();
Leigh Stoller's avatar
Leigh Stoller committed
1167 1168
	my $pid = $experiment->pid();
	my $eid = $experiment->eid();
Leigh Stoller's avatar
Leigh Stoller committed
1169

1170 1171 1172 1173 1174 1175
	#
	# Shared virtnode only for this part, we want to avoid duplicated
	# or unnecessary work (no need to tear down on dedicated hosts).
	#
	if ($self->status() ne "stopped") {
	    if ($node->isremotenode() && $node->isvirtnode()) {
1176
		mysystem("$VNODESETUP -p -q -m -k $pid $eid $node_id");
1177 1178 1179 1180
		if ($?) {
		    print STDERR "$VNODESETUP -k failed on $node_id\n";
		    return -1;
		}
1181
	    }
1182
	    elsif ($node->sharing_mode()) {
1183
		mysystem("$VNODESETUP -j -q -m -k $pid $eid $node_id");
1184 1185 1186 1187
		if ($?) {
		    print STDERR "$VNODESETUP -k failed on $node_id\n";
		    return -1;
		}
Leigh Stoller's avatar
Leigh Stoller committed
1188
	    }
1189
	}
Leigh Stoller's avatar
Leigh Stoller committed
1190

1191
	my $virt_type = GeniXML::GetVirtualizationType($self->rspec());
1192
	my $sub_type  = GeniXML::GetVirtualizationSubtype($self->rspec());
1193
	if (!$node->isremotenode() && $node->isvirtnode()) {
Leigh Stoller's avatar
Leigh Stoller committed
1194 1195 1196 1197 1198 1199
	    my $pnode_id = $node->phys_nodeid();
	    my $pnode = Node->Lookup($pnode_id);
	    if (!defined($pnode)) {
		print STDERR "Could not get pnode object for $pnode_id\n";
		return -1;
	    }
1200 1201 1202

	    #
	    # If this is the last virtnode on the physnode, release the
Leigh Stoller's avatar
Leigh Stoller committed
1203 1204
	    # physnode too. Unless its a shared host, in which case just
	    # deallocate the virtnode.
1205
	    #
Leigh Stoller's avatar
Leigh Stoller committed
1206 1207 1208 1209 1210 1211
	    my @vnodes = ();
	    
	    if ($pnode->sharing_mode()) {
		$nophysfree = 1;
	    }
	    elsif ($pnode->VirtualNodes(\@vnodes) != 0) {
1212
		print STDERR "Could not get vnode list for $pnode\n";
Leigh Stoller's avatar
Leigh Stoller committed
1213 1214
		return -1;
	    }
1215

1216
	    if (scalar(@vnodes) > 1 || $nophysfree) {
1217
		mysystem("$NFREE -q $pid $eid $node_id");
1218 1219 1220
		# Unincorporate the node. Bogus, needs fixing.
		$pnode->ModifyReservation({"genisliver_idx" => 0})
		    if (! ($pnode->sharing_mode() || scalar(@vnodes) > 1));
1221 1222
	    }
	    else {
1223
		mysystem("$NFREE -x -q $pid $eid $pnode_id");
1224 1225
		$pnode->Refresh();
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1226 1227
	}
	else {
1228 1229 1230 1231 1232
	    if ($nophysfree) {
		# Unincorporate the node. Bogus, needs fixing.
		$node->ModifyReservation({"genisliver_idx" => 0});
		goto skip;
	    }
1233 1234
	    my $opt = "";
	    
1235 1236 1237 1238 1239 1240 1241 1242
	    #
	    # Look to see if local physical node was stopped (powered off).
	    #
	    if (!$node->isvirtnode() &&
		!$node->isremotenode() &&
		$self->state() eq "stopped") {
		system("$POWER on $node_id");
	    }
1243 1244 1245 1246 1247 1248 1249
	    # Kill vnodes on pnode if we are deallocating a pnode.
	    if (!$node->isvirtnode() &&
		!$node->isremotenode() &&
		!$node->sharing_mode()) {
		$opt = "-x";
	    }	    
	    mysystem("$NFREE $opt -q $pid $eid $node_id");
Leigh Stoller's avatar
Leigh Stoller committed
1250
	}
Leigh Stoller's avatar
Leigh Stoller committed
1251 1252
	if ($?) {
	    print STDERR "Could not deallocate $node from $self\n";
Leigh Stoller's avatar
Leigh Stoller committed
1253
	    $node->Refresh();
Leigh Stoller's avatar
Leigh Stoller committed
1254 1255
	    return -1;
	}
1256
      skip:
Leigh Stoller's avatar
Leigh Stoller committed
1257
	$node->Refresh();
Leigh Stoller's avatar
Leigh Stoller committed
1258 1259 1260 1261
    }
    else {
	print STDERR "$node is reserved to another, not $self\n";
	# Signal error so we can look at what happened.
1262
	return 0;
Leigh Stoller's avatar
Leigh Stoller committed
1263 1264 1265 1266
    }
    return 0;
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
#
# Process a manifest.
#
sub ProcessManifest($$)
{
    my ($self, $manifest) = @_;

    return -1
	if (! ref($self));

1277
    my $experiment = $self->GetExperiment();
1278 1279 1280 1281 1282 1283 1284
    if (!defined($experiment)) {
	print STDERR "Could not map $self to its experiment\n";
	return -1;
    }
    my $pid = $experiment->pid();
    my $eid = $experiment->eid();
    
1285
    my $node_id = $self->resource_id();
1286
    return 0
1287 1288
	if (!defined($node_id));
    my $node       = Node->Lookup($node_id);
1289
    if (!defined($node)) {
1290
	print STDERR "Could not map node $node_id to its object\n";
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
	return -1;
    }
    my $reservation = $node->Reservation();
    if (!defined($reservation)) {
	print STDERR "$node was already released from $self\n";
	return -1;
    }
    if ($reservation->SameExperiment($experiment)) {
	#
	# Find the corresponding node in the manifest.
	#
1302
	foreach my $ref (GeniXML::FindNodes("n:node",
1303
					    $manifest)->get_nodelist()) {
1304
	    my $sliver_urn = GeniXML::GetSliverId($ref);
1305
	    if (defined($sliver_urn) && $sliver_urn eq $self->sliver_urn()) {
1306
		# startup command.
1307
		my $startupcmd = GeniXML::GetStartupCommand($ref);
1308
		if (defined($startupcmd)) {
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
		    if (! TBcheck_dbslot($startupcmd, "virt_nodes",
					 "startupcmd",
					 TBDB_CHECKDBSLOT_WARN|
					 TBDB_CHECKDBSLOT_ERROR)) {
			print STDERR "Invalid startup command '$startupcmd'\n";
			return -1;
		    }
		    $node->Update({"startupcmd" => $startupcmd});
		}
		return 0;
	    }
	}
    }
    else {
	print STDERR "$node is reserved to another, not $self\n";
	# Signal error so we can look at what happened.
	return -1;
    }
    return 0;
}

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
sub Start($$)
{
    my ($self, $version) = @_;

    return $self->Action($version, "start");
}

sub Restart($$)
{
    my ($self, $version) = @_;

    return $self->Action($version, "restart");
}

sub Reload($$)
{
    my ($self, $version) = @_;

    return $self->Action($version, "reload");
}

Leigh Stoller's avatar
Leigh Stoller committed
1351
#
1352
# Start, Restart, and Reload.
Leigh Stoller's avatar
Leigh Stoller committed
1353
#
1354
sub Action($$$)
Leigh Stoller's avatar
Leigh Stoller committed
1355
{
1356 1357 1358
    my ($self, $version, $action) = @_;
    my $restart = ($action eq "restart" ? 1 : 0);
    my $reload  = ($action eq "reload" ? 1 : 0);
Leigh Stoller's avatar
Leigh Stoller committed
1359 1360 1361 1362

    return -1
	if (! ref($self));

1363
    my $experiment = $self->GetExperiment();
Leigh Stoller's avatar
Leigh Stoller committed
1364 1365 1366 1367
    if (!defined($experiment)) {
	print STDERR "Could not map $self to its experiment\n";
	return -1;
    }
Leigh Stoller's avatar
Leigh Stoller committed
1368 1369 1370
    my $pid = $experiment->pid();
    my $eid = $experiment->eid();
    
1371
    my $node_id = $self->resource_id();
Leigh Stoller's avatar
Leigh Stoller committed
1372
    return 0
1373 1374
	if (!defined($node_id));
    my $node       = Node->Lookup($node_id);
Leigh Stoller's avatar
Leigh Stoller committed
1375
    if (!defined($node)) {
1376
	print STDERR "Could not map node $node_id to its object\n";
Leigh Stoller's avatar
Leigh Stoller committed
1377 1378 1379 1380 1381 1382 1383 1384
	return -1;
    }
    my $reservation = $node->Reservation();
    if (!defined($reservation)) {
	print STDERR "$node was already released from $self\n";
	return -1;
    }
    if ($reservation->SameExperiment($experiment)) {
Leigh Stoller's avatar
Leigh Stoller committed
1385
	my $node_id = $node->node_id();
Leigh Stoller's avatar
Leigh Stoller committed
1386

1387 1388 1389 1390 1391 1392
	if ($reload) {
	    system("$OSLOAD -c -s $node_id");
	    return -1
		if ($?);
	}

Leigh Stoller's avatar
Leigh Stoller committed
1393 1394 1395
	#
	# Reboot and wait?
	#
1396 1397
	if ($node->isvirtnode()) {
	    if ($self->state() eq "stopped") {
1398
		system("$VNODESETUP -j -m $pid $eid $node_id");
Leigh Stoller's avatar
Leigh Stoller committed
1399
	    }
1400 1401 1402
	    elsif ($restart) {
		system("$NODEREBOOT $node_id");
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1403 1404
	}
	else {
1405 1406 1407
	    #
	    # Look to see if local physical node was stopped (powered off).
	    #
1408
	    if ($self->state() eq "stopped") {
1409 1410
		system("$POWER on $node_id");
	    }
1411
	    elsif ($restart) {
1412
		system("$NODEREBOOT $node_id");
1413
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1414
	}
Leigh Stoller's avatar
Leigh Stoller committed
1415 1416
	return -1
	    if ($?);
Leigh Stoller's avatar
Leigh Stoller committed
1417 1418 1419 1420 1421
    }
    else {
	print STDERR "$node is reserved to another, not $self\n";
	# Signal error so we can look at what happened.
	return -1;
Leigh Stoller's avatar
Leigh Stoller committed
1422
    }
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    $self->SetState("started");
    return 0;
}
# And stop.
sub Stop($$)
{
    my ($self, $version) = @_;

    return -1
	if (! ref($self));

1434
    my $experiment = $self->GetExperiment();
1435 1436 1437 1438 1439 1440 1441
    if (!defined($experiment)) {
	print STDERR "Could not map $self to its experiment\n";
	return -1;
    }
    my $pid = $experiment->pid();
    my $eid = $experiment->eid();
    
1442
    my $node_id = $self->resource_id();
1443
    return 0
1444 1445
	if (!defined($node_id));
    my $node       = Node->Lookup($node_id);
1446
    if (!defined($node)) {
1447
	print STDERR "Could not map node $node_id to its object\n";
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
	return -1;
    }
    my $reservation = $node->Reservation();
    if (!defined($reservation)) {
	print STDERR "$node was already released from $self\n";
	return -1;
    }
    if ($reservation->SameExperiment($experiment)) {
	my $node_id = $node->node_id();

	#
1459
	# Virtnodes are "halted" which shuts down the VM but leaves the disks.
1460
	#
1461 1462
	if ($node->isvirtnode()) {
	    system("$VNODESETUP -j -h -m $pid $eid $node_id");
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
	}
	else {
	    system("$POWER off $node_id");
	}
	return -1
	    if ($?);
    }
    else {
	print STDERR "$node is reserved to another, not $self\n";
	# Signal error so we can look at what happened.
	return -1;
    }
    $self->SetState("stopped");
    return 0;
}

1479
sub ComputeStatus($;$)
1480 1481 1482 1483 1484 1485 1486
{
    my ($self, $pref) = @_;
    my $status = undef;

    return -1
	if (! ref($self));

Leigh Stoller's avatar
Leigh Stoller committed
1487
    #
Leigh Stoller's avatar
Leigh Stoller committed
1488 1489
    # If the sliver is "broken" then call it failed. It might be failed,
    # but if the node actually came up okay later, we set it back to okay.
Leigh Stoller's avatar
Leigh Stoller committed
1490
    #
1491
    if ($self->status() eq "broken" || $self->status() eq "canceled") {
1492 1493
	$$pref = "failed"
	    if ($pref);
Leigh Stoller's avatar
Leigh Stoller committed
1494 1495 1496
	return 0;
    }

1497
    my $node_id = $self->resource_id();
1498
    return -1
1499 1500
	if (!defined($node_id));
    my $node       = Node->Lookup($node_id);
1501
    if (!defined($node)) {
1502
	print STDERR "Could not map node $node_id to its object\n";
1503 1504 1505 1506 1507 1508 1509
	return -1;
    }
    my $reservation = $node->Reservation();
    if (!defined($reservation)) {
	print STDERR "$node was already released from $self\n";
	return -1;
    }
1510 1511
    # Make sure our object has the updated state.
    $node->GetEventState();
1512
    
Leigh Stoller's avatar
Leigh Stoller committed
1513
    #
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
    # Special state for updating user accounts. We never go into the
    # state unless the sliver was started/ready, so we know we can go
    # back into the started state when it is done. 
    #
    if ($self->state() eq "updating_users") {
	if ($node->IsUpdated() == 0) {
	    $status = "changing";
	    goto done;
	}
	else {
	    # return to normal started state and continue below.
	    $self->SetState("started");
	}
    }
1528
    if ($self->state() eq "imaging" || $self->state() eq "restarting") {
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
	$status = "changing";
	goto done;
    }
    elsif ($reservation->elab_in_elab()) {
	#
	# The inner nodes do not tell us what is happening, so we just
	# call them ready when inner_elab_boot is set, which means that
	# inner elab is setup and running okay. Inner boss/ops do tell
	# us their state, so we use that to determine ready.
	#
1539 1540
	if ($node->eventstate() eq TBDB_NODESTATE_TBFAILED() ||
	    $node->eventstate() eq TBDB_NODESTATE_RELOADFAILED()) {
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
	    $status = "failed";
	    goto done;
	}
	elsif ($node->inner_elab_role() eq "node") {
	    $status = ($node->inner_elab_boot() ? "ready" : "notready");
	    goto done;
	}
	elsif (!$node->inner_elab_boot()) {
	    $status = "notready";
	    goto done;
	}
	# Fall through, waiting for ISUP for boss/ops.
    }
    
1555
    #
Leigh Stoller's avatar
Leigh Stoller committed
1556 1557
    # Emulab does not return "unknown" ... we always know ...
    #
1558 1559 1560 1561
    my $eventstate = $node->eventstate();
    if ($eventstate eq TBDB_NODESTATE_ISUP()) {
	$status = "ready";
    }
1562 1563
    elsif ($eventstate eq TBDB_NODESTATE_TBFAILED() ||
	   $eventstate eq TBDB_NODESTATE_RELOADFAILED()) {
1564 1565
	$status = "failed";
    }
1566 1567
    elsif ($eventstate eq TBDB_NODESTATE_SHUTDOWN() ||
	   $eventstate eq TBDB_NODESTATE_PXEWAIT()) {
1568 1569
	$status = "notready";
    }
Leigh Stoller's avatar
Leigh Stoller committed
1570 1571 1572
    else {
	$status = "changing";
    }
1573
  done:
1574
    $self->SetStatus($status);
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    $$pref = $status
	if (defined($pref));
    return 0;
}

#
# Set the status for the sliver.
#
sub SetStatus($$)
{
    my ($self, $status) = @_;
    my $idx = $self->idx();

    #
    # We want to know if the DB actually changed, and if so, we send
    # out an event indicating a change.
    #
    my $query_result =
1593 1594 1595
	DBQueryWarn("update geni_slivers set ".
		    "  status='$status',".
		    "  status_state_timestamp=unix_timestamp(now()) ".
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
		    "where idx='$idx' and status!='$status'");
    return -1
	if (!$query_result);
    
    $self->{'SLIVER'}->{'status'} = $status;
    # No change.
    return 0
	if (!$query_result->affectedrows);

    return $self->SendStatusEvent();
}

#
# Set the state for the sliver.
#
sub SetState($$)
{
    my ($self, $state) = @_;
    my $idx = $self->idx();

    #
    # We want to know if the DB actually changed, and if so, we send
    # out an event indicating a change. It would not be incorrect, but
    # lets avoid the extra noise.
    #
    my $query_result =
1622 1623 1624
	DBQueryWarn("update geni_slivers set ".
		    "  state='$state',".
		    "  status_state_timestamp=unix_timestamp(now()) ".
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
		    "where idx='$idx' and state!='$state'");
    return -1
	if (!$query_result);
    
    $self->{'SLIVER'}->{'state'} = $state;
    # No change.
    return 0
	if (!$query_result->affectedrows);
    
    return $self->SendStatusEvent();
}

#
# Send a status event. The status might not be any different then the last
# time we sent it; it is up to the consumer to deal with that. 
#
sub SendStatusEvent($)
{
    my ($self) = @_;

    my $slice = $self->GetSlice();
    return -1
	if (!defined($slice));

    my $blob = $self->GenerateStatusBlob();
    if (defined($blob)) {
	GeniEvent->SendEvent({"type"    => "SLIVERSTATUS",
			      "slice"   => $slice->urn(),
			      "urn"     => $self->sliver_urn(),
			      "details" => $blob});
    }
Leigh Stoller's avatar
Leigh Stoller committed
1656 1657
    return 0;
}
Leigh Stoller's avatar
Leigh Stoller committed
1658

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
#
# Like above, but send frisbee status stuff.
#
sub SendFrisbeeEvent($$$)
{
    my ($self, $imagename, $mb_written) = @_;
    my $slice = $self->GetSlice();
    return -1
	if (!defined($slice));

    my $resource_id   = $self->resource_id();
    my $nickname      = $self->nickname() || "";

    my $blob = {
	"component_urn" => $resource_id,
	"client_id"     => $nickname,
	"imagename"     => $imagename,
	"MB_written"    => $mb_written,
	"utc"           => time(),
    };
    GeniEvent->SendEvent({"type"    => "FRISBEESTATUS",
			  "slice"   => $slice->urn(),
			  "urn"     => $self->sliver_urn(),
			  "details" => $blob});
    return 0;
}

1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
#
# Generate the blob for status. 
#
sub GenerateStatusBlob($)
{
    my ($self) = @_;

    my $sliver_urn    = $self->sliver_urn();
    my $resource_id   = $self->resource_id();
    my $state         = $self->state();
    my $status        = $self->status();
    my $nickname      = $self->nickname() || "";
1698 1699
    # Fall back to current time if no timestamp yet.
    my $utc           = $self->status_state_timestamp() || time();
1700 1701 1702 1703

    my $node = Node->LookupSync($resource_id);
    if (!defined($node)) {
	print STDERR "Could not map node $resource_id to its object\n";
Leigh Stoller's avatar
Leigh Stoller committed
1704
	return undef;
1705
    }
1706 1707 1708 1709 1710 1711 1712
    my ($nodestatus,$nodestatus_timestamp) = $node->GetStatus();
    if (!defined($nodestatus)) {
	$nodestatus = "unknown";
	$nodestatus_timestamp = 0;
    }
    my $rawstate = $node->eventstate();
    my $rawstate_timestamp = $node->state_timestamp();
1713 1714 1715 1716 1717

    # New is the same as stopped. Separate state is handy.
    $state = "stopped"
	if ($state eq "new");

Leigh Stoller's avatar
Leigh Stoller committed
1718 1719 1720 1721 1722 1723
    # See if booted into the admin or recovery MFS (not frisbee).
    my $recovery = 0;
    if ($node->temp_boot_osid()) {
	$recovery = 1;
    }

1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
    #
    # So we have a bunch of timestamps for various bits of state.
    # Not much atomicity, but I think we are okay. Use the most
    # recent timestamp, else current time.
    #
    $utc = $nodestatus_timestamp
	if ($nodestatus_timestamp > $utc);
    $utc = $rawstate_timestamp
	if ($rawstate_timestamp > $utc);

1734 1735 1736 1737 1738
    my $blob = {
	"component_urn" => $resource_id,
	"client_id"     => $nickname,
	"state"         => $state,
	"status"        => $status,
Leigh Stoller's avatar
Leigh Stoller committed
1739
	# We do not put this in unless its for SliverStatus. Too big.
1740
	"error"         => "",
1741
	"rawstate"      => $rawstate,
1742
	"nodestatus"    => $nodestatus,
1743
	"utc"           => $utc,
Leigh Stoller's avatar
Leigh Stoller committed
1744
	"recovery"      => $recovery,
1745 1746 1747 1748 1749 1750
    };

    #
    # Startup command info.
    #
    if (defined($node) &&
1751 1752
	((defined($node->startupcmd()) && $node->startupcmd() ne "") ||
	 $node->HasStartupAgent())) {
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
	if (defined($node->startstatus()) &&
	    $node->startstatus() ne "none") {
	    $blob->{'execute_state'}   = "exited";
	    $blob->{'execute_status'}  = $node->startstatus();
	}
	else {
	    if ($node->eventstate() eq "ISUP") {
		$blob->{'execute_state'}   = "running";
		$blob->{'execute_status'}  = "unknown";
	    }
	    else {
		$blob->{'execute_state'}   = "n/a";
		$blob->{'execute_status'}  = "n/a";
	    }
	}
    }
    return $blob;
}

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
##########################################################################
#
package GeniSliver::Vhost;
use vars qw(@ISA);
@ISA = "GeniSliver::Node";

use GeniDB;
use GeniComponent;
use GeniSlice;
use GeniCredential;
use GeniCertificate;
use GeniUtil;

#
# This is a wrapper so that we can represent internally added hosts
# but not treat them like normal nodes when doing rspec/manifest things.
#
sub Create($$$$$)
{
    my ($class, $slice, $user, $node, $rspec) = @_;

    return GeniSliver::Node->Create($slice, $user, $node, $rspec, "Vhost");
}

# Nothing to do right now.
sub UnProvision($$)
{
    return 0;
}

1802
########################