template_export.in 8.28 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# 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 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# 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;

#
# Export a template.
#
# 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
31
	  "Usage: template_export [-q] [-s] [-r <runidx>] -i <idx>\n".
32 33 34
	  "switches and arguments:\n".
	  "-q           - be less chatty\n".
	  "-s           - spew to stdout (as for web page).\n".
35 36
	  "-i <idx>     - Instance index to export\n".
	  "-r <runidx>  - Run index to export\n");
37 38
    exit(-1);
}
39
my $optlist	 = "qi:dsr:";
40 41 42 43 44
my %options      = ();
my $spew         = 0;
my $quiet        = 0;
my $debug        = 0;
my $exptidx;
45
my $runidx;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
my %bindings;

#
# 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;
64 65 66
my $pid;
my $guid;
my $version;
67 68 69 70 71 72 73 74 75 76 77 78 79 80

# Protos
sub ParseArgs();
sub fatal($$);
sub cleanup();

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
use Template;
81
use User;
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

# Be careful not to exit on transient error
$libdb::DBQUERY_MAXTRIES = 0;

# 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.
#
111 112 113
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
114 115 116 117 118 119 120 121 122
}

# Now parse arguments.
ParseArgs();

# Temporary
libArchive::setdebug($debug);

#
123
# Grab instance info and do access check via the template.
124
#
125 126 127
$instance = Template::Instance->LookupByExptidx($exptidx);
if (!defined($instance)) {
    fatal(-1, "Could not get instance record for experiment $exptidx!");
128
}
129 130 131 132 133 134
$template = $instance->template();
$pid      = $template->pid();
$guid     = $template->guid();
$version  = $template->vers();

if (! TBProjAccessCheck($this_user->uid(),
135 136 137 138 139 140
			$template->pid(), $template->gid(),
			TB_PROJECT_READINFO)) {
    tberror("You do not have permission to export template $guid/$version");
    exit(1);
}

141
if (system("$checkquota " . $this_user->uid()) != 0) {
142 143
    tberror("You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
144 145 146 147 148 149 150 151 152 153
    exit(1);
}

#
# Checkout to the project tree.
#
my $checkout = "$projroot/$pid/export/$guid/$version/$exptidx";

# Cleanup existing goo.
if (-e $checkout) {
154 155 156 157 158 159 160 161 162 163
    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");
164 165 166 167 168 169 170 171 172 173 174 175
}

#
# Since that worked, lets create the XML representation of it and stash
# to a file.
#
my $root = {};

$root->{"guid"} = $instance->guid() . "/" . $instance->vers();
$root->{"pid"}  = $instance->pid();
$root->{"eid"}  = $instance->eid();
$root->{"uid"}  = $instance->uid();
Leigh Stoller's avatar
Leigh Stoller committed
176 177
$root->{"start_time"} = $instance->start_time();
$root->{"stop_time"}  = $instance->stop_time();
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 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 236 237 238 239 240 241 242 243

# 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};
	
	$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;
    }
}

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
open(DUMP, ">$checkout/export.xml")
    or fatal(-1, "Could not open $checkout/export.xml for writing");
print DUMP "$xml\n";
close(DUMP);

252 253 254 255 256 257 258 259 260

#
# Now dump a checkout of each run, in its own directory. Eventually we
# need to allow for sending out the actual repo instead of checkouts.
#
if (keys(%runlist)) {
    $root->{"runs"} = {};
    foreach my $name (keys(%runlist)) {
	my $rowref = $runlist{$name};
261 262 263 264 265 266

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

	my $dir    = "$checkout/run" . $rowref->{"idx"};
267
	my $tag    = $rowref->{"ending_archive_tag"};
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

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

	if (libArchive::TBCheckoutExperimentArchivebyExptIDX($exptidx,
							     $dir, $tag) < 0) {
	    fatal(-1, "Could not checkout $tag to $dir");
	}
    }
}
else {
Leigh Stoller's avatar
Leigh Stoller committed
283 284
    my $archive_tag;

285
    # This would be silly; exporting an instance with no runs.
Leigh Stoller's avatar
Leigh Stoller committed
286 287 288 289
    if ($instance->ArchiveTag(\$archive_tag) < 0) {
	fatal(-1, "Could not get current archive tag for instance $exptidx!");
    }
    
290 291 292 293 294 295 296
    if (libArchive::TBCheckoutExperimentArchivebyExptIDX($exptidx,
							 $checkout,
							 $archive_tag) < 0) {
	fatal(-1, "Could not checkout $archive_tag to $checkout");
    }
}

297 298 299 300 301
#
# Note the time this export was done.
#
$instance->UpdateExportTime();

302 303 304 305
if ($spew) {
    system("$TAR zcf - -C $checkout .");
    cleanup();
}
306 307 308
else {
    print "$checkout\n";
}
309 310 311 312 313 314 315 316 317 318 319 320
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();
    }

321 322
    usage()
	if (@ARGV);
323 324 325 326 327 328 329 330 331
    
    if (defined($options{"i"})) {
	$exptidx = $options{"i"};
    
	if (! TBcheck_dbslot($exptidx, "default", "int",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper experiment index!");
	}
	# real check.
332
	if ($exptidx =~ /^([\d]*)$/) {
333 334 335 336 337 338 339 340 341 342
	    $exptidx = $1;
	}
	else {
	    tbdie("Bad data in argument: $exptidx");
	}
    }
    else {
	tbdie("You must supply the -i option!");
    }

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    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");
	}
    }

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
    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"s"})) {
	$spew = 1;
    }
    if (defined($options{"d"})) {
	$debug = 2;
    }
}

#
# 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 ...";

    exit($errorstat);
}