manage_profile.in 38.5 KB
Newer Older
1
2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-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
26
27
# 
# {{{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
use Carp qw(cluck);
34
35
36
37
38
39

#
# Back-end script to manage APT profiles.
#
sub usage()
{
40
    print("Usage: manage_profile create [-s uuid | -c uuid] <xmlfile>\n");
41
    print("Usage: manage_profile update <profile> <xmlfile>\n");
42
    print("Usage: manage_profile updatefromrepo <profile>\n");
43
    print("Usage: manage_profile publish <profile>\n");
44
45
46
    print("Usage: manage_profile delete -a <profile>\n");
    print("Usage: manage_profile undelete pid,name:version\n");
    print("Usage: manage_profile listimages <profile>\n");
47
48
    exit(-1);
}
49
my $optlist     = "dvt:m";
50
my $debug       = 0;
51
my $verbose     = 0;
52
53
my $webtask;
my $webtask_id;
54
55
56
57
58
59
60
# VerifyXML sets these, need to declare early. Need to clean this up.
my %new_args    = ();
my %update_args = ();
my %modifiers   = ();
my $rspec;
my $script;
my $project;
61
62
63
64

#
# Configure variables
#
65
66
my $TB		    = "@prefix@";
my $TBOPS           = "@TBOPSEMAIL@";
67
my $TBLOGS	    = "@TBLOGSEMAIL@";
68
my $MANAGEINSTANCE  = "$TB/bin/manage_instance";
69
my $MANAGEGITREPO   = "$TB/bin/manage_gitrepo";
70
my $MANAGEIMAGES    = "$TB/bin/manage_images";
71
my $RUNGENILIB      = "$TB/bin/rungenilib";
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

#
# 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;
91
use libEmulab;
92
use libtestbed;
93
94
95
use User;
use Project;
use APT_Profile;
96
use APT_Instance;
97
use APT_Aggregate;
98
99
use GeniXML;
use GeniHRN;
100
use WebTask;
101
use EmulabFeatures;
102
103
104

# Protos
sub fatal($);
105
106
107
108
sub UserError($);
sub CreateProfile();
sub ModifyProfile();
sub UpdateProfileFromRepo();
109
110
111
sub DeleteProfile();
sub UnDeleteProfile($);
sub CanDelete($$);
112
sub PublishProfile($);
113
114
sub InsertImageRecords($);
sub ListImages();
115
116
117
118
sub HandleScript($);
sub VerifyXML($$);
sub ModifyProfileInternal($$$);
		      
119
120
121
122
123
124
125
126
127
# 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!");
    }
}

128
129
130
131
132
133
134
135
136
137
138
#
# 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;
}
139
140
if (defined($options{"v"})) {
    $verbose = 1;
141
}
142
143
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
144
145
146
147
148
149
150
151
    #
    # Grab the webtask object.
    #
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not lookup/create webtask for profile");
    }
    $webtask->AutoStore(1);
152
}
153
154
155
usage()
    if (!@ARGV);
my $action = shift(@ARGV);
156
157
158
159
160
161
162

#
# 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.
163
my $SLOT_UPDATE 	= 0x8;  # Allowed to update.
164
my $SLOT_MODIFIER 	= 0x10; # Allowed to update.
165
166
167
168
169
170
171
172
173
#
# 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],
174
     "profile_listed"      => ["listed",	$SLOT_OPTIONAL|$SLOT_UPDATE],
175
     "profile_public"      => ["public",	$SLOT_OPTIONAL|$SLOT_UPDATE],
Leigh B Stoller's avatar
Leigh B Stoller committed
176
     "profile_shared"      => ["shared",	$SLOT_OPTIONAL|$SLOT_UPDATE],
177
178
     "profile_topdog"      => ["topdog",	$SLOT_OPTIONAL|
			                          $SLOT_UPDATE|$SLOT_ADMINONLY],
179
180
     "profile_disabled"    => ["disabled",	$SLOT_OPTIONAL|
			                          $SLOT_UPDATE|$SLOT_ADMINONLY],
181
182
     "profile_disable_all" => ["disable_all",	$SLOT_OPTIONAL|$SLOT_MODIFIER,
			                          $SLOT_UPDATE|$SLOT_ADMINONLY],
183
184
185
186
     "profile_nodelete"    => ["nodelete",	$SLOT_OPTIONAL|
			                          $SLOT_UPDATE|$SLOT_ADMINONLY],
     "profile_nodelete_all"=> ["nodelete_all",	$SLOT_OPTIONAL|$SLOT_MODIFIER,
			                          $SLOT_UPDATE|$SLOT_ADMINONLY],
187
     "rspec"		   => ["rspec",		$SLOT_REQUIRED|$SLOT_UPDATE],
188
     "script"		   => ["script",	$SLOT_OPTIONAL|$SLOT_UPDATE],
189
     "repourl"		   => ["repourl",	$SLOT_OPTIONAL],
190
191
);

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
if ($action eq "update") {
    exit(ModifyProfile());
}
elsif ($action eq "updatefromrepo") {
    exit(UpdateProfileFromRepo());
}
elsif ($action eq "delete") {
    exit(DeleteProfile());
}
elsif ($action eq "undelete") {
    exit(UnDeleteProfile(shift(@ARGV)));
}
elsif ($action eq "publish") {
    exit(PublishProfile(shift(@ARGV)));
}
elsif ($action eq "insertimages") {
    exit(InsertImageRecords(shift(@ARGV)));
}
elsif ($action eq "listimages") {
    exit(ListImages());
}
elsif ($action eq "create") {
    exit(CreateProfile());
215
216
217
}

#
218
# Create/Update a profile. 
219
#
220
221
sub CreateProfile()
{
222
    my $optlist    = "s:c:U";
223
224
    my $snap       = 0;
    my $copy       = 0;
225
    my $prepare    = 0;
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    my $copyuuid;
    my $fromrepo   = 0;
    my $instance;
    my $aggregate;
    my $parent_profile;
    my $node_id;
    my $usererror;
    my %errors = ();
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"s"})) {
	$snap = 1;
	$copyuuid = $options{"s"};
242
243
244
	if (defined($options{"U"})) {
	    $prepare = 1;
	}
245
246
247
248
249
250
251
252
253
254
    }
    if (defined($options{"c"})) {
	$copy = 1;
	$copyuuid = $options{"c"};
    }
    usage()
	if (@ARGV != 1);
    my $xmlfile = shift(@ARGV);
    # This will exit if there are any errors.
    VerifyXML($xmlfile, 0);
255

256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    #
    # We need to make sure the project exists and is a valid project for
    # the creator (current user). 
    #
    $project = Project->Lookup($new_args{"pid"});
    if (!defined($project)) {
	UserError({"profile_pid" => "No such project exists"})
    }
    elsif (!$project->AccessCheck($this_user, TB_PROJECT_MAKEIMAGEID())) {
	UserError({"profile_pid" => "Not enough permission in this project"});
    }
    # Check datasets.
    if (defined($rspec)) {
	my $errmsg = "Bad dataset";
	if (APT_Profile::CheckDatasets($rspec, \$errmsg)) {
	    UserError($errmsg);
	}
273
274
    }

275
276
277
278
279
280
281
    #
    # Need to do initial clone. 
    #
    if (exists($new_args{'repourl'})) {
	my $repourl  = $new_args{'repourl'};
	my $reponame = NewUUID();
	my $repohash;
282

283
284
285
286
287
288
	my $output =
	    emutil::ExecQuiet("$MANAGEGITREPO clone -n $reponame '$repourl'");
	if ($?) {
	    UserError($output);
	}
	$new_args{'reponame'} = $reponame;
289

290
291
292
293
294
295
	#
	# Get the commit hash for the HEAD commit.
	#
	$output = emutil::ExecQuiet("$MANAGEGITREPO hash -n $reponame");
	if ($?) {
	    UserError($output);	
296
	}
297
298
299
300
301
302
303
304
305
306
307
308
309
	$repohash = $output;
	chomp($repohash);
	$new_args{'repohash'} = $repohash;
	$fromrepo = 1;

	#
	# And an access key for the push webhook.
	#
	my $repokey = TBGenSecretKey();
	if (!defined($repokey)) {
	    fatal("Could not generate a repo access key");
	}
	$new_args{'repokey'} = $repokey;
310
    }
311
312
313
314
    # Script parameters
    if (defined($script) && $script ne "") {
	my $paramdefs = HandleScript($script);

315
316
	$new_args{"paramdefs"} =
	    $paramdefs if (defined($paramdefs) && $paramdefs ne "");
317
318
319
320
321
322
323
324
325
326
327
328
    }
    #
    # Are we going to snapshot a node in an experiment? If so we
    # sanity check to make sure there is just one node. 
    #
    if ($snap) {
	$instance = APT_Instance->Lookup($copyuuid);
	if (!defined($instance)) {
	    fatal("Could not look up instance $copyuuid");
	}
	if ($instance->status() ne "ready") {
	    UserError("Instance must be in the ready state for cloning");
329
	}
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
	if ($instance->AggregateList() != 1) {
	    UserError("Must be only one aggregate to snapshot");
	}
	($aggregate) = $instance->AggregateList();
	my $manifest = GeniXML::Parse($aggregate->manifest());
	if (! defined($manifest)) {
	    fatal("Could not parse manifest");
	}
	my @nodes = GeniXML::FindNodes("n:node", $manifest)->get_nodelist();
	if (@nodes != 1) {
	    UserError("Too many nodes (> 1) to snapshot");
	}
	my $sliver_urn = GeniXML::GetSliverId($nodes[0]);
	my $manager_urn= GeniXML::GetManagerId($nodes[0]);
	$node_id       = GeniXML::GetVirtualId($nodes[0]);
	if (! (defined($sliver_urn) &&
	       $manager_urn eq $aggregate->aggregate_urn())) {
	    UserError("$node_id is not at " . $aggregate->aggregate_urn());
	}
	$parent_profile = $instance->Profile();
350
    }
351
352
353
354
355
    elsif ($copy) {
	$parent_profile = APT_Profile->Lookup($copyuuid);
	if (!defined($parent_profile)) {
	    fatal("Could not look up copy profile $copyuuid");
	}
356
    }
357
358
359
    if (defined(APT_Profile->Lookup($new_args{"pid"}, $new_args{"name"}))) {
	$errors{"profile_name"} = "Already in use";
	UserError(\%errors);
360
    }
361
362
363
364
365
366
367
368
    my $profile = APT_Profile->Create($parent_profile, $project,
				      $this_user, \%new_args, \$usererror);
    if (!defined($profile)) {
	if (defined($usererror)) {
	    $errors{"profile_name"} = $usererror;
	    UserError(\%errors);
	}
	fatal("Could not create new profile");
369
    }
370
371
372
373
374
375
376
377
378
379
380
381
    # This is deprecated.
    $profile->Publish();
    
    #
    # Now do the snapshot operation.
    #
    if (defined($instance)) {
	my $apt_uuid   = $instance->uuid();
	my $imagename  = $profile->name();
	my $new_uuid   = $profile->uuid();
	# We want to use the webtask associated with the new profile.
	my $pwebtask   = $profile->webtask();
382
	my $ptask_id   = $pwebtask->task_id();
383
384
	# But the image details are stored in the instance webtask.
	my $iwebtask   = $instance->webtask();
385
	my $prepopt    = $prepare ? "-U" : "";
386
387
388
389
390
    
	if ($profile->Lock()) {
	    $profile->Delete(1);
	    fatal("Could not lock new profile");
	}
391
392
	my $command = "$MANAGEINSTANCE -t $ptask_id snapshot " . 
	    "$apt_uuid -c $new_uuid -n $node_id -i $imagename $prepopt";
393

394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
	if ($verbose) {
	    print "$command\n";
	}
    
	#
	# This returns pretty fast, and then the imaging takes place in
	# 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.
	#
	my $output = emutil::ExecQuiet($command);
	if ($?) {
	    my $stat = $? >> 8;
	    
	    $profile->Delete(1);
	    print STDERR $output . "\n";
	    if ($stat < 0) {
		fatal("Failed to create disk image!");
	    }
	    UserError($output);
	}
	print $output;
	#
	# The script helpfully put the new image urn in the webtask.
	#
	$pwebtask->AutoStore(1);
	$pwebtask->Refresh();
	$iwebtask->Refresh();
	my $newimage;

	if (GetSiteVar("protogeni/use_imagetracker") &&	
	    EmulabFeatures->FeatureEnabled("APT_UseImageTracker",
					   $this_user, $project)) {
	    $newimage = $iwebtask->image_urn();
	}
	else {
	    $newimage = $iwebtask->image_url();
	}
	if (!defined($newimage)) {
	    $profile->Delete(1);
	    fatal("Did not get an image for $node_id");
	}
	if ($profile->UpdateDiskImage($node_id, $newimage, 0)) {
	    $profile->Delete(1);
	    fatal("Could not update image in rspec for $node_id; $newimage;");
	}
	# Tell web interface cloning has started.
	$pwebtask->cloning(1);
	# And what is being cloned.
	$pwebtask->cloning_instance($instance->uuid());
	$pwebtask->image_name($iwebtask->image_name());
    
	#
	# Exit and leave child to poll.
	#
	if (! $debug) {
	    my $child = fork();
	    if ($child) {
		exit(0);
	    }
	    # Close our descriptors so web server thinks we are disconnected.
	    if ($webtask_id) {
		for (my $i = 0; $i < 1024; $i++) {
		    POSIX::close($i);
		}
	    }
	    # Let parent exit;
	    sleep(2);
	    POSIX::setsid();
	}
	#
	# 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);
	
	    $pwebtask->Refresh();
	    last
		if (defined($pwebtask->exited()));

	    #
	    # See if the process is still running. If not then it died badly.
	    # Mark the webtask as exited.
	    #
	    my $pid = $pwebtask->process_id();
	    if (! kill(0, $pid)) {
		# Check again in case it just exited.
		$pwebtask->Refresh();
		if (! defined($pwebtask->exited())) {
		    $pwebtask->Exited(-1);
		}
		last;
	    }
	}
	# When the profile is deleted, the web task will be deleted. The
	# web interface will see that of course and return an error to the
	# client JS code. 
	if ($pwebtask->exitcode()) {
	    $profile->Delete(1);
	    exit(1);
	}
	$profile->Refresh();
	$profile->InsertImageRecords();
    
	# Tell web interface cloning has finished. But leave cloning_instance
	# set since otherwise the web interface will no longer be able to
	# figure out what to tell the user.
	$pwebtask->cloning(0);
	$profile->Unlock();
505
    }
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
    else {
	$profile->InsertImageRecords();
    }
    my $portalLogs =
	($project->isAPT() ? "aptnet-logs\@flux.utah.edu" :
	 $project->isCloud() ? "cloudlab-logs\@flux.utah.edu" : 
	 $project->isPNet() ? "phantomnet-logs\@flux.utah.edu" : $TBLOGS);

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

    return 0;
523
524
525
}

#
526
# Modify a profile.
527
#
528
529
530
531
532
533
sub ModifyProfile()
{
    my $errmsg;
    
    usage()
	if (@ARGV != 2);
534

535
536
537
    my ($uuid, $xmlfile) = @ARGV;
    
    my $profile = APT_Profile->Lookup($uuid);
538
539
540
541
    if (!defined($profile)) {
	fatal("Could not lookup profile for update $uuid");
    }
    
542
543
    # This will exit if there are any errors.
    VerifyXML($xmlfile, 1);
544
545

    #
546
547
    # We need to make sure the project exists and is a valid project for
    # the creator (current user). 
548
    #
549
550
551
    $project = Project->Lookup($profile->pid_idx());
    if (!defined($project)) {
	UserError({"profile_pid" => "No such project exists"});
552
    }
553
554
    elsif (!$project->AccessCheck($this_user, TB_PROJECT_MAKEIMAGEID())) {
	UserError({"profile_pid" => "Not enough permission in this project"});
555
    }
556
557
    if ($profile->Lock()) {
	UserError("Profile is busy, cannot lock it.");
558
    }
559
560
561
562
563
564
565
566
567
568
569
    my $retval = ModifyProfileInternal($profile, $project, \$errmsg);
    $profile->Unlock();
    if ($retval) {
	if ($retval < 0) {
	    fatal($errmsg);
	}
	else {
	    UserError($errmsg);
	}
    }
    return 0;
570
571
}

572
573
574
575
576
577
578
579
580
581
582
583
584
585
sub ModifyProfileInternal($$$)
{
    my ($profile, $project, $pmsg)  = @_;
    my %errors     = ();
    my $fromrepo   = 0;

    # Check datasets.
    if (defined($rspec)) {
	my $errmsg = "Bad dataset";
	if (APT_Profile::CheckDatasets($rspec, \$errmsg)) {
	    $$pmsg = $errmsg;
	    # User Error
	    return 1;
	}
586
    }
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606

    if ($profile->IsRepoBased()) {
	my $reponame = $profile->reponame();
	my $repohash;
	# Ignore.
	delete($new_args{'repourl'});

	#
	# Get the commit hash for the HEAD commit.
	#
	my $output = emutil::ExecQuiet("$MANAGEGITREPO hash -n $reponame");
	if ($?) {
	    $$pmsg = $output;
	    # User Error
	    return 1;
	}
	$repohash = $output;
	chomp($repohash);
	$update_args{'repohash'} = $repohash;
	$fromrepo = 1;
607
    }
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
    # Script parameters
    if (defined($script) && $script ne "" && $script =~ /^import/m) {
	#
	# For a Parameterized Profile, need to generate and store the form
	# data. Only python scripts of course.
	#
	my ($fh, $filename) = tempfile();
	if (!defined($fh)) {
	    $$pmsg = "Could not open temporary file for script";
	    return -1;
	}
	print $fh $script;
	my $output = emutil::ExecQuiet("$RUNGENILIB -p $filename");
	if ($?) {
	    $$pmsg = $output;
623
	    return $? >> 8;
624
625
	}
	chomp($output);
626

627
628
	# No versioning so need to clear existing paramdefs.
	$update_args{"paramdefs"} = ($output ne "" ? $output : undef);
629
630
    }

631
    # Kill the description.. No longer used.
632
633
    delete($update_args{"description"});

634
635
636
637
638
639
640
    #
    # Check for version feature.
    #
    my $doversions =
	EmulabFeatures->FeatureEnabled("APT_ProfileVersions",
				       $this_user, $project);

641
    #
642
    # If the rspec/script changed, then make a new version of the profile.
643
644
    # Everything else is metadata.
    #
645
646
647
648
    if (exists($update_args{"rspec"}) || exists($update_args{"script"})) {
	if ((exists($update_args{"rspec"}) &&
	     $update_args{"rspec"} ne $profile->rspec()) ||
	    (exists($update_args{"script"}) &&
649
650
651
652
653
	     $update_args{"script"} ne $profile->script()) ||
	    (defined($profile->repourl()) &&
	     exists($update_args{"repohash"}) &&
	     $update_args{"repohash"} ne $profile->repohash())) {
	    if ($doversions && !$fromrepo) {
654
655
		$profile = $profile->NewVersion($this_user);
		if (!defined($profile)) {
656
657
		    $$pmsg = "Could not create new version of the profile";
		    return -1;
658
		}
659
660
661
		# Tell the web interface we created a new version.
		$webtask->newProfile($profile->uuid())
		    if (defined($webtask));
662
	    }
663
664
665
666
667
668
669
670
	    foreach my $key ("rspec", "script", "paramdefs", "repohash") {
		$profile->UpdateVersion({$key => $update_args{$key}})
		    if (exists($update_args{$key}));
	    }
	}
	foreach my $key ("rspec", "script", "paramdefs", "repohash") {
	    delete($update_args{$key})
		if (exists($update_args{$key}));
671
672
	}
    }
673
    if (keys(%update_args)) {
674
675
676
677
	if ($profile->UpdateMetaData(\%update_args)) {
	    $$pmsg = "Could not update profile record";
	    return -1;
	}
678
    }
679

680
    #
681
    # Disable operates on current version or all versions.
682
683
684
    #
    if ($this_user->IsAdmin() &&
	exists($update_args{"disabled"})) {
685
686
687
	if (exists($modifiers{"disable_all"}) && $modifiers{"disable_all"}) {
	    $profile->UpdateAll({"disabled" => $update_args{"disabled"}});
	}
688
689
	$profile->UpdateVersion({"disabled" => $update_args{"disabled"}});
    }
690
691
692
693
694
695
696
697
698
699
    #
    # Ditto the nodelete flag.
    #
    if ($this_user->IsAdmin() &&
	exists($update_args{"nodelete"})) {
	if (exists($modifiers{"nodelete_all"}) && $modifiers{"nodelete_all"}) {
	    $profile->UpdateAll({"nodelete" => $update_args{"nodelete"}});
	}
	$profile->UpdateVersion({"nodelete" => $update_args{"nodelete"}});
    }
700
    $profile->InsertImageRecords();
701

702
    return 0;
703
}
704

705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
#
# Verify the XML file. Return various arrays to drive the create/update.
#
sub VerifyXML($$)
{
    my ($xmlfile, $isupdate) = @_;

    #
    # 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"}));
739
    }
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
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
    UserError(\%errors)
	if (keys(%errors));

    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 ($verbose);

	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;
	    }
	}
	if ($required & $SLOT_ADMINONLY) {
	    # Admin implies optional, but thats probably not correct approach.
	    $errors{$key} = "Administrators only"
		if (! $this_user->IsAdmin());
	}
	if ($required & $SLOT_MODIFIER) {
	    $modifiers{$dbslot} = $value;
	    next;
	}
	
	# 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;
	$update_args{$dbslot} = $value
	    if ($isupdate && ($required & $SLOT_UPDATE));

	if ($key eq "rspec") {
	    $rspec = $value;
	}
	elsif ($key eq "script") {
	    $script = $value;
799
	}
800
    }
801
802
803
804
    UserError(\%errors)
	if (keys(%errors));

    return 0;
805
}
806
807

#
808
# Update a profile from a repository; this is invoked from the web hook.
809
#
810
811
812
813
814
815
816
817
818
819
sub UpdateProfileFromRepo()
{
    my $errmsg;
    usage()
	if (@ARGV != 1);

    my ($uuid)  = @ARGV;
    my $profile = APT_Profile->Lookup($uuid);
    if (!defined($profile)) {
	fatal("Could not lookup profile for update $uuid");
820
    }
821
822
823
824
825
    if (!defined($profile->repourl())) {
	fatal("Not a repo based profile");
    }
    my $repourl = $profile->repourl();

826
    #
827
828
    # We need to make sure the project exists and is a valid project for
    # the creator (current user). 
829
    #
830
831
832
    $project = Project->Lookup($profile->pid_idx());
    if (!defined($project)) {
	fatal("No such project exists");
833
    }
834
835
836
837
838
839
840
841
    elsif (!$project->AccessCheck($this_user, TB_PROJECT_MAKEIMAGEID())) {
	fatal("Not enough permission in this project");
    }
    if ($profile->Lock()) {
	print STDERR "Profile is busy, cannot lock it.\n";
	exit(1);
    }
    
842
    #
843
844
    # We want to update the profile from its URL, and get back the
    # new source code.
845
    #
846
847
848
849
850
    my $output = emutil::ExecQuiet("$MANAGEGITREPO update -o - -p $uuid");
    if ($?) {
	print STDERR $output;
	$profile->Unlock();
	fatal("Could not update repo from $repourl");
851
    }
852
853
    if ($verbose) {
	print $output . "\n";
854
    }
855
856
    if ($output =~ /\<rspec\>/) {
	$rspec = $output;
857
    }
858
859
    else {
	$script = $output;
860
    }
861
    #
862
    # Convert the script. If it fails we are not going to change the profile.
863
    #
864
865
866
867
868
    if (defined($script)) {
	my ($fh, $filename) = tempfile();
	if (!defined($fh)) {
	    $profile->Unlock();
	    fatal("Could not open temporary file for script");
869
	}
870
871
872
873
874
875
	print $fh $script;
	$output = emutil::ExecQuiet("$RUNGENILIB $filename");
	if ($?) {
	    print STDERR $output;
	    $profile->Unlock();
	    fatal("$RUNGENILIB failed");
876
	}
877
	$rspec = $output;
878
    }
879
    
880
    #
881
    # We mimic what VerifyXML() does, we have to set just a few things.
882
    #
883
884
    $new_args{"rspec"}  = $update_args{"rspec"}  = $rspec;
    $new_args{"script"} = $update_args{"script"} = $script if(defined($script));
885

886
887
888
889
890
891
892
893
894
    my $retval = ModifyProfileInternal($profile, $project, \$errmsg);
    $profile->Unlock();
    if ($retval) {
	if ($retval < 0) {
	    fatal($errmsg);
	}
	else {
	    print STDERR "$errmsg\n";
	    exit(1);
895
	}
896
    }
897
898
899
900
901
902
903
904
905
906
907
    my $profile_name = $profile->name();
    my $profile_pid  = $profile->pid();
    my $creator = User->Lookup($profile->creator_idx());
    $project->SendEmail($creator->email(),
	"Profile updated from Git repository",
	"Profile $profile_pid,$profile_name has been updated ".
	"from its git repository\n".
	"as the result of a push webhook.",
	$project->Brand()->OpsEmailAddress(),
	# Temporary.
	"BCC: " . $project->Brand()->OpsEmailAddress());
908
    
909
    return 0;
910
}
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934

#
# For a Parameterized Profile, need to generate and store the form
# data. Only python scripts of course. Does not return on error.
#
sub HandleScript($)
{
    my ($script) = @_;

    return undef
	if ($script !~ /^import/m);

    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);
    
    return $paramdefs;
}

935
936
937
938
939
940
exit(0);

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

941
942
943
    if (defined($webtask_id)) {
	$webtask->output($mesg);
	$webtask->Exited(-1);
944
    }
945
946
947
948
949
950
951
952
    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
953
954
# relies on using the same name attributes for the errors, as for the
# incoming values. This makes sense to use from Create/Update only.
955
#
956
sub UserError($)
957
{
958
959
960
961
    my ($ref) = @_;
    my $errors = {};

    if (ref($ref) eq "SCALAR") {
962
963
964
	$errors->{"error"} = $$ref;
    }
    elsif (ref($ref) eq "") {
965
	$errors->{"error"} = $ref;
966
    }
967
968
969
970
971
    else {
	$errors = $ref;
    }
    if (defined($webtask_id)) {
	my $xml = "<errors>\n";
972
	    
973
974
975
	foreach my $key (keys(%$errors)) {
	    $xml .= "<error name='$key'>" . CGI::escapeHTML($errors->{$key});
	    $xml .= "</error>\n";
976
	}
977
978
979
980
981
982
983
984
	$xml .= "</errors>\n";

	$webtask->Exited(1);
	$webtask->output($xml);
    }
    else {
	foreach my $key (keys(%$errors)) {
	    print "$key: " . $errors->{$key} . "\n";
985
986
987
988
989
990
991
992
993
994
995
996
997
	}
    }
    # Exit with positive status so web interface treats it as user error.
    exit(1);
}

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

    $str =~ s/[^[:alnum:]]/\\$&/g;
    return $str;
}
998
999
1000

#
# Delete a profile.
For faster browsing, not all history is shown. View entire blame