APT_Profile.pm.in 33.8 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2016 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
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
package APT_Profile;

26 27 28 29 30 31 32 33 34 35 36
#
# Note about permissions bits.
#
# listed - The profile will be listed on the home page for anyone to see/use.
# public - Anyone can instantiate the profile, regardless of its listed bit
#          Say, if you send a URL to someone. 
# shared - Shared with logged in users. If not listed, then the default is
#          that only project members can see/use the profile, unless the public
#          is set (but they need a url). Shared says any logged in user can
#          see and use the profile.  

37 38 39 40 41 42 43 44 45 46
use strict;
use Carp;
use Exporter;
use vars qw(@ISA @EXPORT $AUTOLOAD);

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

# Must come after package declaration!
use EmulabConstants;
47
use emutil;
48
use emdb;
49
use APT_Dataset;
50
use GeniXML;
51
use GeniHRN;
52
use libtestbed;
53
use Lease;
54 55
use English;
use Data::Dumper;
56
use File::Temp qw(tempfile :mktemp tmpnam :POSIX);
57 58 59 60 61
use overload ('""' => 'Stringify');

# Configure variables
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
62 63
my $OURDOMAIN     = "@OURDOMAIN@";
my $MYURN         = "urn:publicid:IDN+${OURDOMAIN}+authority+cm";
64

65 66 67 68 69 70 71 72
# Concat id/vers.
sub versid($)
{
    my ($self) = @_;

    return $self->profileid() . ":" . $self->version();
}

Leigh B Stoller's avatar
Leigh B Stoller committed
73 74 75 76 77 78 79 80
# Concat name/vers.
sub versname($)
{
    my ($self) = @_;

    return $self->name() . ":" . $self->version();
}

81 82 83 84 85 86 87 88 89 90
sub BlessRow($$)
{
    my ($class, $row) = @_;
    
    my $self           = {};
    $self->{'DBROW'}   = $row;

    bless($self, $class);
    return $self;
}
91 92

#
93
# Lookup. 
94
#
95
sub Lookup($$;$$)
96
{
97
    my ($class, $arg1, $arg2, $arg3) = @_;
98 99

    #
100 101
    # A single arg is either an index or "pid,profile[:version]" or
    # "pid/profile[:version]" string.
102 103 104
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
105
	    my $result =
106 107
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    " from apt_profiles as i ".
108 109 110 111 112 113 114 115
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid and ".
			    "     v.version=i.version ".
			    "where i.profileid='$arg1'");
	    return undef
		if (! $result || !$result->numrows);

	    return BlessRow($class, $result->fetchrow_hashref());
116 117
	}
	elsif ($arg1 =~ /^([-\w]*),([-\w\.\+]*)$/ ||
118 119
		$arg1 =~ /^([-\w]*)\/([-\w\.\+]*)$/) {
	    my $result =
120 121
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    " from apt_profiles as i ".
122 123 124 125 126 127 128 129 130 131 132 133
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid and ".
			    "     v.version=i.version ".
			    "where i.pid='$1' and i.name='$2'");
	    return undef
		if (! $result || !$result->numrows);

	    return BlessRow($class, $result->fetchrow_hashref());
	}
	elsif ($arg1 =~ /^([-\w]*),([-\w\.\+]*):(\d*)$/ ||
		$arg1 =~ /^([-\w]*)\/([-\w\.\+]*):(\d*)$/) {
	    my $result =
134 135
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    " from apt_profiles as i ".
136 137 138 139 140 141 142 143
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid ".
			    "where i.pid='$1' and i.name='$2' and ".
			    "      v.version='$3' and v.deleted is null");
	    return undef
		if (!$result || !$result->numrows);

	    return BlessRow($class, $result->fetchrow_hashref())
144 145
	}
	elsif ($arg1 =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
146 147 148 149 150
	    #
	    # First look to see if the uuid is for the profile itself,
	    # which means current version. Otherwise look for a
	    # version with the uuid.
	    #
151
	    my $result =
152 153 154 155 156 157 158 159 160 161
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    "  from apt_profiles as i ".
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid and ".
			    "     v.version=i.version ".
			    "where i.uuid='$arg1'");
	    return undef
		if (! $result);
	    return BlessRow($class, $result->fetchrow_hashref())
		if ($result->numrows);
162

163 164 165 166 167 168 169
	    $result =
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    "  from apt_profile_versions as v ".
			    "left join apt_profiles as i on ".
			    "     v.profileid=i.profileid ".
			    "where v.uuid='$arg1' and ".
			    "      v.deleted is null");
170 171
	    return undef
		if (! $result || !$result->numrows);
172
	    return BlessRow($class, $result->fetchrow_hashref());
173 174 175
	}
	return undef;
    }
176 177 178
    elsif (!defined($arg3)) {
	if ($arg1 =~ /^\d+$/ && $arg2 =~ /^\d+$/) {
	    my $result =
179 180
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    "  from apt_profiles as i ".
181 182 183 184 185 186
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid ".
			    "where i.profileid='$arg1' and v.version='$arg2' ".
			    " and  v.deleted is null");
	    return undef
		if (! $result || !$result->numrows);
187

188 189 190 191
	    return BlessRow($class, $result->fetchrow_hashref());
	}
	elsif ($arg1 =~ /^[-\w]*$/ && $arg2 =~ /^([-\w\.\+]*):(\d+)$/) {
	    my $result =
192 193
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    " from apt_profiles as i ".
194 195 196 197 198 199
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid ".
			    "where i.pid='$arg1' and i.name='$1' and ".
			    "      v.version='$2'");
	    return undef
		if (! $result || !$result->numrows);
200

201 202 203 204
	    return BlessRow($class, $result->fetchrow_hashref());
	}
	elsif ($arg1 =~ /^[-\w]*$/ && $arg2 =~ /^[-\w\.\+]*$/) {
	    my $result =
205 206
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    "  from apt_profiles as i ".
207 208 209 210 211 212
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid and ".
			    "     v.version=i.version ".
			    "where i.pid='$arg1' and i.name='$arg2'");
	    return undef
		if (! $result || !$result->numrows);
213

214 215 216
	    return BlessRow($class, $result->fetchrow_hashref());
	}
	return undef;
217
    }
218 219 220 221
    else {
	if ($arg1 =~ /^[-\w]*$/ &&
	    $arg2 =~ /^[-\w\.\+]*$/ && $arg3 =~ /^\d+$/) {
	    my $result =
222 223
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    "  from apt_profiles as i ".
224 225 226 227 228 229
			    "left join apt_profile_versions as v on ".
			    "     v.profileid=i.profileid ".
			    "where i.pid='$arg1' and i.name='$arg2' and ".
			    "      v.version='$arg3' and v.deleted is null");
	    return undef
		if (!$result || !$result->numrows);
230

231 232 233 234
	    return BlessRow($class, $result->fetchrow_hashref());
	}
    }
    return undef;
235 236 237 238 239 240 241 242 243
}

AUTOLOAD {
    my $self  = $_[0];
    my $type  = ref($self) or croak "$self is not an object";
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
244 245
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
246 247 248 249 250 251 252 253 254
    }
    carp("No such slot '$name' field in class $type");
    return undef;
}

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

255
    $self->{'DBROW'} = undef;
256 257 258 259 260 261 262 263 264 265 266 267
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

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

268 269
    my $profileid = $self->profileid();
    my $version   = $self->version();
270 271
    
    my $query_result =
272 273
	DBQueryWarn("select * from apt_profile_versions ".
		    "where profileid='$profileid' and version='$version'");
274 275 276 277

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

278
    $self->{'DBROW'} = $query_result->fetchrow_hashref();
279 280 281 282 283 284 285

    return 0;
}

#
# Create a profile
#
286
sub Create($$$$$$)
287
{
288
    my ($class, $parent, $project, $creator, $argref, $usrerr_ref) = @_;
289 290 291 292

    my $name    = DBQuoteSpecial($argref->{'name'});
    my $pid     = $project->pid();
    my $pid_idx = $project->pid_idx();
293 294
    my $gid     = $project->pid();
    my $gid_idx = $project->pid_idx();
295 296 297 298 299 300
    my $uid     = $creator->uid();
    my $uid_idx = $creator->uid_idx();

    #
    # The pid/imageid has to be unique, so lock the table for the check/insert.
    #
301 302
    DBQueryWarn("lock tables apt_profiles write, apt_profile_versions write, ".
		"            emulab_indicies write")
303 304 305 306 307 308 309 310 311 312 313 314
	or return undef;

    my $query_result =
	DBQueryWarn("select name from apt_profiles ".
		    "where pid_idx='$pid_idx' and name=$name");

    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
	$$usrerr_ref = "Profile already exists in project!";
	return undef;
    }
    
315
    my $profileid = TBGetUniqueIndex("next_profile", undef, 1);
316 317
    my $puuid     = NewUUID();
    my $vuuid     = NewUUID();
318 319 320
    my $rspec     = DBQuoteSpecial($argref->{'rspec'});
    my $cquery    = "";
    my $vquery    = "";
321

322 323 324 325 326 327 328 329
    #
    # This part is common between the two tables.
    #
    $cquery .= "name=$name,profileid='$profileid'";
    $cquery .= ",pid='$pid',pid_idx='$pid_idx'";

    # And the versions table.
    $vquery  = $cquery;
330
    $vquery .= ",uuid='$vuuid',created=now()";
331 332 333 334 335 336 337 338
    $vquery .= ",creator='$uid',creator_idx='$uid_idx'";
    $vquery .= ",rspec=$rspec";

    # Set derived from pointer.
    if (defined($parent)) {
	$vquery .= ",parent_profileid=" . $parent->profileid();
	$vquery .= ",parent_version=" . $parent->version();
    }
339 340
    if (exists($argref->{'script'}) && $argref->{'script'} ne "") {
	$vquery .= ",script=" . DBQuoteSpecial($argref->{'script'});
341 342 343
	if (exists($argref->{'paramdefs'}) && $argref->{'paramdefs'} ne "") {
	    $vquery .= ",paramdefs=" . DBQuoteSpecial($argref->{'paramdefs'});
	}
344
    }
345

346
    # Back to the main table.
347
    $cquery .= ",uuid='$puuid'";
348
    $cquery .= ",public=1"
349
	if (exists($argref->{'public'}) && $argref->{'public'});
350
    $cquery .= ",listed=1"
351
	if (exists($argref->{'listed'}) && $argref->{'listed'});
352
    $cquery .= ",shared=1"
353
	if (exists($argref->{'shared'}) && $argref->{'shared'});
354 355
    $cquery .= ",topdog=1"
	if (exists($argref->{'topdog'}) && $argref->{'topdog'});
356

357 358 359 360 361 362 363 364 365
    # Create the main entry:
    if (! DBQueryWarn("insert into apt_profiles set $cquery")) {
	DBQueryWarn("unlock tables");
	tberror("Error inserting new apt_profiles record!");
	return undef;
    }
    # And the versions entry.
    if (! DBQueryWarn("insert into apt_profile_versions set $vquery")) {
	DBQueryWarn("delete from apt_profiles where profileid='$profileid'");
366
	DBQueryWarn("unlock tables");
367
	tberror("Error inserting new apt_profile_versions record!");
368 369 370 371 372 373
	return undef;
    }
    DBQueryWarn("unlock tables");
    return Lookup($class, $pid, $argref->{'name'});
}

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
#
# Create a new version of a profile.
#
sub NewVersion($$)
{
    my ($self, $creator) = @_;
    my $profileid   = $self->profileid();
    my $version     = $self->version();
    my $uid         = $creator->uid();
    my $uid_idx     = $creator->uid_idx();

    DBQueryWarn("lock tables apt_profiles write, ".
		"            apt_profile_versions write, ".
		"            apt_profile_versions as v write")
	or return undef;

    #
    # This might not be the head version, so have to find the
    # current max.
    #
    my $query_result =
	DBQueryWarn("select max(version) from apt_profile_versions ".
		    "where profileid='$profileid'");
    goto bad
	if (!$query_result || !$query_result->numrows);

    my ($newvers) = $query_result->fetchrow_array() + 1;

    #
    # Insert new version. The "current" version becomes this one.
    #
    goto bad
	if (! DBQueryWarn("insert into apt_profile_versions ".
			  "  (name,profileid,version,pid,pid_idx, ".
408 409
			  "   creator,creator_idx,updater,updater_idx, ".
			  "   created,uuid, ".
410 411
			  "   parent_profileid,parent_version,rspec, ".
			  "   script,paramdefs) ".
412
			  "select name,profileid,'$newvers',pid,pid_idx, ".
413 414
			  "  creator,creator_idx,'$uid','$uid_idx',".
			  "  now(),uuid(),'$profileid', ".
415
			  "  '$version',rspec,script,paramdefs ".
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
			  "from apt_profile_versions as v ".
			  "where v.profileid='$profileid' and ".
			  "      v.version='$version'"));
    if (! DBQueryWarn("update apt_profiles set version=$newvers ".
		      "where profileid='$profileid'")) {
	DBQueryWarn("delete from apt_profile_versions ".
		    "where profileid='$profileid' and version='$version'");
	goto bad;
    }
    DBQueryWarn("unlock tables");
    return APT_Profile->Lookup($profileid, $newvers);
  bad:
    DBQueryWarn("unlock tables");
    return undef;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
432 433 434 435 436 437 438 439 440
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid       = $self->pid();
    my $name      = $self->name();
441
    my $version   = $self->version();
Leigh B Stoller's avatar
Leigh B Stoller committed
442

443
    return "[Profile: $pid,$name:$version]";
Leigh B Stoller's avatar
Leigh B Stoller committed
444 445
}

446 447 448
#
# Perform some updates ...
#
449
sub UpdateVersion($$)
450 451 452 453 454 455 456
{
    my ($self, $argref) = @_;

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

457 458
    my $profileid = $self->profileid();
    my $version   = $self->version();
459

460
    my $query = "update apt_profile_versions set ".
461 462
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

463
    $query .= " where profileid='$profileid' and version='$version'";
464 465 466 467 468 469 470

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
sub UpdateAll($$)
{
    my ($self, $argref) = @_;

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

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

    my $query = "update apt_profile_versions set ".
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

    $query .= " where profileid='$profileid'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

492 493 494 495
#
# Perform some updates ...
#
sub UpdateMetaData($$)
496
{
497
    my ($self, $argref) = @_;
498 499 500 501 502

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

503
    my $profileid = $self->profileid();
504

505 506 507 508
    #
    # This is the only metadata we can update.
    #
    my %mods = ();
509
    foreach my $key ("listed", "shared", "public", "topdog") {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
	if (exists($argref->{$key})) {
	    $mods{$key} = $argref->{$key};
	}
    }
    my $query = "update apt_profiles set ".
	join(",", map("$_=" . DBQuoteSpecial($mods{$_}), keys(%mods)));

    $query .= " where profileid='$profileid'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

sub Delete($$)
{
    my ($self, $purge) = @_;
    my $profileid = $self->profileid();
529

530 531 532
    $purge = 0
	if (!defined($purge));
    
533
    DBQueryWarn("lock tables apt_profiles write, apt_profile_versions write, ".
534
		"     web_tasks write, apt_profile_favorites write")
535 536 537
	or return -1;

    if ($purge) {
538 539 540
	# Do not delete the web task here, it is needed to pass status
	# back to the web interface during profile creation. 
	DBQueryWarn("delete from apt_profile_versions ".
541 542
		    "where apt_profile_versions.profileid='$profileid'")
	    or goto bad;
543 544 545
    }
    else {
	# Set deleted on all of the versions.
546
	DBQueryWarn("update apt_profile_versions set deleted=now() ".
547 548
		    "where profileid='$profileid'")
	    or goto bad;
549 550 551 552 553
	# Delete any leftover webtasks.
	DBQueryWarn("delete web_tasks from apt_profile_versions ".
		    "left join web_tasks on ".
		    "   web_tasks.object_uuid=apt_profile_versions.uuid ".
		    "where apt_profile_versions.profileid='$profileid'");
554
    }
555 556 557
    DBQueryWarn("delete from apt_profile_favorites ".
		"where profileid='$profileid'")
	or goto bad;
558 559 560
    DBQueryWarn("delete from apt_profiles where profileid='$profileid'")
	or goto bad;
    
561
    DBQueryWarn("unlock tables");
562
    return 0;
563 564 565 566

  bad:
    DBQueryWarn("unlock tables");
    return -1;
567 568
}

569
#
570 571
# Delete a profile version, only allow it if it is the highest
# numbered version.
572
#
573
sub DeleteVersion($)
574 575 576
{
    my ($self) = @_;

577 578
    DBQueryWarn("lock tables apt_profile_versions write, ".
		"     apt_profiles write, web_tasks write")
579
	or return -1;
580

581 582
    my $profileid = $self->profileid();
    my $version   = $self->version();
583

584
    #
585 586
    # Need to know what profile becomes the head version. This will
    # always be the highest numbered undeleted profile.
587 588 589
    #
    my $query_result =
	DBQueryWarn("select max(version) from apt_profile_versions ".
590 591
		    "where profileid='$profileid' and version!=${version} ".
		    "      and deleted is null");
592 593
    goto bad
	if (!$query_result || !$query_result->numrows);
594

595 596
    my ($newhead) = $query_result->fetchrow_array();

597 598 599 600 601 602 603
    # Delete leftover webtask.
    DBQueryWarn("delete web_tasks from apt_profile_versions ".
		"left join web_tasks on ".
		"   web_tasks.object_uuid=apt_profile_versions.uuid ".
		"where apt_profile_versions.profileid='$profileid' and ".
		"      apt_profile_versions.version='$version'");

604
    goto bad
605
	if (!DBQueryWarn("update apt_profile_versions set deleted=now() ".
606 607
			 "where profileid='$profileid' and ".
			 "      version='$version'"));
608

609
    goto bad
610
	if (!DBQueryWarn("update apt_profiles set version=$newhead ".
611 612 613
			 "where profileid='$profileid' and ".
			 "      version='$version'"));
    DBQueryWarn("unlock tables");
614
    return 0;
615 616 617
  bad:
    DBQueryWarn("unlock tables");
    return -1;
618 619
}

620 621 622 623
#
# Condomize a profile rspec by inserting the necessary firewall section
# to each of the nodes.
#
624
sub CheckFirewall($$)
625
{
626
    my ($self, $condomize) = @_;
627 628 629 630 631 632 633 634 635 636 637

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

    my $rspec = GeniXML::Parse($self->rspec());
    if (! defined($rspec)) {
	print STDERR "Could not parse rspec\n";
	return undef;
    }
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
	my @routable_control_ip =
	    GeniXML::FindNodesNS("n:routable_control_ip",
				 $ref,
				 $GeniXML::EMULAB_NS)->get_nodelist();
	my $virtualization_type = GeniXML::GetVirtualizationSubtype($ref);
	#
	# If a XEN container but not a routable IP, then use the basic
	# rules instead of closed, so that ssh is allowed in on the
	# alternate port. That is the only real difference between basic
	# and closed.
	#
	my $style = "closed";
	if (defined($virtualization_type) &&
	    $virtualization_type eq "emulab-xen" && !@routable_control_ip) {
	    $style = "basic";
	}
	
655 656 657 658 659 660 661
	if ($condomize) {
	    #
	    # No settings is easy; wrap it tight.
	    #
	    if (!GeniXML::HasFirewallSettings($ref)) {
		my $firewall = GeniXML::AddElement("firewall", $ref,
						   $GeniXML::EMULAB_NS);
662
		GeniXML::SetText("style", $firewall, $style);
663 664 665 666 667 668 669 670 671
		next;
	    }
	    #
	    # Make sure the existing section has a reasonable setting.
	    #
	    my $settings = GeniXML::FindNodesNS("n:firewall", $ref,
						$GeniXML::EMULAB_NS)->pop();
	    my $style = GeniXML::GetText("style", $settings);
	    if (!defined($style) || $style ne "basic" || $style ne "closed") {
672
		GeniXML::SetText("style", $settings, $style);
673
	    }
674 675
	}
	#
676 677
	# Quick pass over the exceptions to see if we need to substitute
	# the callers IP address.
678
	#
679 680 681 682 683 684
	foreach my $exception (GeniXML::FindNodesNS("n:firewall/n:exception",
				$ref, $GeniXML::EMULAB_NS)->get_nodelist()) {
	    my $ip = GeniXML::GetText("ip", $exception);
	    if (defined($ip) && $ip eq "myip" && exists($ENV{'REMOTE_ADDR'})) {
		GeniXML::SetText("ip", $exception, $ENV{'REMOTE_ADDR'});
	    }
685 686 687 688
	}
    }
    return GeniXML::Serialize($rspec);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
689 690 691 692 693 694 695

#
# Lock and Unlock
#
sub Lock($)
{
    my ($self) = @_;
696
    my $profileid = $self->profileid();
Leigh B Stoller's avatar
Leigh B Stoller committed
697 698 699 700 701

    return -1
	if (!DBQueryWarn("lock tables apt_profiles write"));

    my $query_result =
702 703
	DBQueryWarn("update apt_profiles set locked=now(),locker_pid='$PID' " .
		    "where profileid='$profileid' and locked is null");
Leigh B Stoller's avatar
Leigh B Stoller committed
704 705 706 707 708 709 710

    if (! $query_result ||
	$query_result->numrows == 0) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables");
711
    $self->{'DBROW'}->{'locked'} = time();
Leigh B Stoller's avatar
Leigh B Stoller committed
712 713 714 715 716 717
    return 0;
}

sub Unlock($)
{
    my ($self) = @_;
718
    my $profileid = $self->profileid();
Leigh B Stoller's avatar
Leigh B Stoller committed
719 720

    return -1
721 722 723 724 725 726 727 728 729
	if (! DBQueryWarn("update apt_profiles set ".
			  "   locked=null,locker_pid=0 ".
			  "where profileid='$profileid'"));
    
    $self->{'DBROW'}->{'locked'} = 0;
    return 0;
}

#
730 731 732
# Update the disk image inside a profile. We update the URL for the
# specified node, and if $all is set, we change all nodes with the
# same original disk image as the specified node.
733
#
734
sub UpdateDiskImage($$@)
735
{
736
    my ($self, $node_id, $newimage, $all) = @_;
737 738 739 740 741
    my $rspec = GeniXML::Parse($self->rspec());
    if (! defined($rspec)) {
	print STDERR "UpdateDiskImage: Could not parse rspec\n";
	return -1;
    }
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
    #
    # Find all the nodes we want to update, might be just the one or
    # all with the same image.
    #
    my @nodes = ();
    my $node;

    # First find the specified node.
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	if (GeniXML::GetVirtualId($ref) eq $node_id) {
	    $node = $ref;
	    last;
	}
    }
    if (!defined($node)) {
	print STDERR "$node_id not in rspec\n";
	return -1;
    }
    if ($all) {
	#
	# Pull out the disk url/urn of the specified node.
	#
764
	my $Odiskref = GeniXML::GetDiskImage($node);
765 766
	my $image_urn;
	my $image_url;
767 768 769
	if (defined($Odiskref)) {
	    $image_url = GeniXML::GetText("url", $Odiskref);
	    $image_urn = GeniXML::GetText("name", $Odiskref);
770 771 772 773 774 775 776 777 778 779 780 781 782
	    if (defined($image_url) || defined($image_urn)) {
		# Watch for url in the name, flipflop. 
		if (defined($image_urn) && $image_urn =~ /^http/) {
		    $image_url = $image_urn;
		    $image_urn = undef;
		}
	    }
	}
	#
	# Now find all nodes using the same disk urn/url and change.
	#
	foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	    my $diskref   = GeniXML::GetDiskImage($ref);
783 784 785 786 787 788 789 790 791
	    #
	    # If the both this node and the original node did not
	    # specify a disk image, then we update it. 
	    #
	    if (!defined($diskref)) {
		push(@nodes, $ref)
		    if (!defined($Odiskref));
		next;
	    }
792 793 794 795 796 797 798 799 800 801 802 803
	    my $this_url = GeniXML::GetText("url", $diskref);
	    my $this_urn = GeniXML::GetText("name", $diskref);
	    next
		if (!(defined($image_url) || defined($image_urn)));

	    # Watch for url in the name, flipflop. 
	    if (defined($this_urn) && $this_urn =~ /^http/) {
		$this_url = $this_urn;
		$this_urn = undef;
	    }
	    if (defined($image_url)) {
		push(@nodes, $ref)
804
		    if ((defined($this_url) && $this_url eq $image_url));
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
	    }
	    else {
		push(@nodes, $ref)
 		    if (defined($this_urn) && $this_urn eq $image_urn);
	    }
	}
    }
    else {
	@nodes = ($node);
    }
    if (!@nodes) {
	print STDERR "Could not find any nodes to update disk image\n";
	return -1;
    }
    foreach my $node (@nodes) {
820
	GeniXML::SetDiskImage($node, $newimage);
821
    }
822 823 824 825 826 827 828
    if ($self->UpdateVersion({"rspec" => GeniXML::Serialize($rspec)})) {
	print STDERR "UpdateDiskImage: Could not update rspec\n";
	return -1;
    }
    return 0;
}

829
# Total nonsense, to be thrown away.
830
sub CheckNodeConstraints($$$)
831
{
832
    my ($self, $default_aggregate_urn, $pmsg) = @_;
833
    my $cloudwww = "www.utah.cloudlab.us";
834
    my $cloudurn = "urn:publicid:IDN+utah.cloudlab.us+authority+cm";
835 836 837 838 839 840 841 842 843
    require URI;

    my $rspec = GeniXML::Parse($self->rspec());
    if (! defined($rspec)) {
	print STDERR "Could not parse rspec\n";
	return -1;
    }
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	my $client_id = GetVirtualId($ref);
844
	my $virtualization_type = GeniXML::GetVirtualizationSubtype($ref);
845 846 847 848 849
	my $manager_urn = GetManagerId($ref);
	if (! defined($manager_urn)) {
	    $manager_urn = $default_aggregate_urn;
	}
	my $iscloudlab = ($manager_urn eq $cloudurn ? 1 : 0);
850 851 852 853 854 855 856

	if (defined($virtualization_type) && $iscloudlab &&
	    $virtualization_type eq "emulab-xen") {
	    $$pmsg = "Node '$client_id' is a XEN VM, which is ".
		"not supported on the Cloudlab cluster";
	    return -1;
	}
857 858 859 860
	my $diskref   = GeniXML::GetDiskImage($ref);
	next
	    if (!defined($diskref));
	my $image_url = GeniXML::GetText("url", $diskref);
861
	my $image_urn = GeniXML::GetText("name", $diskref);
862
	next
863 864
	    if (!(defined($image_url) || defined($image_urn)));

865
	# Watch for url in the name, flipflop. 
Leigh B Stoller's avatar
Leigh B Stoller committed
866
	if (defined($image_urn) && $image_urn =~ /^http/) {
867 868 869 870
	    $image_url = $image_urn;
	    $image_urn = undef;
	}

871
	if (defined($image_urn)) {
872 873
	    if ($image_urn =~ /UBUNTU14\-10\-64\-OS/ ||
		$image_urn =~ /UBUNTU15\-04\-64\-OS/) {
Leigh B Stoller's avatar
Leigh B Stoller committed
874 875
		return 0;
	    }
876
	    elsif ($iscloudlab &&
877
		   !($image_urn =~ /ARM/i || $image_urn =~ /HPC/i)) {
878
		$$pmsg = "The disk image specified for node '$client_id' ".
879
		    "will not run on the Cloudlab Utah cluster";
880 881
		return -1;
	    }
882
	    elsif (!$iscloudlab && $image_urn =~ /ARM/i) {
883
		$$pmsg = "The disk image specified for node '$client_id' ".
884
		    "will only run on the Cloudlab Utah cluster";
885 886 887 888 889
		return -1;
	    }
	}
	next if
	    (!defined($image_url));
890 891 892 893 894 895 896 897 898 899 900 901

	# Get the hostname for the image URL.
	my $uri = URI->new($image_url);
	if (!defined($uri)) {
	    print STDERR "Could not parse $image_url\n";
	    return -1;
	}
	my $image_host = $uri->host();

	if ($iscloudlab) {
	    if ($image_host ne $cloudwww) {
		$$pmsg = "The disk image specified for node '$client_id' ".
902
		    "will not run on the Cloudlab Utah cluster";
903 904 905 906 907 908 909 910 911 912 913 914 915 916
		return -1;
	    }
	}
	else {
	    if ($image_host eq $cloudwww) {
		$$pmsg = "The disk image specified for node '$client_id' ".
		    "will not run on cluster you selected";
		return -1;
	    }
	}
    }
    return 0;
}

917
#
918
# Check dataset validity.
919
#
920
sub CheckDatasets($$)
921
{
922
    my ($xml, $pmsg) = @_;
923
    
924 925 926 927 928 929
    my $rspec = GeniXML::Parse($xml);
    if (! defined($rspec)) {
	print STDERR "CheckDatasets: Could not parse rspec\n";
	return -1;
    }
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
930 931
	my $manager_urn = GetManagerId($ref);	
	
932 933 934
	foreach my $blockref (GeniXML::FindNodesNS("n:blockstore",
						   $ref,
				   $GeniXML::EMULAB_NS)->get_nodelist()) {
935 936
	    my $dataset_id  = GeniXML::GetText("dataset", $blockref);
	    my $class       = GeniXML::GetText("class", $blockref);
937 938 939 940 941 942

	    #
	    # We only care about datasets here, we let the backend
	    # do the error checking on ephemeral blockstores.
	    #
	    next
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
		if (!defined($dataset_id));

	    if (!defined($class)) {
		$class = "remote";
	    }
	    elsif ($class ne "local" && $class ne "remote") {
		$$pmsg = "class must be local or remote";
		return 1;
	    }

	    #
	    # If the dataset is local and its a URL, then make sure its
	    # a valid URL.
	    #
	    if ($class eq "local" && $dataset_id =~ /^(http|https):/) {
		if (!TBcheck_dbslot($dataset_id, "virt_nodes", "osname",
				TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)){
		    $$pmsg = "Invalid url for dataset";
		    return 1;
		}
		next;
	    }
	    if (!GeniHRN::IsValid($dataset_id)) {
		$$pmsg = "Persistent dataset is not a valid URN";
967 968
		return 1;
	    }
969
	    my $dataset_urn = GeniHRN->new($dataset_id);
970
	    
971
	    #
972 973 974
	    # For leases, the domain of the dataset has to match the
	    # domain of aggregate, but for image backed datasets, we now
	    # to transfer them as needed.
975
	    #
976 977 978
	    if ($class ne "local") {
		if (defined($manager_urn)) {
		    $manager_urn = GeniHRN->new($manager_urn);
979
		
980 981 982 983 984 985 986 987 988 989
		    if ($manager_urn->domain() ne $dataset_urn->domain()) {
			$$pmsg = "$dataset_urn is not located on $manager_urn";
			return 1;
		    }
		}
		#
		# Not all backends have blockstore (lease) support.
		#
		if (!APT_Dataset::ValidBlockstoreBackend($dataset_urn)) {
		    $$pmsg = "Dataset $dataset_urn is not on a valid aggregate";
990 991 992
		    return 1;
		}
	    }
993
	    #
994 995 996
	    # So the rspec will refer to the dataset by the remote URN.
	    # And it might be a classic dataset (so not in the apt_datasets
	    # table). We want to be able to handle either of these cases.
997
	    #
998
	    my $dataset = APT_Dataset->LookupByRemoteURN($dataset_urn);
999
	    if (!defined($dataset)) {
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
		#
		# Local image backed dataset or lease.
		#
		if ($dataset_urn->domain() eq $OURDOMAIN) {
		    my $pid = $dataset_urn->project();
		    my $id  = $dataset_urn->id();

		    if ($dataset_urn->type() eq "imdataset") {
			$dataset = Image->Lookup($pid, $id);
			if ($dataset && !$dataset->isdataset()) {
			    $$pmsg = "$dataset_urn is an image not a dataset ";
			    return 1;
			}
1013
		    }
1014 1015
		    else {
			$dataset = Lease->Lookup($pid, $id);
1016
		    }
1017
		}
1018
	    }
1019 1020 1021 1022
	    if (!defined($dataset)) {
		$$pmsg = "Persistent dataset '$dataset_urn' does not exist";
		return 1;
	    }
1023 1024 1025 1026 1027
	}
    }
    return 0;
}

1028 1029 1030
#
# Set the component_manager_urn for the sites.
#
1031
sub SetSites($$$$$$)
1032
{
1033 1034 1035 1036
    my ($prspecstr, $sitemap, $default_aggregate_urn, $paggregate_urns,
	$pneedstitcher, $perrmsg) = @_;
    my %interface_map   = ();
    my %aggregates      = ();
1037 1038 1039 1040 1041 1042 1043 1044

    my $rspec = GeniXML::Parse($$prspecstr);
    if (! defined($rspec)) {
	$$perrmsg = "Could not parse rspec\n";
	return -1;
    }
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	my $client_id   = GetVirtualId($ref);
1045
	my $manager_urn = GetManagerId($ref);	
1046 1047
	my $site_id     = GeniXML::GetJacksSiteId($ref);

1048 1049 1050 1051 1052 1053
	# A node can be bound in the rspec.
	if (defined($manager_urn)) {
	    if (!GeniHRN::IsValid($manager_urn)) {
		$$perrmsg = "$client_id has an invalid manager URN";
		return 1;
	    }
1054
	}
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	# Or there is a site tag, and a site mapping for it.
	elsif (defined($site_id)) {
	    if (defined($sitemap)) {
		my $site_mid = "site:" . $site_id;

		if (!exists($sitemap->{$site_mid})) {
		    $$perrmsg =
			"No site mapping for node $client_id ($site_id)";
		    return -1;
		}
		$manager_urn = $sitemap->{$site_mid};
	    }
	    else {
		$manager_urn = $default_aggregate_urn;
	    }
	    if (!GeniHRN::IsValid($manager_urn)) {
		$$perrmsg = "$site_id has an invalid manager URN";
		return 1;
	    }
	    GeniXML::SetManagerId($ref, $manager_urn);
	    GeniXML::SetJacksSiteManagerId($ref, $manager_urn);
	}
	# Else use the default aggregate.
	else {
	    $manager_urn = $default_aggregate_urn;
	    
	    GeniXML::SetManagerId($ref, $manager_urn);
1082
	}
1083
	$aggregates{$manager_urn} = $manager_urn;
1084 1085 1086 1087 1088 1089 1090 1091

	#
	# Get all of the interfaces, we need those for the links, so
	# we can add the managers to them, according to site id.
	#
	foreach my $iref (GeniXML::FindNodes("n:interface",
					     $ref)->get_nodelist()) {
	    my $client_id = GeniXML::GetInterfaceId($iref);
1092
	    $interface_map{$client_id} = $manager_urn;
1093
	}
1094
    }
1095 1096 1097
    foreach my $ref (GeniXML::FindNodes("n:link", $rspec)->get_nodelist()) {
	my %linksites = ();

1098 1099 1100 1101 1102
	foreach my $iref (GeniXML::FindNodes("n:interface_ref",
					     $ref)->get_nodelist()) {
	    my $client_id = GeniXML::GetInterfaceId($iref);
	    next
		if (!exists($interface_map{$client_id}));
1103

1104 1105 1106 1107 1108
	    my $manager_urn = $interface_map{$client_id};
	    
	    GeniXML::AddManagerToLink($ref, $manager_urn)
		if (!exists($linksites{$manager_urn}));
	    $linksites{$manager_urn} = 1;
1109
	}
1110 1111 1112 1113 1114
	# Two clusters only (point to point links and lans).
	if (keys(%linksites) > 2) {
	    $$perrmsg = "Multisite links/lans may span at most two clusters";
	    return 1;
	}
1115 1116 1117 1118 1119
	# if more then one site for a link, must use the stitcher.
	$$pneedstitcher = 1
	    if (keys(%linksites) > 1);
    }
    $$prspecstr = GeniXML::Serialize($rspec);
1120
    @$paggregate_urns = keys(%aggregates);
1121 1122 1123
    return 0;
}

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
#
# Encrypt blocks.
#
sub EncryptBlocks($$$)
{
    my ($pxml, $certificate, $pmsg) = @_;
    my @encrypt = ();
    
    my $rspec = GeniXML::Parse($$pxml);
    if (! defined($rspec)) {
	print STDERR "EncryptBlocks: Could not parse rspec\n";
	return -1;
    }
1137 1138 1139 1140 1141 1142 1143 1144
    foreach my $encref (GeniXML::FindNodesNS("n:encrypt", $rspec,
				    $GeniXML::EMULAB_NS)->get_nodelist()) {
	my $text = $encref->textContent();
	next
	    if (!$text || $text eq "");
	my $encrypted = GeniXML::GetText("encrypted", $encref);
	next
	    if ($encrypted);
1145
	    
1146 1147 1148
	push(@encrypt, $encref);
    }
    foreach my $encref (GeniXML::FindNodesNS("n:password", $rspec,
1149
				   $GeniXML::EMULAB_NS)->get_nodelist()) {
1150 1151 1152
	my $plaintext = substr(TBGenSecretKey(), 0, 12);
	$encref->appendText($plaintext);
	push(@encrypt, $encref);
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    }
    if (@encrypt) {
	my $certname = $certificate->WriteToFile();
	if (!defined($certname)) {
	    $$pmsg = "Could not encrypt blocks; not able to write certificate";
	    return -1;
	}
	foreach my $ref (@encrypt) {
	    my $tempname = mktemp("/tmp/encrypt.XXXXXX");
	    emutil::PipeCommand("/usr/bin/openssl smime ".
				"-encrypt -outform PEM ".
				"-out $tempname ".
				"-aes256 $certname",
				$ref->textContent(), $pmsg);
	    if ($?) {
		return -1;
	    }
	    my $encrypted = `cat $tempname`;
	    $ref->setAttribute("encrypted", "true");
	    $ref->removeChildNodes();
	    $ref->appendText($encrypted);
	    unlink($tempname);
	}
	$$pxml = GeniXML::Serialize($rspec);
    }
    return 0;
}

1181 1182 1183 1184 1185 1186 1187