template_export.in 11.8 KB
Newer Older
1
#!/usr/bin/perl -w
2 3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2006, 2007 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16
# All rights reserved.
#
use English;
use strict;
use Getopt::Std;
use POSIX qw(isatty setsid);
use POSIX qw(strftime);
use Errno qw(EDQUOT);
use XML::Simple;
use Data::Dumper;

#
17 18 19
# Export a template. The first form exports from an instance of a template,
# optionally at a specific run/tag. The second form exports from the
# template itself, optionally at a specific tag.
20 21 22 23 24 25 26 27 28 29 30 31 32
#
# Exit codes are important; they tell the web page what has happened so
# it can say something useful to the user. Fatal errors are mostly done
# with die(), but expected errors use this routine. At some point we will
# use the DB to communicate the actual error.
#
# $status < 0 - Fatal error. Something went wrong we did not expect.
# $status = 0 - Everything okay.
# $status > 0 - Expected error. User not allowed for some reason. 
# 
sub usage()
{
    print(STDERR
33 34
	  "Usage: template_export [-q] [-s] [-r runidx | -t tag] -i <idx>\n".
	  "       template_export [-q] [-s] [-t tag] guid/vers\n".
35 36
	  "switches and arguments:\n".
	  "-q           - be less chatty\n".
37
	  "-o           - overwrite existing export directory\n".
38
	  "-s           - spew to stdout (as for web page).\n".
39
	  "-t           - specific archive tag to export.\n".
40
	  "-i <idx>     - Instance index to export\n".
41 42
	  "-r <runidx>  - Run index to export\n".
	  "guid/vers    - The template to export.\n");
43 44
    exit(-1);
}
45
my $optlist	 = "qi:dsr:ot:";
46 47 48 49
my %options      = ();
my $spew         = 0;
my $quiet        = 0;
my $debug        = 0;
50 51 52 53
my $overwrite    = 0;
my $template_mode= 0;
my $guid;
my $version;
54
my $exptidx;
55
my $runidx;
56
my $tag;
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

#
# Configure variables
#
my $TB		= "@prefix@";
my $EVENTSYS	= @EVENTSYS@;
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
my $TBDOCBASE	= "@TBDOCBASE@";
my $TBBASE	= "@TBBASE@";
my $CONTROL     = "@USERNODE@";
my $checkquota  = "$TB/sbin/checkquota";
my $TAR         = "/usr/bin/tar";

# Locals
my $template;
my $instance;
74
my $pid;
75 76 77 78
my $project;
my $archive;
my %bindings;
my $checkout;
79 80 81 82 83

# Protos
sub ParseArgs();
sub fatal($$);
sub cleanup();
84 85
sub ExportTemplate();
sub ExportInstance();
86 87 88 89 90 91 92 93 94

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
use Template;
95
use User;
96 97 98
use Project;
use Archive;
use Experiment;
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

# In libdb
my $projroot = PROJROOT();

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

#
# Set umask for start/swap. We want other members in the project to be
# able to swap/end experiments, so the log and intermediate files need
# to be 664 since some are opened for append.
#
umask(0002);

#
# Untaint the path
#
# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Verify user and get his DB uid.
#
125 126 127
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
128 129 130 131 132 133
}

# Now parse arguments.
ParseArgs();

#
134 135
# Depending on call method, we find the template, or the instance and
# then the template.
136
#
137 138 139 140 141 142 143 144 145
if ($template_mode) {
    $template = Template->Lookup($guid, $version);

    if (!defined($template)) {
	fatal(-1, "Could not get template record for $guid/$version!");
    }
    $project = $template->GetProject();
    $pid     = $project->pid();
    $archive = $template->GetArchive();
146
}
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
else {
    #
    # Grab instance info and do access check via the template.
    #
    $instance = Template::Instance->LookupByExptidx($exptidx);
    if (!defined($instance)) {
	fatal(-1, "Could not get instance record for experiment $exptidx!");
    }
    $template = $instance->template();
    $project  = $template->GetProject();
    $pid      = $project->pid();
    $archive  = $template->GetArchive();
    $guid     = $template->guid();
    $version  = $template->vers();
}

if (! $project->AccessCheck($this_user, TB_PROJECT_READINFO)) {
    tberror("You do not have permission to export from $template");
165 166 167
    exit(1);
}

168
if (system("$checkquota " . $this_user->uid()) != 0) {
169 170
    tberror("You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
171 172 173 174 175 176
    exit(1);
}

#
# Checkout to the project tree.
#
177 178 179 180 181 182 183 184 185 186 187 188 189
if ($spew) {
    $checkout = "/var/tmp/export.$$";
}
elsif ($template_mode) {
    $checkout  = "$projroot/$pid/export/$guid/$version/";
    $checkout .= "/$tag"
	if (defined($tag));
}
else {
    $checkout = "$projroot/$pid/export/$guid/$version/$exptidx";
    $checkout .= "/$tag"
	if (defined($tag));
}
190 191 192

# Cleanup existing goo.
if (-e $checkout) {
193 194 195 196 197 198
    if (!$overwrite) {
	# Exit status tells web interface what has happened.
	print STDERR "Export directory already exists; ".
	    "use overwite option (-o).\n";
	exit(2);
    }
199 200 201 202 203 204 205 206 207 208
    my $dirtoremove = $checkout;

    $dirtoremove .= "/run${runidx}"
	if (defined($runidx));

    system("/bin/rm -rf $dirtoremove");
}
if (! -e $checkout) {
    system("mkdir -p $checkout") == 0
	or fatal(-1, "Could not mkdir $checkout");
209 210
}

211
# XML stuff.
212 213
my $root = {};

214 215
if ($template_mode) {
    $root = ExportTemplate();
216
}
217 218
else {
    $root = ExportInstance();
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
}

if ($debug) {
    print Dumper($root);
    print "\n";
}

my %xmloptions = ('RootName' => 'instance',
		  'SuppressEmpty' => undef,
		  'NoAttr' => 1);

my $xml = XMLout($root, %xmloptions);

if ($debug) {
    print "$xml\n";

    $root = XMLin($xml, KeyAttr => "name",
		  "ForceArray" => ["metadata", "runs", "bindings"]);
    print Dumper($root);
    print "\n";
}

#
# Stash this into the checkout directory we created above. 
#
244 245 246
unlink("$checkout/export.xml")
    if (-e "$checkout/export.xml");

247 248 249 250 251 252 253 254 255
open(DUMP, ">$checkout/export.xml")
    or fatal(-1, "Could not open $checkout/export.xml for writing");
print DUMP "$xml\n";
close(DUMP);

if ($spew) {
    system("$TAR zcf - -C $checkout .");
    cleanup();
}
256 257 258
else {
    print "$checkout\n";
}
259 260 261 262 263 264 265 266 267 268 269 270 271
exit(0);

#
# Parse command arguments. Once we return from getopts, all that are
# left are the required arguments.
#
sub ParseArgs()
{
    if (! getopts($optlist, \%options)) {
	usage();
    }

    if (defined($options{"i"})) {
272 273 274
	usage()
	    if (@ARGV);
	
275 276 277 278 279 280 281
	$exptidx = $options{"i"};
    
	if (! TBcheck_dbslot($exptidx, "default", "int",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper experiment index!");
	}
	# real check.
282
	if ($exptidx =~ /^([\d]*)$/) {
283 284 285 286 287 288 289
	    $exptidx = $1;
	}
	else {
	    tbdie("Bad data in argument: $exptidx");
	}
    }
    else {
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
	usage()
	    if (@ARGV != 1);

	#
	# Pick up guid/version first and untaint.
	#
	my $tmp = shift(@ARGV);

	if ($tmp =~ /^([\w]*)\/([\d]*)$/) {
	    $guid = $1;
	    $version = $2;
	}
	else {
	    tbdie("Bad data in argument: $tmp");
	}
	$template_mode = 1;
306 307
    }

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    if (defined($options{"r"})) {
	$runidx = $options{"r"};
    
	if (! TBcheck_dbslot($runidx, "default", "int",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper run index!");
	}
	# real check.
	if ($runidx =~ /^([\d]*)$/) {
	    $runidx = $1;
	}
	else {
	    tbdie("Bad data in argument: $runidx");
	}
    }

324 325 326 327 328 329 330 331 332
    if (defined($options{"t"})) {
	$tag = $options{"t"};
    
	if (! TBcheck_dbslot($tag, "archive_tags", "tag",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper tag!");
	}
    }

333 334 335 336 337 338 339 340 341
    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"s"})) {
	$spew = 1;
    }
    if (defined($options{"d"})) {
	$debug = 2;
    }
342 343 344 345 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 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 505 506 507 508
    if (defined($options{"o"})) {
	$overwrite = 1;
    }

    usage()
	if (defined($runidx) && defined($tag));
}

#
# Export a template at an optional tag.
#
sub ExportTemplate()
{
    my $root     = {};

    $root->{"guid"} = $template->guid() . "/" . $template->vers();
    $root->{"pid"}  = $template->pid();

    #
    # Need the underlying experiment for this template, since that is
    # where the archive hangs off of.
    #
    my $experiment = Experiment->Lookup($template->exptidx());
    fatal(-1, "Could not lookup experiment for $template")
	if (!defined($experiment));

    # Dump formal parameters.
    my %formals = ();
    if ($template->FormalParameterList(\%formals) < 0) {
	fatal(-1, "Could not get formal parameters for $template");
    }
    if (keys(%formals)) {
	$root->{"bindings"} = {};
	foreach my $name (keys(%formals)) {
	    my $value = $formals{$name};
	    my $description;

	    if ($template->FormalParameterDescription($name,
						      \$description) < 0) {
		fatal(-1, "Could not get description for parameter $name");
	    }
	    $root->{"bindings"}->{$name} = {'value' => $value,
					    'description' => $description};
	}
    }

    # Fill in the metadata
    my %mlist;
    $template->MetadataList(\%mlist) == 0
	or fatal(-1, "Could not get Metadata list for $instance");
    if (keys(%mlist)) {
	$root->{"metadata"} = {};
	foreach my $name (keys(%mlist)) {
	    my $value = $mlist{$name};
	
	    $root->{"metadata"}->{$name} = $value;
	}
    }
    if (defined($tag)) {
	if ($archive->Checkout($checkout, $experiment->idx(), $tag) < 0) {
	    fatal(-1, "Could not checkout $tag to $checkout");
	}
    }
    elsif (defined($experiment->archive_tag())) {
	my $curtag = $experiment->archive_tag();

	if ($archive->Checkout($checkout, $experiment->idx(), $curtag) < 0) {
	    fatal(-1, "Could not checkout $curtag to $checkout");
	}
    }
    return $root;
}

sub ExportInstance()
{
    my $root = {};

    $root->{"guid"}       = $instance->guid() . "/" . $instance->vers();
    $root->{"pid"}        = $instance->pid();
    $root->{"eid"}        = $instance->eid();
    $root->{"uid"}        = $instance->uid();
    $root->{"start_time"} = $instance->start_time();
    $root->{"stop_time"}  = $instance->stop_time();

    # Fill in the bindings
    $instance->BindingList(\%bindings) == 0
	or fatal(-1, "Could not get bindings for $instance");
    if (keys(%bindings)) {
	$root->{"bindings"} = {};
	foreach my $name (keys(%bindings)) {
	    my $value = $bindings{$name};
	    my $description;

	    $template->FormalParameterDescription($name, \$description);
	
	    $root->{"bindings"}->{$name} = {'value' => $value,
					    'description' => $description};
	}
    }

    # Fill in the runs.
    my %runlist;
    $instance->RunList(\%runlist) == 0
	or fatal(-1, "Could not get runlist for $instance");
    if (keys(%runlist)) {
	$root->{"runs"} = {};
	foreach my $name (keys(%runlist)) {
	    my $value = $runlist{$name};

	    # Export only requested run.
	    next
		if (defined($runidx) && $runidx != $value->{"idx"});

	    $root->{"runs"}->{$name} = $value;
	}
    }

    # Fill in the metadata
    my %mlist;
    $template->MetadataList(\%mlist) == 0
	or fatal(-1, "Could not get Metadata list for $instance");
    if (keys(%mlist)) {
	$root->{"metadata"} = {};
	foreach my $name (keys(%mlist)) {
	    my $value = $mlist{$name};
	
	    $root->{"metadata"}->{$name} = $value;
	}
    }

    #
    # Dump specific tag, or the runlist, each in its own directory.
    # 
    if (defined($tag)) {
	if ($archive->Checkout($checkout, $instance->exptidx(), $tag) < 0) {
	    fatal(-1, "Could not checkout $tag to $checkout");
	}
    }
    elsif (keys(%runlist)) {
	foreach my $name (keys(%runlist)) {
	    my $rowref = $runlist{$name};

	    # Export only requested run.
	    next
		if (defined($runidx) && $runidx != $rowref->{"idx"});

	    my $dir    = "$checkout/run" . $rowref->{"idx"};
	    my $curtag = $rowref->{"ending_archive_tag"};

	    # This could happen if template still instantiated (last run).
	    next
		if (!defined($curtag) || $curtag eq "");
	
	    system("mkdir -p $dir") == 0
		or fatal(-1, "Could not mkdir $dir");

	    if ($archive->Checkout($dir, $instance->exptidx(), $curtag) < 0) {
		fatal(-1, "Could not checkout $curtag to $dir");
	    }
	}
    }
    #
    # Note the time this export was done.
    #
    $instance->UpdateExportTime();
    
    return $root;
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
}

#
# Cleanup the mess.
#
sub cleanup()
{
    if (defined($checkout) && -e $checkout) {
	system("/bin/rm -rf $checkout");
    }
}

sub fatal($$)
{
    my ($errorstat, $msg) = @_;
    
    tberror $msg;
    tbinfo "Cleaning up and exiting with status $errorstat ...";
527
    cleanup();
528 529 530 531

    exit($errorstat);
}