manage_dataset.in 20.6 KB
Newer Older
1
2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2016 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
28
29
30
31
32
33
34
35
36
37
38
39
# 
# {{{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 Data::Dumper;
use POSIX ":sys_wait_h";
use POSIX qw(setsid close);
use Date::Parse;

#
# Back-end script to manage APT profiles.
#
sub usage()
{
    print STDERR "Usage: manage_dataset [options --] create ...\n";
    print STDERR "Usage: manage_dataset [options --] delete ...\n";
    print STDERR "Usage: manage_dataset [options --] refresh ...\n";
40
41
    print STDERR "Usage: manage_dataset [options --] modify ...\n";
    print STDERR "Usage: manage_dataset [options --] extend ...\n";
42
    print STDERR "Usage: manage_dataset [options --] snapshot ...\n";
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    exit(-1);
}
my $optlist     = "dt:";
my $debug       = 0;
my $webtask_id;
my $webtask;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";

#
# 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 libtestbed;
use EmulabConstants;
use emdb;
use emutil;
use User;
use Project;
use APT_Dataset;
78
use APT_Instance;
79
80
81
use WebTask;
use Blockstore;
use GeniResponse;
82
use GeniXML;
83
84
85

# Protos
sub fatal($);
86
sub uerror($);
87
88
89
90
sub DoCreate();
sub DoDelete();
sub DoRefresh();
sub DoRefreshInternal($$);
91
92
sub DoModify();
sub DoExtend();
93
sub DoSnapshot();
94
sub DoSnapShotInternal($$$$$);
95
sub PollDatasetStatus($$);
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (grep {$_ eq "--"} @ARGV &&
    ! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
111
112
113
114
115
    $webtask = WebTask->LookupOrCreate(undef, $webtask_id);
    if (!defined($webtask)) {
	fatal("Could not create webtask object");
    }
    $webtask->AutoStore(1);
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
}
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!");
    }
}
my $action = shift(@ARGV);

if ($action eq "create") {
    exit(DoCreate());
}
elsif ($action eq "delete") {
    exit(DoDelete());
}
elsif ($action eq "refresh") {
    exit(DoRefresh());
}
140
141
142
143
144
145
elsif ($action eq "modify") {
    exit(DoModify());
}
elsif ($action eq "extend") {
    exit(DoExtend());
}
146
147
148
elsif ($action eq "snapshot") {
    exit(DoSnapshot());
}
149
150
151
152
153
154
155
156
157
158
159
160
else {
    usage();
}
exit(1);

#
# 
#
sub DoCreate()
{
    my $usage = sub {
	print STDERR "Usage: manage_dataset create ".
161
	    "[-t type] [-f fstype] [-e expiration] ".
162
	    "[-R global|project] [-W creator|project] ".
163
	    "-a am_urn -s size pid/name\n";
164
165
	exit(-1);
    };
166
    my $aggregate_urn;
167
168
169
    my $errmsg;
    my $pid;
    my $expires;
170
    my $size = 0;
171
172
    my $type = "stdataset";
    my $fstype;
173
174
    my $read_access;
    my $write_access;
175
    # imdataset snapshot info.
176
    my ($instance,$aggregate,$nodeid,$bsname);
177
    
178
    my $optlist = "ds:t:e:f:w:p:R:W:I:i:a:";
179
180
181
182
183
184
185
186
187
188
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"d"})) {
	$debug = 1;
    }
    if (defined($options{"t"})) {
	$type = $options{"t"};
	&$usage()
189
190
	    if (! ($type eq "stdataset" || $type eq "ltdataset" ||
		   $type eq "imdataset"));
191
    }
192
193
194
195
196
197
    if (defined($options{"a"})) {
	$aggregate_urn = $options{"a"};
    }
    elsif ($type ne "imdataset") {
	&$usage();
    }
198
    if ($type eq "imdataset") {
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
	if (!exists($options{"i"})) {
	    print STDERR "Must provide -i opton for imdatasets\n";
	    &$usage();
	}
	if (!exists($options{"I"})) {
	    print STDERR "Must provide -I opton for imdatasets\n";
	    &$usage();
	}
	$instance = APT_Instance->Lookup($options{"i"});
	if (!defined($instance)) {
	    fatal("Instance does not exist!");
	}
	($nodeid,$bsname) = split(",", $options{"I"});
	if (! (defined($nodeid) && defined($bsname))) {
	    print STDERR "Improper -I opton for imdatasets\n";
214
215
	    &$usage();
	}
216
217
218
219
	$aggregate = $instance->FindAggregateByNodeId($nodeid);
	if (!defined($aggregate)) {
	    fatal("Could not find aggregate for $nodeid");
	}
220
	$aggregate_urn = $aggregate->aggregate_urn();
221
    }
222
    else {
223
	if (!APT_Dataset::ValidBlockstoreBackend($aggregate_urn)) {	
224
225
226
	    fatal("Invalid cluster selection");
	}
    }
227
228
229
230
231
232
233
234
235
236
237
238
    if (defined($options{"f"})) {
	$fstype = $options{"f"};
	&$usage()
	    if ($fstype !~ /^(ext2|ext3|ext4|ufs|ufs2)$/);
    }
    if (defined($options{"R"})) {
	$read_access = $options{"R"};
	&$usage()
	    if ($read_access !~ /^(global|project)$/);
    }
    if (defined($options{"W"})) {
	$write_access = $options{"W"};
Leigh B Stoller's avatar
Leigh B Stoller committed
239
	&$usage()
240
	    if ($write_access !~ /^(creator|project)$/);
Leigh B Stoller's avatar
Leigh B Stoller committed
241
    }
242
243
244
245
246
247
248
249
250
    if (defined($options{"s"})) {
	if ($options{"s"} =~ /^(\d+)$/) {
	    $size = $1;
	}
	elsif ($options{"s"} =~ /^(\d+)(\w+)$/) {
	    $size = Blockstore::ConvertToMebi($options{"s"});
	    if ($size < 0) {
		fatal("Could not parse size.");
	    }
251
252
253
	    if ($size <= 1) {
		fatal("Size too small, try a little bigger");
	    }
254
255
256
257
258
259
260
261
262
263
264
265
	}
	else {
	    &$usage();
	}
    }
    if (defined($options{"e"})) {
	$expires = str2time($options{"e"});
	if (!defined($expires)) {
	    fatal("Could not parse expiration date.");
	}
	$expires = $options{"e"};
    }
266
    
267
    &$usage()
268
	if (@ARGV != 1 || !defined($aggregate_urn) ||
269
	    ($type ne "imdataset" && !defined($size)) ||
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
	    ($type eq "stdataset" && !defined($expires)));
    my $name = shift(@ARGV);

    if ($name =~ /^([-\w]+)\/([-\w]+)$/) {
	$pid  = $1;
	$name = $2;
    }
    else {
	fatal("Dataset name $name not in the form <pid>/<name>.");
    }
    my $project = Project->Lookup($pid);
    if (!defined($project)) {
	fatal("No such project");
    }
    if (!$project->AccessCheck($this_user, TB_PROJECT_CREATELEASE())) {
	fatal("Not enough permission in project");
    }
    &$usage()
	if ($type eq "stdataset" && !defined($expires));

    if (APT_Dataset->Lookup("$pid/$name")) {
	fatal("Dataset already exists!");
    }

    my $blob = {
	"dataset_id"     => $name,
	"pid"            => $project->pid(),
	"pid_idx"        => $project->pid_idx,
	"creator_uid"    => $this_user->uid(),
	"creator_idx"    => $this_user->uid_idx(),
	"aggregate_urn"  => $aggregate_urn,
	"type"           => $type,
	"size"           => $size,
    };
    $blob->{"fstype"} = $fstype
	if (defined($fstype));
Leigh B Stoller's avatar
Leigh B Stoller committed
306
    $blob->{"expires"} = TBDateStringLocal($expires)
307
	if (defined($expires));
308
309
310
311
    $blob->{"read_access"} = $read_access
	if (defined($read_access));
    $blob->{"write_access"} = $write_access
	if (defined($write_access));
312
313
314
315
316

    my $dataset = APT_Dataset->Create($blob);
    if (!defined($dataset)) {
	fatal("Internal error creating dataset object");
    }
317
    
318
319
320
321
322
323
324
325
    # new dataset is returned locked. If we have instance, try to lock
    # that now, else its a failure.
    if ($type eq "imdataset" && defined($instance)) {
	if ($instance->Lock()) {
	    $errmsg = "Instance is busy, cannot snapshot data";
	    goto failed;
	}
    }
326
327
328
329
330
331
332
333
334
335
336
    #
    # For IM datasets always create a webtask for tracking imaging status.
    #
    if ($type eq "imdataset") {
	$webtask = WebTask->Create($dataset->uuid());
	if (!defined($webtask)) {
	    $errmsg = "Could not create webtask object";
	    goto failed;
	}
	$webtask->AutoStore(1);
    }
337
338
339
340
341
342
    #
    # Ask the aggregate to create the dataset. 
    #
    my $response = $dataset->CreateDataset();
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	$errmsg = "CreateDataset failed: ". $response->output() . "\n";
343
344
	$instance->Unlock()
	    if (defined($instance));
345
346
347
	goto failed;
    }
    $blob = $response->value();
348
349
    $dataset->Update({"remote_uuid" => $blob->{"uuid"},
		      "remote_urn"  => $blob->{"urn"}});
350
351
352
    if (exists($blob->{'url'}) && $blob->{'url'} ne "") {
	$dataset->Update({"remote_url" => $blob->{"url"}});
    }
353

354
355
356
357
358
359
360
361
362
363
364
    #
    # Okay, this is silly; there is no distinct state for resource allocation.
    # It is unapproved and locked. The other side tells us its locked in the
    # blob (busy), so look for this and set the state to busy. Then we poll
    # waiting for the lease to go nonbusy and approved. Ick.
    #
    if ($blob->{"busy"}) {
	$dataset->Update({"state" => "busy"});
    }
    else {
	$dataset->Update({"state" => $blob->{"state"}});
365
366
367
368
	if ($type ne "imdataset" || !defined($instance)) {
	    $dataset->Unlock();
	    return 0;
	}
369
    }
370
371
372
373
    #
    # Handoff to snapshot if an imdataset.
    #
    if ($type eq "imdataset" &&
374
	DoSnapShotInternal($dataset, $aggregate,
375
			   $bsname, $nodeid, \$errmsg)) {
376
377
378
379
380
381
382
383
	$response = $dataset->DeleteDataset();
	if ($response->code() == GENIRESPONSE_SUCCESS ||
	    $response->code() == GENIRESPONSE_SEARCHFAILED) {
	    $instance->Unlock();
	    goto failed;
	}
	# We want to keep the local dataset record around since we could
	# not delete it remotely.
384
	$instance->Unlock();
385
386
	# This will set the webtask, see below.
	fatal($errmsg);
387
    }
388
389
390
    if (PollDatasetStatus($dataset, \$errmsg)) {
	# Exit and let child poll
	exit(0);
391
392
    }
    $dataset->Unlock();
393
    $instance->Unlock() if (defined($instance));
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    return 0;

  failed:
    $dataset->Delete()
	if (defined($dataset));
    # This will set the webtask, see below.
    fatal($errmsg);
}

#
# Delete
#
sub DoDelete()
{
408
    my $errmsg  = "Could not delete dataset";
409
410
411
412
413
414
415
416
417
418
    
    if (@ARGV != 1) {
	fatal("usage: $0 delete pid/name");
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    if ($dataset->Lock()) {
419
	uerror("dataset is busy, cannot lock it");
420
421
    }
    my $response = $dataset->DeleteDataset();
Leigh B Stoller's avatar
Leigh B Stoller committed
422
    if ($response->code() != GENIRESPONSE_SUCCESS &&
423
424
	$response->code() != GENIRESPONSE_SEARCHFAILED &&
	$response->code() != GENIRESPONSE_BUSY) {
425
426
427
	$errmsg = "DeleteDataset failed: ". $response->output() . "\n";
	goto failed;
    }
428
    if ($response->code() == GENIRESPONSE_BUSY) {
429
430
431
	$dataset->Unlock();
	uerror("dataset was busy at the remote cluster, try again later");
    }
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
    $dataset->Delete();
    return 0;

  failed:
    $dataset->Unlock();
    # This will set the webtask, see below.
    fatal($errmsg);
}

#
# Refresh
#
sub DoRefresh()
{
    my $errmsg;
    
    if (@ARGV != 1) {
	fatal("usage: $0 refresh pid/name");
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    if ($dataset->Lock()) {
457
	uerror("dataset is busy, cannot lock it");
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
    }
    if (DoRefreshInternal($dataset, \$errmsg)) {
	goto failed;
    }
    $dataset->Unlock();
    return 0;

  failed:
    $dataset->Unlock();
    # This will set the webtask, see below.
    fatal($errmsg);
}

sub DoRefreshInternal($$)
{
    my ($dataset, $pmesg) = @_;
    
    my $response = $dataset->DescribeDataset();
    if ($response->code() != GENIRESPONSE_SUCCESS) {
477
	if ($response->code() == GENIRESPONSE_SEARCHFAILED) {
478
	    $$pmesg = "Dataset no longer exists at the remote cluster\n";
479
480
481
482
	}
	else {
	    $$pmesg = "DescribeDataset failed: ". $response->output() . "\n";
	}
483
484
485
	return -1;
    }
    my $blob = $response->value();
486
487
    print STDERR Dumper($blob);
    
488
489
490
491
492
    $dataset->Update({"last_used" => TBDateStringLocal($blob->{"lastused"}),
		      "expires"   => TBDateStringLocal($blob->{"expires"})});

    if ($blob->{"busy"}) {
	$dataset->Update({"state" => "busy"});
493
494
495
496
497
498
499
500
	if ($dataset->type() eq "imdataset") {
	    if (defined($webtask)) {
		$webtask->image_size($blob->{'image_size'}) 	
		    if (exists($blob->{'image_size'}));
		$webtask->image_status($blob->{'image_status'})
		    if (exists($blob->{'image_status'}));
	    }
	}
501
502
503
    }
    else {
	$dataset->Update({"state" => $blob->{"state"}});
504
505
	if ($dataset->type() eq "imdataset") {
	    $dataset->Update({"size" => $blob->{"size"}});
506
507
508
509
510
511
	    if (defined($webtask)) {
		$webtask->image_size($blob->{'image_size'}) 	
		    if (exists($blob->{'image_size'}));
		$webtask->image_status($blob->{'image_status'})
		    if (exists($blob->{'image_status'}));
	    }
512
	}
513
    }
514
515
516
    return 0;
}

517
518
519
520
521
522
523
524
525
#
# Modify
#
sub DoModify()
{
    my $errmsg;
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset modify ".
526
	    "[-R global|project] [-W creator|project] pid/name\n";
527
528
	exit(-1);
    };
529
    my $optlist = "R:W:";
530
531
532
533
534
535
536
537
538
539
540
541
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (@ARGV != 1) {
	&$usage();
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
542
543
544
    my $blob = {};
    if (defined($options{"R"})) {
	my $read_access = $options{"R"};
545
	&$usage()
546
547
	    if ($read_access !~ /^(global|project)$/);
	$blob->{'read_access'} = $read_access;
548
    }
549
550
551
552
553
    if (defined($options{"W"})) {
	my $write_access = $options{"W"};
	&$usage()
	    if ($write_access !~ /^(creator|project)$/);
	$blob->{'write_access'} = $write_access;
554
555
    }
    if ($dataset->Lock()) {
556
	uerror("dataset is busy, cannot lock it");
557
    }
558
559
    if (keys(%$blob)) {
	if ($dataset->Update($blob)) {
560
561
562
563
564
565
566
567
568
569
570
571
572
573
	    $errmsg = "Could not update privacy settings!";
	    goto failed;
	}
    }
    my $response = $dataset->ModifyDataset();
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	if ($response->code() == GENIRESPONSE_SEARCHFAILED) {
	    $errmsg = "Dataset no longer exists at the target\n";
	}
	else {
	    $errmsg = "ModifyDataset failed: ". $response->output() . "\n";
	}
	goto failed;
    }
574
    $blob = $response->value();
575
576
577
    if ($dataset->type() ne "imdataset") {
	$dataset->Update({"expires" => TBDateStringLocal($blob->{"expires"})});
    }
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    $dataset->Unlock();
    return 0;

  failed:
    $dataset->Unlock();
    # This will set the webtask, see below.
    fatal($errmsg);
}

#
# Extend
#
sub DoExtend()
{
    my $errmsg;
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset extend pid/name\n";
	exit(-1);
    };
    if (@ARGV != 1) {
	&$usage();
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    if ($dataset->Lock()) {
607
	uerror("dataset is busy, cannot lock it");
608
609
610
611
612
613
614
615
616
617
618
619
620
    }
    my $response = $dataset->ExtendDataset();
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	if ($response->code() == GENIRESPONSE_SEARCHFAILED) {
	    $errmsg = "Dataset no longer exists at the target\n";
	}
	else {
	    $errmsg = "ExtendDataset failed: ". $response->output() . "\n";
	}
	goto failed;
    }
    my $blob = $response->value();
    $dataset->Update({"expires" => TBDateStringLocal($blob->{"expires"})});
621
622
623
    if (exists($blob->{'state'})) {
	$dataset->Update({"state" => $blob->{'state'}});
    }
624
625
626
627
628
629
630
631
632
    $dataset->Unlock();
    return 0;

  failed:
    $dataset->Unlock();
    # This will set the webtask, see below.
    fatal($errmsg);
}

633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#
# Snapshot an image backed dataset
#
sub DoSnapshot()
{
    my $errmsg;
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset snapshot ".
	    "-i instance -b bsname pid/name nodeid\n";
	exit(-1);
    };
    my $optlist = "b:i:";
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    &$usage()
	if (! (@ARGV == 2 && exists($options{"b"}) && exists($options{"i"})));
    
    my $bsname  = $options{"b"};
    my $token   = shift(@ARGV);
    my $nodeid  = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    if ($dataset->type() ne "imdataset") {
661
	fatal("Only image backed datasets supported");
662
663
664
    }
    my $instance = APT_Instance->Lookup($options{"i"});
    if (!defined($instance)) {
665
666
	fatal("No such instance");
    }
667
668
669
670
    my $aggregate = $instance->FindAggregateByNodeId($nodeid);
    if (!defined($aggregate)) {
	fatal("Could not find aggregate for $nodeid");
    }
671
    if ($dataset->Lock()) {
672
	uerror("dataset is busy, cannot lock it");
673
674
    }
    if ($instance->Lock()) {
675
676
	$dataset->Unlock();
	uerror("instance is busy, cannot lock it");
677
    }
678
679
680
681
    #
    # Always create a webtask for tracking imaging status. Must be
    # associated with the object.
    #
682
    if (defined($webtask)) {
683
684
685
686
687
688
689
690
691
692
693
	if ($webtask->object_uuid() ne $dataset->uuid()) {
	    $errmsg = "Webtask not associated with dataset!";
	    goto failed;
	}
    }
    else {
	$webtask = WebTask->LookupOrCreate($dataset->uuid());
	if (!defined($webtask)) {
	    $errmsg = "Could not create webtask object!";
	    goto failed;
	}
694
695
	$webtask->AutoStore(1);
    }
696
    
697
    if (DoSnapShotInternal($dataset, $aggregate, $bsname, $nodeid, \$errmsg)) {
698
699
	goto failed;
    }
700
701
702
703
    if (PollDatasetStatus($dataset, \$errmsg)) {
	# Exit and let child poll
	exit(0);
    }
704
705
706
707
708
    $instance->Unlock();
    $dataset->Unlock();
    return 0;
    
  failed:
709
    $instance->Unlock();
710
711
712
713
714
715
716
    $dataset->Unlock();
    # This will set the webtask, see below.
    fatal($errmsg);
}

sub DoSnapShotInternal($$$$$)
{
717
    my ($dataset, $aggregate, $bsname, $nodeid, $perrmsg) = @_;
718
719
    my $errmsg;
    
720
    my $manifest = GeniXML::Parse($aggregate->manifest());
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    if (! defined($manifest)) {
	$errmsg = "Could not parse manifest";
	goto failed;
    }
    my $sliver_urn;
    my @nodes = GeniXML::FindNodes("n:node", $manifest)->get_nodelist();
    foreach my $node (@nodes) {
	my $client_id = GeniXML::GetVirtualId($node);
	if ($nodeid eq $client_id) {
	    $sliver_urn = GeniXML::GetSliverId($node);
	    #
	    # But check that the bsname is on this node.
	    #
	    my $found = 0;
	    foreach my $blockref
		(GeniXML::FindNodesNS("n:blockstore", $node,
				      $GeniXML::EMULAB_NS)->get_nodelist()) {
		    my $name = GeniXML::GetText("name", $blockref);
		    if ($name eq $bsname) {
			$found = 1;
			last;
		    }
	    }
	    if (!$found) {
		$errmsg = "No such blockstore $bsname on node $nodeid";
		goto failed;
	    }
	    last;
	}
    }
    if (!defined($sliver_urn)) {
	$errmsg = "Could not find node '$nodeid' in manifest";
	goto failed;
    }
755
    my $response = $aggregate->CreateImage($sliver_urn,
756
757
					   $dataset->dataset_id(),
					   0, undef, $bsname);
758
759
760
761
762
763
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	$errmsg = "SnapshotDataset failed: ". $response->output() . "\n";
	goto failed;
    }
    $dataset->Update({"state" => "busy"});
    return 0;
764

765
  failed:
766
767
    $$perrmsg = $errmsg;
    return -1;
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

#
# Poll for snapshot status.
#
sub PollDatasetStatus($$)
{
    my ($dataset, $perrmsg) = @_;
    my $project = $dataset->GetProject();
    my $dname   = $dataset->dataset_id();
    my $logfile;

    #
    # If busy, then allocation is in progress. We leave it locked and
    # poll in the background for a while, hoping for it to eventually
    # stop being busy. Eventually might have to replace this, since
    # polling got any non-small length of time will lead to trouble.
    #
    if (! $debug) {
        $logfile = TBMakeLogname("createdataset");

	if (my $childpid = TBBackGround($logfile)) {
	    return $childpid;
	}
	# Let parent exit;
	sleep(2);
    }
    $webtask->SetProcessID($PID)
	if (defined($webtask));

    my $seconds  = 1200;
    my $interval = 5;
    
    while ($seconds > 0) {
	$seconds -= $interval;
	if (DoRefreshInternal($dataset, $perrmsg)) {
	    print STDERR $$perrmsg;
	    sleep($interval);
	    next;
	}
	if ($dataset->state() eq "valid") {
	    $project->SendEmail($this_user->email(),
			"Your dataset is now ready to use",
811
			"Dataset '$dname' is now ready to use.\n",
812
				$project->LogsEmailAddress(), undef, $logfile);
813
814
815
816
817
818
819
820
821
	    $webtask->Exited(0)
		if (defined($webtask));
	    last;
	}
	sleep($interval);
    }
    $webtask->Exited(-1)
	if (defined($webtask) && $seconds <= 0);
    
Leigh B Stoller's avatar
Leigh B Stoller committed
822
823
    unlink($logfile)
	if (defined($logfile));
824
825
826
    return 0;
}

827
828
829
830
831
832
833
834
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(-1);
    }
835
    print STDERR "$mesg\n";
836
837
838
839
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

840
841
842
843
844
845
846
847
848
849
850
851
sub uerror($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(1);
    }
    print STDERR "$mesg\n";
    exit(1);
}

852
853
854
855
856
857
858
859
sub escapeshellarg($)
{
    my ($str) = @_;

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