manage_profile.in 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#!/usr/bin/perl -w
#
# Copyright (c) 2000-2014 University of Utah and the Flux Group.
# 
# {{{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/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
28
use File::Temp qw(tempfile :POSIX );
29 30
use Data::Dumper;
use CGI;
31 32
use POSIX ":sys_wait_h";
use POSIX qw(setsid);
33 34 35 36 37 38

#
# Back-end script to manage APT profiles.
#
sub usage()
{
39 40 41 42
    print("Usage: manage_profile create [-s uuid] <xmlfile>\n");
    print("Usage: manage_profile update <profile> <xmlfile>\n");
    print("Usage: manage_profile publish <profile>\n");
    print("Usage: manage_profile delete <profile>\n");
43 44
    exit(-1);
}
45
my $optlist     = "ds:t:";
46
my $debug       = 0;
47
my $update      = 0;
48 49
my $snap        = 0;
my $uuid;
50
my $rspec;
51
my $script;
52
my $profile;
53
my $instance;
54 55
my $webtask;
my $webtask_id;
56 57 58 59

#
# Configure variables
#
60 61
my $TB		    = "@prefix@";
my $TBOPS           = "@TBOPSEMAIL@";
62
my $TBLOGS	    = "@TBLOGSEMAIL@";
63
my $MANAGEINSTANCE  = "$TB/bin/manage_instance";
64
my $RUNGENILIB      = "$TB/bin/rungenilib";
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use EmulabConstants;
use emdb;
use emutil;
use User;
use Project;
use APT_Profile;
87 88 89
use APT_Instance;
use GeniXML;
use GeniHRN;
90
use WebTask;
91 92 93

# Protos
sub fatal($);
94
sub UserError(;$);
95
sub DeleteProfile($);
96
sub PublishProfile($);
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
# Parse args below.
if (@ARGV < 2) {
    usage();
}
my $action = shift(@ARGV);

# The web interface (and in the future the xmlrpc interface) sets this.
my $this_user = User->ImpliedUser();
if (! defined($this_user)) {
    $this_user = User->ThisUser();
    if (!defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
}

if ($action eq "delete") {
    exit(DeleteProfile($ARGV[0]));
}
elsif ($action eq "publish") {
    exit(PublishProfile($ARGV[0]));
}
elsif (! ($action eq "create" || $action eq "update")) {
    usage();
}

123 124 125 126 127 128 129 130 131 132 133
#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
134
if (defined($options{"s"})) {
135 136
    $snap = 1;
    $uuid = $options{"s"};
137
}
138 139 140
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
}
141 142 143
if ($action eq "update") {
    $update = 1;
    $uuid = shift(@ARGV);
144
}
145
my $xmlfile = shift(@ARGV);
146 147 148 149 150 151 152

#
# These are the fields that we allow to come in from the XMLfile.
#
my $SLOT_OPTIONAL	= 0x1;	# The field is not required.
my $SLOT_REQUIRED	= 0x2;  # The field is required and must be non-null.
my $SLOT_ADMINONLY	= 0x4;  # Only admins can set this field.
153
my $SLOT_UPDATE 	= 0x8;  # Allowed to update.
154 155 156 157 158 159 160 161 162
#
# XXX We should encode all of this in the DB so that we can generate the
# forms on the fly, as well as this checking code.
#
my %xmlfields =
    # XML Field Name        DB slot name         Flags             Default
    ("profile_name"	   => ["name",		$SLOT_REQUIRED],
     "profile_pid"	   => ["pid",		$SLOT_REQUIRED],
     "profile_creator"	   => ["creator",	$SLOT_OPTIONAL],
163
     "profile_listed"      => ["listed",	$SLOT_OPTIONAL|$SLOT_UPDATE],
164
     "profile_public"      => ["public",	$SLOT_OPTIONAL|$SLOT_UPDATE],
Leigh B Stoller's avatar
Leigh B Stoller committed
165
     "profile_shared"      => ["shared",	$SLOT_OPTIONAL|$SLOT_UPDATE],
166 167
     "profile_topdog"      => ["topdog",	$SLOT_OPTIONAL|
			                          $SLOT_UPDATE|$SLOT_ADMINONLY],
168
     "rspec"		   => ["rspec",		$SLOT_REQUIRED|$SLOT_UPDATE],
169
     "script"		   => ["script",	$SLOT_OPTIONAL|$SLOT_UPDATE],
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
);

#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);

#
# Process and dump the errors (formatted for the web interface).
# We should probably XML format the errors instead but not sure I want
# to go there yet.
#
my %errors = ();

#
# Make sure all the required arguments were provided.
#
my $key;
foreach $key (keys(%xmlfields)) {
    my (undef, $required, undef) = @{$xmlfields{$key}};

    $errors{$key} = "Required value not provided"
	if ($required & $SLOT_REQUIRED  &&
	    ! exists($xmlparse->{'attribute'}->{"$key"}));
}
UserError()
    if (keys(%errors));

#
# We build up an array of arguments to create.
#
my %new_args = ();
207
my %update_args = ();
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
    my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }

    print STDERR "User attribute: '$key' -> '$value'\n"
	if ($debug);

    my $field = $key;
    if (!exists($xmlfields{$field})) {
	next; # Skip it.
    }
    my ($dbslot, $required, $default) = @{$xmlfields{$field}};

    if ($required & $SLOT_REQUIRED) {
	# A slot that must be provided, so do not allow a null value.
	if (!defined($value)) {
	    $errors{$key} = "Must provide a non-null value";
	    next;
	}
    }
    if ($required & $SLOT_OPTIONAL) {
	# Optional slot. If value is null skip it. Might not be the correct
	# thing to do all the time?
	if (!defined($value)) {
	    next
		if (!defined($default));
	    $value = $default;
	}
    }
240
    if ($required & $SLOT_ADMINONLY) {
241 242 243 244 245 246 247 248 249 250 251 252
	# Admin implies optional, but thats probably not correct approach.
	$errors{$key} = "Administrators only"
	    if (! $this_user->IsAdmin());
    }
	
    # Now check that the value is legal.
    if (! TBcheck_dbslot($value, "apt_profiles",
			 $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
	$errors{$key} = TBFieldErrorString();
	next;
    }
    $new_args{$dbslot} = $value;
253 254
    $update_args{$dbslot} = $value
	if ($update && ($required & $SLOT_UPDATE));
255 256 257 258

    if ($key eq "rspec") {
	$rspec = $value;
    }
259 260 261
    elsif ($key eq "script") {
	$script = $value;
    }
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
}
UserError()
    if (keys(%errors));

#
# We need to make sure the project exists and is a valid project for
# the creator (current user). 
#
my $project = Project->Lookup($new_args{"pid"});
if (!defined($project)) {
    $errors{"profile_pid"} = "No such project exists";
}
elsif (!$project->AccessCheck($this_user, TB_PROJECT_MAKEIMAGEID())) {
    $errors{"profile_pid"} = "Not enough permission in this project";
}

278 279 280 281 282 283 284 285 286
# Check datasets.
if (defined($rspec)) {
    my $errmsg = "Bad dataset";
    if (APT_Profile::CheckDatasets($rspec, $project->pid(), \$errmsg)) {
	$errors{"error"} = $errmsg;
	UserError();
    }
}

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
#
# See if this is a Parameterized Profile. Generate and store the form
# data if it is.
#
if (defined($script) && $script ne "") {
    my ($fh, $filename) = tempfile();
    fatal("Could not open temporary file for script")
	if (!defined($fh));
    print $fh $script;
    my $paramdefs = `$RUNGENILIB -p $filename`;
    fatal("$RUNGENILIB failed")
	if ($?);
    chomp($paramdefs);
    if ($paramdefs ne "") {
	if ($update) {
	    $update_args{"paramdefs"} = $paramdefs;
	}
	else {
	    $new_args{"paramdefs"} = $paramdefs;
	}
    }
}

310 311 312 313
#
# Are we going to snapshot a node in an experiment? If so we
# sanity check to make sure there is just one node. 
#
314 315
if ($snap) {
    $instance = APT_Instance->Lookup($uuid);
316
    if (!defined($instance)) {
317
	fatal("Could not look up instance $uuid");
318 319 320 321 322 323 324 325 326 327 328
    }
    my $manifest = GeniXML::Parse($instance->manifest());
    if (! defined($manifest)) {
	fatal("Could not parse manifest");
    }
    my @nodes = GeniXML::FindNodes("n:node", $manifest)->get_nodelist();
    if (@nodes != 1) {
	$errors{"error"} = "Too many nodes (> 1) to snapshot";
	UserError();
    }
}
329
if ($update) {
330
    $profile = APT_Profile->Lookup($uuid);
331
    if (!defined($profile)) {
332
	fatal("Could not lookup profile for update $uuid");
333
    }
334
    # Kill the description.. No longer used.
335 336 337
    delete($update_args{"description"});

    #
338
    # If the rspec/script changed, then make a new version of the profile.
339 340
    # Everything else is metadata.
    #
341 342 343 344 345
    if (exists($update_args{"rspec"}) || exists($update_args{"script"})) {
	if ((exists($update_args{"rspec"}) &&
	     $update_args{"rspec"} ne $profile->rspec()) ||
	    (exists($update_args{"script"}) &&
	     $update_args{"script"} ne $profile->script())) {
346 347 348 349 350
	    if ($this_user->IsAdmin()) {
		$profile = $profile->NewVersion($this_user);
		if (!defined($profile)) {
		    fatal("Could not create new version of the profile");
		}
351
	    }
352 353 354 355
	    $profile->UpdateVersion({"rspec" => $update_args{"rspec"}})
		if (exists($update_args{"rspec"}));
	    $profile->UpdateVersion({"script" => $update_args{"script"}})
		if (exists($update_args{"script"}));
356 357
	    $profile->UpdateVersion({"paramdefs" => $update_args{"paramdefs"}})
		if (exists($update_args{"paramdefs"}));
358
	}
359 360 361 362
	delete($update_args{"rspec"})
	    if (exists($update_args{"rspec"}));
	delete($update_args{"script"})
	    if (exists($update_args{"script"}));
363 364
	delete($update_args{"paramdefs"})
	    if (exists($update_args{"paramdefs"}));
365 366
    }
    $profile->UpdateMetaData(\%update_args) == 0 or
367
	fatal("Could not update profile record");
368

369 370
    # Bump the modtime.
    $profile->MarkModified();
371 372 373
}
else {
    my $usererror;
374 375

    $profile = APT_Profile->Lookup($new_args{"pid"}, $new_args{"name"});
376 377 378 379 380
    if (defined($profile)) {
	$errors{"profile_name"} = "Already in use";
	UserError();
    }
    $profile =
Leigh B Stoller's avatar
Leigh B Stoller committed
381
	APT_Profile->Create($profile, $project,
382
			    $this_user, \%new_args, \$usererror);
383 384 385 386 387 388 389
    if (!defined($profile)) {
	if (defined($usererror)) {
	    $errors{"profile_name"} = $usererror;
	    UserError();
	}
	fatal("Could not create new profile");
    }
390 391 392
    if (!$this_user->IsAdmin()) {
	$profile->Publish();
    }
393
}
394 395 396 397 398 399 400 401 402 403 404

#
# Now do the snapshot operation.
#
if (defined($instance)) {
    my $manifest = GeniXML::Parse($instance->manifest());
    if (! defined($manifest)) {
	fatal("Could not parse manifest");
    }
    my ($node) = GeniXML::FindNodes("n:node", $manifest)->get_nodelist();
    my $sliver_urn = GeniXML::GetSliverId($node);
405
    my $node_id    = GeniXML::GetVirtualId($node);
406 407 408
    my $apt_uuid   = $instance->uuid();
    my $imagename  = $profile->name();

409 410
    #
    # Grab the webtask object so we can watch it. We are looking
411 412 413 414
    # for it to finish, so we can unlock the profile for use. Note
    # this always creates a webtask, even if not directed to on the
    # commmand line, so that we can communicate with the script we
    # call that does the work. 
415 416 417
    #
    $webtask = WebTask->Create($profile->uuid(), $webtask_id);
    if (!defined($webtask)) {
418
	$profile->Delete(1);
419
    }
420
    $webtask->AutoStore(1);
421 422

    if ($profile->Lock()) {
423
	$profile->Delete(1);
424 425 426
	fatal("Could not lock new profile");
    }

427 428 429
    my $command = "$MANAGEINSTANCE -t " . $webtask->task_id() . " ".
	"snapshot $apt_uuid $imagename $node_id";
    
430 431
    #
    # This returns pretty fast, and then the imaging takes place in
432 433 434
    # the background at the aggregate. The script keeps a process
    # running in the background waiting for the sliver to unlock and
    # the sliverstatus to indicate the node is running again.
435 436 437
    #
    my $output = emutil::ExecQuiet($command);
    if ($?) {
438
	$profile->Delete(1);
439 440 441
	$webtask->Delete()
	    if (!defined($webtask_id));
	print STDERR $output . "\n";
442 443 444
	fatal("Failed to create disk image!");
    }
    #
445
    # The script helpfully put the new image urn in the webtask.
446
    #
447
    $webtask->Refresh();
448 449 450
    my $image_url = $webtask->image_url();
    if (!defined($image_url) ||
	$profile->UpdateDiskImage($image_url)) {
451 452
	$webtask->Delete()
	    if (!defined($webtask_id));
453 454
	$profile->Delete(1);
	fatal("Could not update image URN in rspec");
455
    }
456 457 458 459 460 461 462 463 464

    #
    # Exit and leave child to poll.
    #
    if (! $debug) {
	my $child = fork();
	if ($child) {
	    exit(0);
	}
465 466 467 468 469 470
	# Close our descriptors so web server thinks we are disconnected.
	if ($webtask_id) {
	    for (my $i = 0; $i < 1024; $i++) {
	        POSIX::close($i);
	    }
	}
471 472
	# Let parent exit;
	sleep(2);
473
        POSIX::setsid();
474
    }
475 476 477 478 479 480 481 482
    #
    # We are waiting for the backend process to exit. The web interface is
    # reading the webtask structure, but if it fails we want to know that
    # so we can delete the profile. 
    #
    while (1) {
	sleep(10);
	
483 484 485
	$webtask->Refresh();
	last
	    if (defined($webtask->exited()));
486 487 488 489 490 491 492 493 494 495 496 497 498 499

	#
	# See if the process is still running. If not then it died badly.
	# Mark the webtask as exited.
	#
	my $pid = $webtask->process_id();
	if (! kill(0, $pid)) {
	    # Check again in case it just exited.
	    $webtask->Refresh();
	    if (! defined($webtask->exited())) {
		$webtask->Exited(-1);
	    }
	    last;
	}
500 501
    }
    if ($webtask->exitcode()) {
502
	$profile->Delete(1);
503 504
	$webtask->Delete()
	    if (!defined($webtask_id));
505 506 507
	exit(1);
    }
    $profile->Unlock();
508 509
    $webtask->Delete()
	if (!defined($webtask_id));
510
    exit(0);
511
}
512 513 514 515 516 517 518 519 520 521 522 523 524 525

my $portalLogs =
    ($project->isAPT() ? "aptnet-logs\@flux.utah.edu" :
     $project->isCloud() ? "cloudlab-logs\@flux.utah.edu" : $TBLOGS);

$project->SendEmail($portalLogs, "New Profile Created",
	 "Name:     ". $profile->name() . "\n".
	 "User:     ". $profile->creator() . "\n".
	 "Project:  ". $profile->pid() .
	                 " (" . $project->Brand()->brand() . ")\n".
	 "UUID:     ". $profile->uuid() . "\n".
	 "URL:      ". $profile->AdminURL() . "\n",
	 $TBOPS);

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
exit(0);

sub fatal($)
{
    my ($mesg) = @_;

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

#
# Generate a simple XML file that PHP can parse. The web interface
# relies on using the same name attributes for the errors, as for
# the incoming values.
#
543
sub UserError(;$)
544
{
545 546 547 548 549
    my ($msg) = @_;
    
    if (defined($msg)) {
	$errors{"error"} = $msg;
    }
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    if (keys(%errors)) {
	print "<errors>\n";
	foreach my $key (keys(%errors)) {
    	    print "<error name='$key'>" . CGI::escapeHTML($errors{$key});
	    print "</error>\n";
	}
	print "</errors>\n";
    }
    # Exit with positive status so web interface treats it as user error.
    exit(1);
}

sub escapeshellarg($)
{
    my ($str) = @_;

    $str =~ s/[^[:alnum:]]/\\$&/g;
    return $str;
}
569 570 571 572 573 574 575 576 577 578 579

#
# Delete a profile.
#
sub DeleteProfile($)
{
    my ($name)  = @_;
    my $profile = APT_Profile->Lookup($name);
    if (!defined($profile)) {
	fatal("No such profile exists");
    }
580 581 582
    #
    # Not allowed to delete a published profile, yet. Needs thought.
    #
583
    if (defined($profile->published()) && !$this_user->IsAdmin()) {
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	UserError("Not allowed to delete a published profile");
    }
    if (!$profile->IsHead()) {
	UserError("Only allowed to delete the most recent profile");
    }
    #
    # Version zero is special of course.
    #
    if ($profile->version()) {
	$profile->DeleteVersion(0) == 0 or
	    fatal("Could not delete profile version");
    }
    else {
	# Purge it. At some point we want to save them.
	$profile->Delete(1) == 0 or
	    fatal("Could not delete profile");
    }
    return 0;
}

#
# Publish a profile.
#
sub PublishProfile($)
{
    my ($name)  = @_;
    my $profile = APT_Profile->Lookup($name);
    if (!defined($profile)) {
	fatal("No such profile exists");
    }
    if (!$profile->IsHead()) {
	UserError("Only allowed to publish the most recent profile");
    }
    $profile->Publish() == 0 or
	fatal("Could not publish profile");
619 620
    return 0;
}