manage_profile.in 12.8 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
28
29
#!/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;
use Data::Dumper;
use CGI;
30
31
use POSIX ":sys_wait_h";
use POSIX qw(setsid);
32
33
34
35
36
37

#
# Back-end script to manage APT profiles.
#
sub usage()
{
38
39
    print("Usage: manage_profile [-u uuid | -s uuid] <xmlfile>\n");
    print("Usage: manage_profile [-r | -p] profile\n");
40
41
    exit(-1);
}
42
my $optlist     = "du:rs:t:fp";
43
44
my $debug       = 0;
my $verify      = 0;	# Check data and return status only.
45
my $update      = 0;
46
my $snap        = 0;
47
my $delete      = 0;
48
my $skipadmin   = 0;
49
50
51
my $force       = 0; # With delete.
my $uuid;
my $profile;
52
my $instance;
53
54
my $webtask;
my $webtask_id;
55
56
57
58
59
60

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
61
my $QUICKVM     = "$TB/sbin/protogeni/quickvm";
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

#
# 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;
84
85
86
use APT_Instance;
use GeniXML;
use GeniHRN;
87
use WebTask;
Leigh B Stoller's avatar
Leigh B Stoller committed
88
use libaudit;
89
90
91

# Protos
sub fatal($);
92
sub UserError(;$);
93
sub DeleteProfile($);
94
sub PublishProfile($);
95
96
97
98
99
100
101
102
103
104
105
106

#
# 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;
}
107
108
109
if (defined($options{"f"})) {
    $force = 1;
}
110
111
112
if (defined($options{"v"})) {
    $verify = 1;
}
113
114
if (defined($options{"u"})) {
    $update = 1;
115
    $uuid = $options{"u"};
116
}
117
if (defined($options{"s"})) {
118
119
    $snap = 1;
    $uuid = $options{"s"};
120
}
121
122
123
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
}
124
125
126
127
128
129
130
131
132
133
134
135
136
137
if (@ARGV != 1) {
    usage();
}
# 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!");
    }
}

# Remove profile.
if (defined($options{"r"})) {
138
    exit(DeleteProfile($ARGV[0]));
139
}
140
141
142
143
elsif (defined($options{"p"})) {
    exit(PublishProfile($ARGV[0]));
}

144
145
146
147
148
149
150
151
my $xmlfile  = shift(@ARGV);

#
# 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.
152
my $SLOT_UPDATE 	= 0x8;  # Allowed to update.
153
154
155
156
157
158
159
160
161
#
# 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],
162
     "profile_listed"      => ["listed",	$SLOT_OPTIONAL|$SLOT_UPDATE],
163
     "profile_public"      => ["public",	$SLOT_OPTIONAL|$SLOT_UPDATE],
Leigh B Stoller's avatar
Leigh B Stoller committed
164
     "profile_shared"      => ["shared",	$SLOT_OPTIONAL|$SLOT_UPDATE],
165
     "rspec"		   => ["rspec",		$SLOT_REQUIRED|$SLOT_UPDATE],
166
167
168
169
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
);

#
# 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 = ();
203
my %update_args = ();
204
205
206
207
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
240
241
242
243
244
245
246
247
248

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;
	}
    }
    if ($required & $SLOT_ADMINONLY && !$skipadmin) {
	# 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;
249
250
    $update_args{$dbslot} = $value
	if ($update && ($required & $SLOT_UPDATE));
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
}
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";
}

267
268
269
270
#
# Are we going to snapshot a node in an experiment? If so we
# sanity check to make sure there is just one node. 
#
271
272
if ($snap) {
    $instance = APT_Instance->Lookup($uuid);
273
    if (!defined($instance)) {
274
	fatal("Could not look up instance $uuid");
275
276
277
278
279
280
281
282
283
284
285
    }
    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();
    }
}
286
if ($update) {
287
    $profile = APT_Profile->Lookup($uuid);
288
    if (!defined($profile)) {
289
	fatal("Could not lookup profile for update $uuid");
290
    }
291
    # Kill the description.. No longer used.
292
293
294
295
296
297
298
299
    delete($update_args{"description"});

    #
    # If the rspec changed, then make a new version of the profile.
    # Everything else is metadata.
    #
    if (exists($update_args{"rspec"})) {
	if ($update_args{"rspec"} ne $profile->rspec()) {
300
301
302
303
304
	    if ($this_user->IsAdmin()) {
		$profile = $profile->NewVersion($this_user);
		if (!defined($profile)) {
		    fatal("Could not create new version of the profile");
		}
305
306
307
308
309
310
	    }
	    $profile->UpdateVersion({"rspec" => $update_args{"rspec"}});
	}
	delete($update_args{"rspec"});
    }
    $profile->UpdateMetaData(\%update_args) == 0 or
311
	fatal("Could not update profile record");
312

313
314
    # Bump the modtime.
    $profile->MarkModified();
315
316
317
}
else {
    my $usererror;
318
319

    $profile = APT_Profile->Lookup($new_args{"pid"}, $new_args{"name"});
320
321
322
323
324
    if (defined($profile)) {
	$errors{"profile_name"} = "Already in use";
	UserError();
    }
    $profile =
Leigh B Stoller's avatar
Leigh B Stoller committed
325
	APT_Profile->Create($profile, $project,
326
			    $this_user, \%new_args, \$usererror);
327
328
329
330
331
332
333
    if (!defined($profile)) {
	if (defined($usererror)) {
	    $errors{"profile_name"} = $usererror;
	    UserError();
	}
	fatal("Could not create new profile");
    }
334
335
336
    if (!$this_user->IsAdmin()) {
	$profile->Publish();
    }
337
}
338
339
340
341
342
343
344
345
346
347
348
349
350
351

#
# 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);
    my $apt_uuid   = $instance->uuid();
    my $imagename  = $profile->name();

352
353
354
355
356
357
    #
    # Grab the webtask object so we can watch it. We are looking
    # for it to finish, so we can unlock the profile for use. 
    #
    $webtask = WebTask->Create($profile->uuid(), $webtask_id);
    if (!defined($webtask)) {
358
	$profile->Delete(1);
359
    }
360
    $webtask->AutoStore(1);
361
362

    if ($profile->Lock()) {
363
	$profile->Delete(1);
364
365
366
367
368
	fatal("Could not lock new profile");
    }

    my $command = "$QUICKVM " . ($webtask_id ? "-t $webtask_id " : " ") .
	"-s $apt_uuid $sliver_urn $imagename";
369
370
371
372
373
374
375
376
    #
    # This returns pretty fast, and then the imaging takes place in
    # the background at the aggregate. quickvm 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 ($?) {
377
	$profile->Delete(1);
378
	$webtask->Delete();
379
380
381
382
383
384
385
386
387
388
389
	fatal("Failed to create disk image!");
    }
    #
    # Parse the output to get the new image urn, then stick that
    # into the rspec, and update the database.
    #
    my $image_urn;
    if ($output =~ /^(urn:.*),/) {
	$image_urn = $1;
    }
    else {
390
	$profile->Delete(1);
391
392
	fatal("Could not find image urn in:\n$output");
    }
393
394
395
396
    # Again, this only makes sense for single node profiles.
    if ($profile->UpdateDiskImage($image_urn)) {
	$profile->Delete(1);
	fatal("Could not update image URN in rspec");
397
    }
398
399
400
401
402
403
404
405
406
407
408

    #
    # Exit and leave child to poll.
    #
    if (! $debug) {
	my $child = fork();
	if ($child) {
	    exit(0);
	}
	# Let parent exit;
	sleep(2);
Leigh B Stoller's avatar
Leigh B Stoller committed
409
410
411
412
413
	if (0) {
	    AuditStart(0, undef, LIBAUDIT_LOGTBLOGS()|LIBAUDIT_LOGONLY());
	    AddAuditInfo("cc", "aptnet-logs\@flux.utah.edu");
	}
	POSIX::setsid();
414
415
416
417
418
419
420
421
422
423
424
425
426
    }
    my $seconds  = 1200;
    my $interval = 5;

    while ($seconds >= 0) {
	sleep($interval);
	$seconds -= $interval;

	$webtask->Refresh();
	last
	    if (defined($webtask->exited()));
    }
    if ($webtask->exitcode()) {
427
	$profile->Delete(1);
428
429
430
431
	exit(1);
    }
    $profile->Unlock();
    exit(0);
432
}
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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.
#
450
sub UserError(;$)
451
{
452
453
454
455
456
    my ($msg) = @_;
    
    if (defined($msg)) {
	$errors{"error"} = $msg;
    }
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
    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;
}
476
477
478
479
480
481
482
483
484
485
486

#
# Delete a profile.
#
sub DeleteProfile($)
{
    my ($name)  = @_;
    my $profile = APT_Profile->Lookup($name);
    if (!defined($profile)) {
	fatal("No such profile exists");
    }
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    #
    # Not allowed to delete a published profile, yet. Needs thought.
    #
    if (defined($profile->published())) {
	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");
526
527
    return 0;
}