template_export.in 12.5 KB
Newer Older
1
#!/usr/bin/perl -w
2
#
3
# Copyright (c) 2006, 2007 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
# 
# {{{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/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33
#
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;

#
34 35 36
# 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.
37 38 39 40 41 42 43 44 45 46 47 48 49
#
# 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
50 51
	  "Usage: template_export [-q] [-s] [-r runidx | -t tag] -i <idx>\n".
	  "       template_export [-q] [-s] [-t tag] guid/vers\n".
52 53
	  "switches and arguments:\n".
	  "-q           - be less chatty\n".
54
	  "-o           - overwrite existing export directory\n".
55
	  "-s           - spew to stdout (as for web page).\n".
56
	  "-t           - specific archive tag to export.\n".
57
	  "-i <idx>     - Instance index to export\n".
58 59
	  "-r <runidx>  - Run index to export\n".
	  "guid/vers    - The template to export.\n");
60 61
    exit(-1);
}
62
my $optlist	 = "qi:dsr:ot:";
63 64 65 66
my %options      = ();
my $spew         = 0;
my $quiet        = 0;
my $debug        = 0;
67 68 69 70
my $overwrite    = 0;
my $template_mode= 0;
my $guid;
my $version;
71
my $exptidx;
72
my $runidx;
73
my $tag;
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

#
# 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;
91
my $pid;
92 93 94 95
my $project;
my $archive;
my %bindings;
my $checkout;
96 97 98 99 100

# Protos
sub ParseArgs();
sub fatal($$);
sub cleanup();
101 102
sub ExportTemplate();
sub ExportInstance();
103 104 105 106 107 108 109 110 111

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
use Template;
112
use User;
113 114 115
use Project;
use Archive;
use Experiment;
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

# 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.
#
142 143 144
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
145 146 147 148 149 150
}

# Now parse arguments.
ParseArgs();

#
151 152
# Depending on call method, we find the template, or the instance and
# then the template.
153
#
154 155 156 157 158 159 160 161 162
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();
163
}
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
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");
182 183 184
    exit(1);
}

185
if (system("$checkquota " . $this_user->uid()) != 0) {
186 187
    tberror("You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
188 189 190 191 192 193
    exit(1);
}

#
# Checkout to the project tree.
#
194 195 196 197 198 199 200 201 202 203 204 205 206
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));
}
207 208 209

# Cleanup existing goo.
if (-e $checkout) {
210 211 212 213 214 215
    if (!$overwrite) {
	# Exit status tells web interface what has happened.
	print STDERR "Export directory already exists; ".
	    "use overwite option (-o).\n";
	exit(2);
    }
216 217 218 219 220 221 222 223 224 225
    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");
226 227
}

228
# XML stuff.
229 230
my $root = {};

231 232
if ($template_mode) {
    $root = ExportTemplate();
233
}
234 235
else {
    $root = ExportInstance();
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
}

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. 
#
261 262 263
unlink("$checkout/export.xml")
    if (-e "$checkout/export.xml");

264 265 266 267 268 269 270 271 272
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();
}
273 274 275
else {
    print "$checkout\n";
}
276 277 278 279 280 281 282 283 284 285 286 287 288
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"})) {
289 290 291
	usage()
	    if (@ARGV);
	
292 293 294 295 296 297 298
	$exptidx = $options{"i"};
    
	if (! TBcheck_dbslot($exptidx, "default", "int",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper experiment index!");
	}
	# real check.
299
	if ($exptidx =~ /^([\d]*)$/) {
300 301 302 303 304 305 306
	    $exptidx = $1;
	}
	else {
	    tbdie("Bad data in argument: $exptidx");
	}
    }
    else {
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
	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;
323 324
    }

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    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");
	}
    }

341 342 343 344 345 346 347 348 349
    if (defined($options{"t"})) {
	$tag = $options{"t"};
    
	if (! TBcheck_dbslot($tag, "archive_tags", "tag",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper tag!");
	}
    }

350 351 352 353 354 355 356 357 358
    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"s"})) {
	$spew = 1;
    }
    if (defined($options{"d"})) {
	$debug = 2;
    }
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 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    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;
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
}

#
# 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 ...";
544
    cleanup();
545 546 547 548

    exit($errorstat);
}