manage_profile.in 11.2 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
    print("Usage: manage_profile [-u | -s uuid] <xmlfile>\n");
39
40
41
    print("Usage: manage_profile -r profile\n");
    exit(-1);
}
42
my $optlist     = "durs:t:";
43
44
my $debug       = 0;
my $verify      = 0;	# Check data and return status only.
45
46
my $update      = 0;
my $delete      = 0;
47
my $skipadmin   = 0;
48
49
my $snapuuid;
my $instance;
50
51
my $webtask;
my $webtask_id;
52
53
54
55
56
57

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

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

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

#
# 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;
}
if (defined($options{"v"})) {
    $verify = 1;
}
106
107
108
if (defined($options{"u"})) {
    $update = 1;
}
109
110
111
if (defined($options{"s"})) {
    $snapuuid = $options{"s"};
}
112
113
114
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
}
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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"})) {
129
    exit(DeleteProfile($ARGV[0]));
130
131
132
133
134
135
136
137
138
}
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.
139
my $SLOT_UPDATE 	= 0x8;  # Allowed to update.
140
141
142
143
144
145
146
147
148
#
# 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],
149
     "profile_listed"      => ["listed",	$SLOT_OPTIONAL|$SLOT_UPDATE],
150
     "profile_public"      => ["public",	$SLOT_OPTIONAL|$SLOT_UPDATE],
Leigh B Stoller's avatar
Leigh B Stoller committed
151
     "profile_shared"      => ["shared",	$SLOT_OPTIONAL|$SLOT_UPDATE],
152
     "rspec"		   => ["rspec",		$SLOT_REQUIRED|$SLOT_UPDATE],
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
);

#
# 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 = ();
190
my %update_args = ();
191
192
193
194
195
196
197
198
199
200
201
202
203
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

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;
236
237
    $update_args{$dbslot} = $value
	if ($update && ($required & $SLOT_UPDATE));
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
}
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";
}

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#
# Are we going to snapshot a node in an experiment? If so we
# sanity check to make sure there is just one node. 
#
if (defined($snapuuid)) {
    $instance = APT_Instance->Lookup($snapuuid);
    if (!defined($instance)) {
	fatal("Could not look up instance $snapuuid");
    }
    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();
    }
}

274
275
276
277
278
my $profile = APT_Profile->Lookup($new_args{"pid"}, $new_args{"name"});

if ($update) {
    if (!defined($profile)) {
	$errors{"profile_name"} = "No such profile exists";
279
280
	UserError();
    }
281
282
283
    # Kill the description.. No longer used.
    $update_args{"description"} = "";
    
284
285
    $profile->Update(\%update_args) == 0 or
	fatal("Could not update profile record");
286
287
    # Bump the modtime.
    $profile->MarkModified();
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
}
else {
    my $usererror;
    if (defined($profile)) {
	$errors{"profile_name"} = "Already in use";
	UserError();
    }
    $profile =
	APT_Profile->Create($project, $this_user, \%new_args, \$usererror);
    if (!defined($profile)) {
	if (defined($usererror)) {
	    $errors{"profile_name"} = $usererror;
	    UserError();
	}
	fatal("Could not create new profile");
    }
304
}
305
306
307
308
309
310
311
312
313
314
315
316
317
318

#
# 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();

319
320
321
322
323
324
325
326
    #
    # 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)) {
	$profile->Delete();
    }
327
    $webtask->AutoStore(1);
328
329
330
331
332
333
334
335

    if ($profile->Lock()) {
	$profile->Delete();
	fatal("Could not lock new profile");
    }

    my $command = "$QUICKVM " . ($webtask_id ? "-t $webtask_id " : " ") .
	"-s $apt_uuid $sliver_urn $imagename";
336
337
338
339
340
341
342
343
344
    #
    # 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 ($?) {
	$profile->Delete();
345
	$webtask->Delete();
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
	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 {
	$profile->Delete();
	fatal("Could not find image urn in:\n$output");
    }
    my $rspec = GeniXML::Parse($profile->rspec());
    if (! defined($rspec)) {
	$profile->Delete();
	fatal("Could not parse rspec");
    }
    ($node) = GeniXML::FindNodes("n:node", $rspec)->get_nodelist();
    GeniXML::SetDiskImage($node, $image_urn);
    if ($profile->Update({"rspec" => GeniXML::Serialize($rspec)})) {
	$profile->Delete();
	fatal("Could not update rspec");
    }
371
372
373
374
375
376
377
378
379
380
381

    #
    # 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
382
383
384
385
386
	if (0) {
	    AuditStart(0, undef, LIBAUDIT_LOGTBLOGS()|LIBAUDIT_LOGONLY());
	    AddAuditInfo("cc", "aptnet-logs\@flux.utah.edu");
	}
	POSIX::setsid();
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    }
    my $seconds  = 1200;
    my $interval = 5;

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

	$webtask->Refresh();
	last
	    if (defined($webtask->exited()));
    }
    if ($webtask->exitcode()) {
	$profile->Delete();
	exit(1);
    }
    $profile->Unlock();
    exit(0);
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
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.
#
sub UserError()
{
    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;
}
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

#
# Delete a profile.
#
sub DeleteProfile($)
{
    my ($name)  = @_;
    my $profile = APT_Profile->Lookup($name);
    if (!defined($profile)) {
	fatal("No such profile exists");
    }
    $profile->Delete() == 0 or
	fatal("Could not delete profile");
    return 0;
}