APT_Profile.pm.in 53.7 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2017 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 WebTask;
49
use emdb;
50
use APT_Dataset;
51
use GeniXML;
52
use GeniHRN;
53
use libtestbed;
54
use Project;
55
use Lease;
56 57
use English;
use Data::Dumper;
58
use File::Basename;
59
use File::Temp qw(tempfile :mktemp tmpnam :POSIX);
60
use URI::URL;
61 62 63 64 65
use overload ('""' => 'Stringify');

# Configure variables
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
66 67
my $OURDOMAIN     = "@OURDOMAIN@";
my $MYURN         = "urn:publicid:IDN+${OURDOMAIN}+authority+cm";
68
my $MAINSITE      = @TBMAINSITE@;
Leigh B Stoller's avatar
Leigh B Stoller committed
69
my $CONVERTER     = "$TB/bin/rspec2genilib";
70

71 72 73 74 75 76 77 78
# Concat id/vers.
sub versid($)
{
    my ($self) = @_;

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

Leigh B Stoller's avatar
Leigh B Stoller committed
79 80 81 82 83 84 85 86
# Concat name/vers.
sub versname($)
{
    my ($self) = @_;

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

87 88 89 90 91 92 93
sub BlessRow($$)
{
    my ($class, $row) = @_;
    
    my $self           = {};
    $self->{'DBROW'}   = $row;
    bless($self, $class);
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

    #
    # Grab the webtask. Backwards compat mode, see if there is one associated
    # with the object, use that. Otherwise create a new one.
    #
    my $webtask;
    
    if (defined($self->webtask_id())) {
	$webtask = WebTask->Lookup($self->webtask_id());
    }
    if (!defined($webtask)) {
	$webtask = WebTask->LookupByObject($self->uuid());
	if (!defined($webtask)) {
	    $webtask = WebTask->Create();
	    return undef
		if (!defined($webtask));
	}
	my $profileid  = $self->profileid();
	my $webtask_id = $webtask->task_id();
	
	DBQueryWarn("update apt_profiles set webtask_id='$webtask_id' ".
		    "where profileid='$profileid'")
	    or return undef;
    }
    $self->{'WEBTASK'} = $webtask;
119 120 121 122 123 124 125 126 127 128 129 130 131

    #
    # If not deleted, then grab the image info records.
    #
    if (!defined($self->deleted())) {
	my $images;
	return undef
	    if (APT_Profile::ImageInfo->LookupForProfile($self, \$images));
	$self->{'IMAGES'} = $images;
    }
    else {
	$self->{'IMAGES'} = {};
    }
132 133
    return $self;
}
134 135

#
136
# Lookup. 
137
#
138
sub Lookup($$;$$)
139
{
140
    my ($class, $arg1, $arg2, $arg3) = @_;
141 142

    #
143 144
    # A single arg is either an index or "pid,profile[:version]" or
    # "pid/profile[:version]" string.
145 146 147
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
148
	    my $result =
149 150 151
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
152
			    " from apt_profiles as i ".
153 154 155 156 157 158 159 160
			    "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());
161 162
	}
	elsif ($arg1 =~ /^([-\w]*),([-\w\.\+]*)$/ ||
163 164
		$arg1 =~ /^([-\w]*)\/([-\w\.\+]*)$/) {
	    my $result =
165 166 167
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
168
			    " from apt_profiles as i ".
169 170 171 172 173 174 175 176 177 178 179 180
			    "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 =
181 182 183
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
184
			    " from apt_profiles as i ".
185 186 187 188 189 190 191 192
			    "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())
193 194
	}
	elsif ($arg1 =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
195 196 197 198 199
	    #
	    # First look to see if the uuid is for the profile itself,
	    # which means current version. Otherwise look for a
	    # version with the uuid.
	    #
200
	    my $result =
201 202 203
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
204 205 206 207 208 209 210 211 212
			    "  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);
213

214
	    $result =
215 216 217
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
218 219 220 221 222
			    "  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");
223 224
	    return undef
		if (! $result || !$result->numrows);
225
	    return BlessRow($class, $result->fetchrow_hashref());
226 227 228
	}
	return undef;
    }
229 230 231
    elsif (!defined($arg3)) {
	if ($arg1 =~ /^\d+$/ && $arg2 =~ /^\d+$/) {
	    my $result =
232 233 234
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
235
			    "  from apt_profiles as i ".
236 237 238 239 240 241
			    "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);
242

243 244 245 246
	    return BlessRow($class, $result->fetchrow_hashref());
	}
	elsif ($arg1 =~ /^[-\w]*$/ && $arg2 =~ /^([-\w\.\+]*):(\d+)$/) {
	    my $result =
247 248 249
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
250
			    " from apt_profiles as i ".
251 252 253 254 255 256
			    "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);
257

258 259 260 261
	    return BlessRow($class, $result->fetchrow_hashref());
	}
	elsif ($arg1 =~ /^[-\w]*$/ && $arg2 =~ /^[-\w\.\+]*$/) {
	    my $result =
262 263 264
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid, ".
                            "    i.disabled as profile_disabled, ".
                            "    i.nodelete as profile_nodelete ".
265
			    "  from apt_profiles as i ".
266 267 268 269 270 271
			    "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);
272

273 274 275
	    return BlessRow($class, $result->fetchrow_hashref());
	}
	return undef;
276
    }
277 278 279 280
    else {
	if ($arg1 =~ /^[-\w]*$/ &&
	    $arg2 =~ /^[-\w\.\+]*$/ && $arg3 =~ /^\d+$/) {
	    my $result =
281 282
		DBQueryWarn("select i.*,v.*,i.uuid as profile_uuid ".
			    "  from apt_profiles as i ".
283 284 285 286 287 288
			    "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);
289

290 291 292 293
	    return BlessRow($class, $result->fetchrow_hashref());
	}
    }
    return undef;
294
}
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
#
# Lookup by repo key.
#
sub LookupByRepoKey($$)
{
    my ($class, $token) = @_;

    return undef
	if ($token !~ /^\w+$/);

    my $query_result =
	DBQueryWarn("select uuid from apt_profile_versions ".
		    "where repokey='$token'");

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

    my ($uuid) = $query_result->fetchrow_array();
    return Lookup($class, $uuid);
}
315 316 317 318 319 320 321 322

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.
323 324
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
325 326 327 328
    }
    carp("No such slot '$name' field in class $type");
    return undef;
}
329 330 331 332 333 334 335 336 337 338 339
sub images($;$)
{
    my ($self, $client_id) = @_;
    if (!defined($client_id)) {
	return $self->{'IMAGES'};
    }
    elsif (exists($self->{'IMAGES'}->{$client_id})) {
	return $self->{'IMAGES'}->{$client_id};
    }
    return undef;
}
340 341 342 343 344

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

345 346
    $self->{'WEBTASK'} = undef;
    $self->{'DBROW'}   = undef;
347
    $self->{'IMAGES'}  = undef;
348 349
}

350 351 352 353 354
sub IsRepoBased($) {
    my ($self) = @_;

    return (defined($self->repourl()) ? 1 : 0);
}
355
sub webtask($)  { return $_[0]->{'WEBTASK'}; }
356

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
# A profile is disabled if version is disabled or entire profile is disabled
sub isDisabled($)
{
    my ($self) = @_;

    return ($self->disabled() || $self->profile_disabled() ? 1 : 0);
}
# Ditto nodelete.
sub isLocked($)
{
    my ($self) = @_;

    return ($self->nodelete() || $self->profile_nodelete() ? 1 : 0);
}

372 373 374 375 376 377 378 379 380 381
#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

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

382 383
    my $profileid = $self->profileid();
    my $version   = $self->version();
384 385
    
    my $query_result =
386 387
	DBQueryWarn("select * from apt_profile_versions ".
		    "where profileid='$profileid' and version='$version'");
388 389 390 391

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

392
    $self->{'DBROW'} = $query_result->fetchrow_hashref();
393 394 395 396 397 398 399

    return 0;
}

#
# Create a profile
#
400
sub Create($$$$$$)
401
{
402
    my ($class, $parent, $project, $creator, $argref, $usrerr_ref) = @_;
403 404 405 406

    my $name    = DBQuoteSpecial($argref->{'name'});
    my $pid     = $project->pid();
    my $pid_idx = $project->pid_idx();
407 408
    my $gid     = $project->pid();
    my $gid_idx = $project->pid_idx();
409 410
    my $uid     = $creator->uid();
    my $uid_idx = $creator->uid_idx();
411 412 413 414 415
    my $puuid   = NewUUID();
    my $vuuid   = NewUUID();
    my $webtask = WebTask->Create();
    return undef
	if (!defined($webtask));
416 417 418 419

    #
    # The pid/imageid has to be unique, so lock the table for the check/insert.
    #
420 421 422 423 424 425
    if (!DBQueryWarn("lock tables apt_profiles write, ".
		     "     apt_profile_versions write, ".
		     "     emulab_indicies write")) {
	$webtask->Delete();
	return undef;
    }
426 427 428 429 430 431
    my $query_result =
	DBQueryWarn("select name from apt_profiles ".
		    "where pid_idx='$pid_idx' and name=$name");

    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
432
	$webtask->Delete();
433 434 435 436
	$$usrerr_ref = "Profile already exists in project!";
	return undef;
    }
    
437
    my $profileid = TBGetUniqueIndex("next_profile", undef, 1);
438 439
    my $rspec     = DBQuoteSpecial($argref->{'rspec'})
	if (exists($argref->{'rspec'}));
440 441
    my $cquery    = "";
    my $vquery    = "";
442

443 444 445 446 447
    #
    # This part is common between the two tables.
    #
    $cquery .= "name=$name,profileid='$profileid'";
    $cquery .= ",pid='$pid',pid_idx='$pid_idx'";
448
    $cquery .= ",gid='$gid',gid_idx='$gid_idx'";
449 450 451

    # And the versions table.
    $vquery  = $cquery;
452
    $vquery .= ",uuid='$vuuid',created=now()";
453
    $vquery .= ",creator='$uid',creator_idx='$uid_idx'";
454
    $vquery .= ",rspec=$rspec" if (defined($rspec));
455 456 457 458 459 460

    # Set derived from pointer.
    if (defined($parent)) {
	$vquery .= ",parent_profileid=" . $parent->profileid();
	$vquery .= ",parent_version=" . $parent->version();
    }
461 462
    if (exists($argref->{'script'}) && $argref->{'script'} ne "") {
	$vquery .= ",script=" . DBQuoteSpecial($argref->{'script'});
463 464 465
	if (exists($argref->{'paramdefs'}) && $argref->{'paramdefs'} ne "") {
	    $vquery .= ",paramdefs=" . DBQuoteSpecial($argref->{'paramdefs'});
	}
466
    }
467 468 469 470
    if (exists($argref->{'repourl'}) && $argref->{'repourl'} ne "") {
	$vquery .= ",repourl="  . DBQuoteSpecial($argref->{'repourl'});
	$vquery .= ",reponame=" . DBQuoteSpecial($argref->{'reponame'});
	$vquery .= ",repohash=" . DBQuoteSpecial($argref->{'repohash'});
471
	$vquery .= ",repokey="  . DBQuoteSpecial($argref->{'repokey'});
472
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
473 474 475 476 477
    if (exists($argref->{'portal_converted'}) &&
	$argref->{'portal_converted'} ne "") {
	$vquery .= ",portal_converted="  .
	    DBQuoteSpecial($argref->{'portal_converted'});
    }
478

479
    # Back to the main table.
480
    $cquery .= ",uuid='$puuid'";
481
    $cquery .= ",webtask_id="  . DBQuoteSpecial($webtask->task_id());
482
    $cquery .= ",public=1"
483
	if (exists($argref->{'public'}) && $argref->{'public'});
484
    $cquery .= ",listed=1"
485
	if (exists($argref->{'listed'}) && $argref->{'listed'});
486
    $cquery .= ",shared=1"
487
	if (exists($argref->{'shared'}) && $argref->{'shared'});
488 489
    $cquery .= ",topdog=1"
	if (exists($argref->{'topdog'}) && $argref->{'topdog'});
490

491 492 493 494
    # Create the main entry:
    if (! DBQueryWarn("insert into apt_profiles set $cquery")) {
	DBQueryWarn("unlock tables");
	tberror("Error inserting new apt_profiles record!");
495
	$webtask->Delete();
496 497 498 499 500
	return undef;
    }
    # And the versions entry.
    if (! DBQueryWarn("insert into apt_profile_versions set $vquery")) {
	DBQueryWarn("delete from apt_profiles where profileid='$profileid'");
501
	DBQueryWarn("unlock tables");
502
	tberror("Error inserting new apt_profile_versions record!");
503
	$webtask->Delete();
504 505 506 507 508 509
	return undef;
    }
    DBQueryWarn("unlock tables");
    return Lookup($class, $pid, $argref->{'name'});
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
#
# 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, ".
544
			  "   gid,gid_idx, ".
545 546
			  "   creator,creator_idx,updater,updater_idx, ".
			  "   created,uuid, ".
547
			  "   parent_profileid,parent_version,rspec, ".
548 549
			  "   script,paramdefs,reponame,repourl, ".
			  "   portal_converted) ".
550
			  "select name,profileid,'$newvers',pid,pid_idx, ".
551
			  "  gid,gid_idx, ".
552 553
			  "  creator,creator_idx,'$uid','$uid_idx',".
			  "  now(),uuid(),'$profileid', ".
554
			  "  '$version',rspec,script,paramdefs, ".
555
			  "  reponame,repourl,portal_converted ".
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
			  "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
572 573 574 575 576 577 578 579 580
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid       = $self->pid();
    my $name      = $self->name();
581
    my $version   = $self->version();
Leigh B Stoller's avatar
Leigh B Stoller committed
582

583
    return "[Profile: $pid,$name:$version]";
Leigh B Stoller's avatar
Leigh B Stoller committed
584 585
}

586 587 588
#
# Perform some updates ...
#
589
sub UpdateVersion($$)
590 591 592 593 594 595 596
{
    my ($self, $argref) = @_;

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

597 598
    my $profileid = $self->profileid();
    my $version   = $self->version();
599

600
    my $query = "update apt_profile_versions set ".
601 602 603 604
	join(",", map("$_=" .
		      (defined($argref->{$_}) ?
		       DBQuoteSpecial($argref->{$_}) : "NULL"),
		      keys(%{$argref})));
605

606
    $query .= " where profileid='$profileid' and version='$version'";
607 608 609 610 611 612 613

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

    return Refresh($self);
}

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
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);
}

635 636 637 638
#
# Perform some updates ...
#
sub UpdateMetaData($$)
639
{
640
    my ($self, $argref) = @_;
641 642 643 644 645

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

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

648 649 650 651
    #
    # This is the only metadata we can update.
    #
    my %mods = ();
652
    foreach my $key ("listed", "shared", "public", "topdog") {
653 654 655 656
	if (exists($argref->{$key})) {
	    $mods{$key} = $argref->{$key};
	}
    }
657 658 659
    return 0
	if (!keys(%mods));
    
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
    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();
675

676 677 678
    $purge = 0
	if (!defined($purge));
    
679
    DBQueryWarn("lock tables apt_profiles write, apt_profile_versions write, ".
Leigh B Stoller's avatar
Leigh B Stoller committed
680 681
		"     web_tasks write, apt_profile_favorites write, ".
		"     apt_profile_images write")
682 683 684
	or return -1;

    if ($purge) {
685 686 687
	# 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 ".
688 689
		    "where apt_profile_versions.profileid='$profileid'")
	    or goto bad;
690 691 692
    }
    else {
	# Set deleted on all of the versions.
693
	DBQueryWarn("update apt_profile_versions set deleted=now() ".
694 695
		    "where profileid='$profileid'")
	    or goto bad;
696
	# Delete any leftover webtasks. These are old ones.
697 698 699 700
	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'");
701 702 703
	# Primary webtask.
	$self->webtask()->Delete()
	    if ($self->webtask());
704
    }
705 706 707
    DBQueryWarn("delete from apt_profile_favorites ".
		"where profileid='$profileid'")
	or goto bad;
708 709 710
    DBQueryWarn("delete from apt_profile_images ".
		"where profileid='$profileid'")
	or goto bad;
711 712 713
    DBQueryWarn("delete from apt_profiles where profileid='$profileid'")
	or goto bad;
    
714
    DBQueryWarn("unlock tables");
715
    return 0;
716 717 718 719

  bad:
    DBQueryWarn("unlock tables");
    return -1;
720 721
}

722
#
723 724
# Delete a profile version, only allow it if it is the highest
# numbered version.
725
#
726
sub DeleteVersion($)
727 728 729
{
    my ($self) = @_;

730
    DBQueryWarn("lock tables apt_profile_versions write, ".
Leigh B Stoller's avatar
Leigh B Stoller committed
731 732
		"     apt_profiles write, web_tasks write, ".
		"     apt_profile_images write")
733
	or return -1;
734

735 736
    my $profileid = $self->profileid();
    my $version   = $self->version();
737

738
    #
739 740
    # Need to know what profile becomes the head version. This will
    # always be the highest numbered undeleted profile.
741 742 743
    #
    my $query_result =
	DBQueryWarn("select max(version) from apt_profile_versions ".
744 745
		    "where profileid='$profileid' and version!=${version} ".
		    "      and deleted is null");
746 747
    goto bad
	if (!$query_result || !$query_result->numrows);
748

749 750
    my ($newhead) = $query_result->fetchrow_array();

751 752 753 754 755 756 757
    # 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'");

758
    goto bad
759
	if (!DBQueryWarn("update apt_profile_versions set deleted=now() ".
760 761
			 "where profileid='$profileid' and ".
			 "      version='$version'"));
762

763
    goto bad
764
	if (!DBQueryWarn("update apt_profiles set version=$newhead ".
765 766
			 "where profileid='$profileid' and ".
			 "      version='$version'"));
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

    goto bad 
	if (!DBQueryWarn("delete from apt_profile_images ".
			 "where profileid='$profileid' and ".
			 "      version='$version'"));
    DBQueryWarn("unlock tables");
    return 0;
  bad:
    DBQueryWarn("unlock tables");
    return -1;
}

#
# Recover a deleted version of a profile.
# The profile itself cannot be fully deleted for this to work.
#
sub UnDeleteVersion($$)
{
    my ($self, $version);
    my $profileid = $self->profileid();

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

    #
    # Confirm if this is going to become the new head version.
    #
    my $query_result =
	DBQueryWarn("select version from apt_profiles ".
		    "where profileid='$profileid'");
    goto bad
	if (!$query_result || !$query_result->numrows);
    
    my ($curhead) = $query_result->fetchrow_array();

    #
    # We need a new web task.
    #
    my $webtask = WebTask->CreateAnonymous();
    if (!defined($webtask)) {
	print STDERR "Could not create a new webtask\n";
	goto bad;
    }
    my $webtask_id = $webtask->task_id();
    goto bad
	if (!DBQueryWarn("update apt_profile_versions set ".
			 "   webtask_id='$webtask_id', deleted=null ".
			 "where profileid='$profileid' and ".
			 "      version='$version'"));

    # Is this the new head version? 
    if ($version > $curhead) {
	goto bad
	    if (!DBQueryWarn("update apt_profiles set version='$version' ".
			     "where profileid='$profileid'"));
    }
824
    DBQueryWarn("unlock tables");
825
    return 0;
826 827
  bad:
    DBQueryWarn("unlock tables");
828 829
    $webtask->Delete()
	if (defined($webtask));
830
    return -1;
831 832
}

833 834 835 836
#
# Condomize a profile rspec by inserting the necessary firewall section
# to each of the nodes.
#
837
sub CheckFirewall($$)
838
{
839
    my ($self, $condomize) = @_;
840 841 842 843 844 845 846 847 848 849 850

    # 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()) {
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	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";
	}
	
868 869 870 871 872 873 874
	if ($condomize) {
	    #
	    # No settings is easy; wrap it tight.
	    #
	    if (!GeniXML::HasFirewallSettings($ref)) {
		my $firewall = GeniXML::AddElement("firewall", $ref,
						   $GeniXML::EMULAB_NS);
875
		GeniXML::SetText("style", $firewall, $style);
876 877 878 879 880 881 882 883 884
		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") {
885
		GeniXML::SetText("style", $settings, $style);
886
	    }
887 888
	}
	#
889 890
	# Quick pass over the exceptions to see if we need to substitute
	# the callers IP address.
891
	#
892 893 894 895 896 897
	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'});
	    }
898 899 900 901
	}
    }
    return GeniXML::Serialize($rspec);
}
Leigh B Stoller's avatar
Leigh B Stoller committed
902 903 904 905 906 907 908

#
# Lock and Unlock
#
sub Lock($)
{
    my ($self) = @_;
909
    my $profileid = $self->profileid();
Leigh B Stoller's avatar
Leigh B Stoller committed
910 911 912 913 914

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

    my $query_result =
915 916
	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
917 918 919 920 921 922 923

    if (! $query_result ||
	$query_result->numrows == 0) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables");
924
    $self->{'DBROW'}->{'locked'} = time();
Leigh B Stoller's avatar
Leigh B Stoller committed
925 926 927 928 929 930
    return 0;
}

sub Unlock($)
{
    my ($self) = @_;
931
    my $profileid = $self->profileid();
Leigh B Stoller's avatar
Leigh B Stoller committed
932 933

    return -1
934 935 936 937 938 939 940 941
	if (! DBQueryWarn("update apt_profiles set ".
			  "   locked=null,locker_pid=0 ".
			  "where profileid='$profileid'"));
    
    $self->{'DBROW'}->{'locked'} = 0;
    return 0;
}

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
#
# Wait for lock with timeout (in seconds).
#
sub WaitForLock($$)
{
    my ($self, $timeout) = @_;

    return $self->Lock()
	if (! $timeout);
	
    while ($timeout >= 0) {
	return 0
	    if ($self->Lock() == 0);
	
	$timeout--;
	sleep(1);
    }
    return -1;
}

962
#
963 964 965
# 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.
966
#
Leigh B Stoller's avatar
Leigh B Stoller committed
967
sub UpdateDiskImage($$$$$)
968
{
Leigh B Stoller's avatar
Leigh B Stoller committed
969
    my ($self, $node_id, $newimage, $all, $impotent) = @_;
970 971 972 973 974
    my $rspec = GeniXML::Parse($self->rspec());
    if (! defined($rspec)) {
	print STDERR "UpdateDiskImage: Could not parse rspec\n";
	return -1;
    }
975 976 977 978 979
    #
    # Find all the nodes we want to update, might be just the one or
    # all with the same image.
    #
    my @nodes = ();
Leigh B Stoller's avatar
Leigh B Stoller committed
980
    my @list  = ();
981 982
    my $node;

Leigh B Stoller's avatar
Leigh B Stoller committed
983
    # First find the specified node and generate list to examine.
984 985 986
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	if (GeniXML::GetVirtualId($ref) eq $node_id) {
	    $node = $ref;
Leigh B Stoller's avatar
Leigh B Stoller committed
987 988 989 990
	    push(@list, $node);
	}
	elsif ($all) {
	    push(@list, $ref);
991 992 993 994 995 996
	}
    }
    if (!defined($node)) {
	print STDERR "$node_id not in rspec\n";
	return -1;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    #
    # Pull out the disk url/urn of the specified node.
    #
    my $Odiskref = GeniXML::GetDiskImage($node);
    my $image_urn;
    my $image_url;
    if (defined($Odiskref)) {
	$image_url = GeniXML::GetText("url", $Odiskref);
	$image_urn = GeniXML::GetText("name", $Odiskref);
	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;
1011 1012
	    }
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
1013 1014 1015 1016 1017 1018
    }
    #
    # Now find all nodes using the same disk urn/url and change.
    #
    foreach my $ref (@list) {
	my $diskref   = GeniXML::GetDiskImage($ref);
1019
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1020 1021
	# If the both this node and the original node did not
	# specify a disk image, then we update it. 
1022
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1023 1024 1025 1026 1027 1028 1029 1030 1031
	if (!defined($diskref)) {
	    push(@nodes, $ref)
		if (!defined($Odiskref));
	    next;
	}
	my $this_url = GeniXML::GetText("url", $diskref);
	my $this_urn = GeniXML::GetText("name", $diskref);
	next
	    if (!(defined($image_url) || defined($image_urn)));
1032

Leigh B Stoller's avatar
Leigh B Stoller committed
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
	# 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)) {
	    # Watch for actually needing to change, for impotent mode.
	    # Might not change if the cluster is not doing image
	    # versioning.
	    push(@nodes, $ref)
		if (defined($this_url) && $this_url eq $image_url &&
		    $this_url ne $newimage);
	}
	else {
	    # Watch for actually needing to change, for impotent mode.
	    # Might not change if the cluster is not doing image
	    # versioning.
	    push(@nodes, $ref)
		if (defined($this_urn) && $this_urn eq $image_urn &&
		    $this_urn ne $newimage);
1053 1054
	}
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1055 1056 1057
    # Impotent mode, return number of nodes to be changed.
    if ($impotent) {
	return scalar(@nodes);
1058
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1059 1060 1061
    return 0
	if (!@nodes);

1062
    foreach my $node (@nodes) {
1063
	GeniXML::SetDiskImage($node, $newimage);
1064
    }
1065 1066 1067 1068 1069 1070 1071
    if ($self->UpdateVersion({"rspec" => GeniXML::Serialize($rspec)})) {
	print STDERR "UpdateDiskImage: Could not update rspec\n";
	return -1;
    }
    return 0;
}

1072
# Total nonsense, to be thrown away.
1073
sub CheckNodeConstraints($$$)
1074
{
1075
    my ($self, $default_aggregate_urn, $pmsg) = @_;
1076
    my $cloudwww = "www.utah.cloudlab.us";
1077
    my $cloudurn = "urn:publicid:IDN+utah.cloudlab.us+authority+cm";
1078 1079 1080 1081 1082 1083 1084 1085 1086
    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);
1087
	my $virtualization_type = GeniXML::GetVirtualizationSubtype($ref);
1088 1089 1090 1091 1092
	my $manager_urn = GetManagerId($ref);
	if (! defined($manager_urn)) {
	    $manager_urn = $default_aggregate_urn;
	}
	my $iscloudlab = ($manager_urn eq $cloudurn ? 1 : 0);
1093 1094 1095 1096 1097 1098 1099

	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;
	}
1100 1101 1102 1103
	my $diskref   = GeniXML::GetDiskImage($ref);
	next
	    if (!defined($diskref));
	my $image_url = GeniXML::GetText("url", $diskref);
1104
	my $image_urn = GeniXML::GetText("name", $diskref);
1105
	next
1106 1107
	    if (!(defined($image_url) || defined($image_urn)));

1108
	# Watch for url in the name, flipflop. 
Leigh B Stoller's avatar
Leigh B Stoller committed
1109
	if (defined($image_urn) && $image_urn =~ /^http/) {
1110 1111 1112 1113
	    $image_url = $image_urn;
	    $image_urn = undef;
	}

1114
	if (defined($image_urn)) {
1115 1116
	    if ($image_urn =~ /UBUNTU14\-10\-64\-OS/ ||
		$image_urn =~ /UBUNTU15\-04\-64\-OS/) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1117 1118
		return 0;
	    }
1119
	    elsif ($iscloudlab &&
1120
		   !($image_urn =~ /ARM/i || $image_urn =~ /HPC/i)) {
1121
		$$pmsg = "The disk image specified for node '$client_id' ".
1122
		    "will not run on the Cloudlab Utah cluster";
1123 1124
		return -1;
	    }
1125
	    elsif (!$iscloudlab && $image_urn =~ /ARM/i) {
1126
		$$pmsg = "The disk image specified for node '$client_id' ".
1127
		    "will only run on the Cloudlab Utah cluster";
1128 1129 1130 1131 1132
		return -1;
	    }
	}
	next if
	    (!defined($image_url));
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

	# 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' ".
1145
		    "will not run on the Cloudlab Utah cluster";
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
		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;
}

1160
#
1161
# Check dataset validity.
1162
#
1163
sub CheckDatasets($$)
1164
{
1165
    my ($xml, $pmsg) = @_;
1166
    
1167 1168 1169 1170 1171 1172
    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()) {
1173 1174
	my $manager_urn = GetManagerId($ref);	
	
1175 1176 1177
	foreach my $blockref (GeniXML::FindNodesNS("n:blockstore",
						   $ref,
				   $GeniXML::EMULAB_NS)->get_nodelist()) {
1178 1179
	    my $dataset_id  = GeniXML::GetText("dataset", $blockref);
	    my $class       = GeniXML::GetText("class", $blockref);
1180 1181 1182 1183 1184 1185

	    #
	    # We only care about datasets here, we let the backend
	    # do the error checking on ephemeral blockstores.
	    #
	    next
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
		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";
1210 1211
		return 1;
	    }
1212
	    my $dataset_urn = GeniHRN->new($dataset_id);
1213
	    
1214
	    #
1215 1216 1217
	    # 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.
1218
	    #
1219 1220 1221
	    if ($class ne "local") {
		if (defined($manager_urn)) {
		    $manager_urn = GeniHRN->new($manager_urn);
1222
		
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
		    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";
1233 1234 1235
		    return 1;
		}
	    }
1236
	    #
1237 1238 1239
	    # 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.
1240
	    #
1241
	    my $dataset = APT_Dataset->LookupByRemoteURN($dataset_urn);
1242
	    if (!defined($dataset)) {
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
		#
		# 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;
			}
1256
		    }
1257 1258
		    else {
			$dataset = Lease->Lookup($pid, $id);
1259
		    }
1260
		}
1261
	    }
1262 1263 1264 1265
	    if (!defined($dataset)) {
		$$pmsg = "Persistent dataset '$dataset_urn' does not exist";
		return 1;
	    }
1266 1267 1268 1269 1270
	}
    }
    return 0;
}

1271 1272 1273
#
# Set the component_manager_urn for the sites.
#
1274
sub SetSites($$$$$$)
1275
{
1276 1277 1278 1279
    my ($prspecstr, $sitemap, $default_aggregate_urn, $paggregate_urns,
	$pneedstitcher, $perrmsg) = @_;
    my %interface_map   = ();
    my %aggregates      = ();
1280 1281 1282 1283 1284 1285 1286 1287

    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);
1288
	my $manager_urn = GetManagerId($ref);	
1289 1290
	my $site_id     = GeniXML::GetJacksSiteId($ref);

1291 1292 1293 1294 1295 1296
	# 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;
	    }
1297
	}
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
	# 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);
1325
	}
1326
	$aggregates{$manager_urn} = $manager_urn;
1327 1328 1329 1330 1331 1332 1333 1334

	#
	# 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);
1335
	    $interface_map{$client_id} = $manager_urn;
1336
	}
1337
    }
1338 1339