libArchive.pm.in 43.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
# Copyright (c) 2005 University of Utah and the Flux Group.
# All rights reserved.
#
# XXX Need to deal with locking at some point ...
#
package libArchive;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use lib '@prefix@/lib';
use libdb;
21
use libtestbed;
22 23 24 25 26 27 28 29
use English;
use File::stat;
use File::Basename;
use POSIX qw(strftime);
use Time::HiRes qw(gettimeofday);

# Configure variables
my $TB		= "@prefix@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
30 31
my $MAINSITE    = @TBMAINSITE@;
my $ALLOWEDPID  = "testbed";
32 33 34 35 36 37 38 39 40
# XXX
my $ARCHIVEDIR  = "/usr/testbed/exparchive";
my $TESTMODE    = @TESTMODE@;
my $TBOPS       = "@TBOPSEMAIL@";
my $ELABINELAB  = @ELABINELAB@;
my $MD5		= "/sbin/md5";
my $MKDIR       = "/bin/mkdir";
my $CHMOD       = "/bin/chmod";
my $TAR		= "/usr/bin/tar";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
41
my $RSYNC	= "/usr/local/bin/rsync";
42
my $RM		= "/bin/rm";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
43
my $REALPATH	= "/bin/realpath";
44 45 46
my $SVN         = "/usr/local/bin/svn";
my $SVNADMIN    = "/usr/local/bin/svnadmin";
my $IMPORTER    = "$TB/sbin/svn_load_dirs.pl";
47
my $inittag     = 'root';
48
my $defaultview = 'head';
49
my $debug       = 0;
50
my $svnopt      = ($debug ? "" : "-q");
51 52 53 54 55 56 57 58 59 60 61

# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if ($debug);
    system($command);
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
# Another little helper for scripts that include this library.
sub setdebug($)
{
    my ($toggle) = @_;

    if ($toggle) {
	$debug  = 1;
	$svnopt = "";
    }
    else {
	$debug  = 0;
	$svnopt = "-q";
    }
}

77 78 79 80
#
# Create a new archive. Returns -1 if any error. Otherwise return
# the new record index.
# 
81
sub ArchiveCreate(;$$)
82
{
83
    my ($tag, $view) = @_;
84
    
85 86
    my $idx;
    my $dir;
87 88 89

    $tag = $inittag
	if (!defined($tag));
90 91
    $view = $defaultview
	if (!defined($view));
92

93
    # Tags cannot must start with a letter.
94 95 96
    if ($tag =~ /^\d+/) {
	$tag = "T" . $tag;
    }
97 98 99 100 101

    #
    # Need to create the directory for it, once we have the index.
    # 
    my $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
102
	DBQueryWarn("insert into archives set ".
103
		    "  idx=NULL, ".
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
		    "  date_created=UNIX_TIMESTAMP(now())");

    return -1
	if (!$query_result);

    $idx = $query_result->insertid;
    $dir = "$ARCHIVEDIR/$idx";

    #
    # Create the directory and store the absolute path into the new record.
    # This should probably be a privledged operation at some point.
    # 
    mysystem("$MKDIR $dir") == 0 or goto bad;
    mysystem("$CHMOD 775 $dir") == 0 or goto bad;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
119
    DBQueryWarn("update archives set directory='$dir' where idx='$idx'")
120 121 122
	or goto bad;

    #
123
    # Make subdirs. One to hold the control tree, and the other
124 125
    # to hold currently checked out versions of the tree. Lastly, we
    # need a place to copyin files before they are added to the repo.
126
    #
127
    my $repodir   = "$dir/repo";
128 129
    my $checkouts = "$dir/checkouts";
    my $checkins  = "$dir/checkins";
130

131 132
    if (! mkdir("$repodir", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $repodir: $!\n";
133 134
	goto bad;
    }
135 136
    if (! chmod(0777, "$repodir")) {
	print STDERR "ArchiveCreate: Could not chmod $repodir: $!\n";
137 138
	goto bad;
    }
139 140
    if (! mkdir("$checkouts", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkouts: $!\n";
141 142
	goto bad;
    }
143 144
    if (! chmod(0777, "$checkouts")) {
	print STDERR "ArchiveCreate: Could not chmod $checkouts: $!\n";
145 146
	goto bad;
    }
147 148
    if (! mkdir("$checkins", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins: $!\n";
149 150
	goto bad;
    }
151 152 153 154 155 156 157 158 159 160
    if (! chmod(0777, "$checkins")) {
	print STDERR "ArchiveCreate: Could not chmod $checkins: $!\n";
	goto bad;
    }
    if (! mkdir("$checkins/$view", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins/$view: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$checkins/$view")) {
	print STDERR "ArchiveCreate: Could not chmod $checkins/$view: $!\n";
161 162
	goto bad;
    }
163 164
    # Initialize the repo.
    mysystem("$SVNADMIN create $repodir") == 0
165
	or goto bad;
166 167 168 169
    
    # Create an stub directory tree and import it as "root"
    mysystem("cd $dir; mkdir ignore; cd ignore; mkdir $view; ".
             "         mkdir $view/trunk $view/savepoint $view/tags; ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
170
	     "         mkdir $view/history; ".
171 172
	     "$SVN import $svnopt -m 'ArchiveCreate' "/
	     "     $view file://$repodir/$view")
173 174 175
	== 0 or goto bad;

    # Create a branch tag in the tags directory to base differences against.
176
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
177 178
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${tag}-branch")
179
	== 0 or goto bad;
180
    
181 182
    # Now check it out. This creates the $checkouts/$view directory.
    mysystem("cd $checkouts; ".
183
	     "$SVN checkout $svnopt file://$repodir/$view")
184 185
	== 0 or goto bad;

186 187 188 189 190
    # Now enter the default view (okay, branch) of this archive.
    DBQueryWarn("insert into archive_views set ".
		"  current_tag='$tag', archive_idx='$idx', view='$view', ".
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
    
191
    # Now enter an initial tag for the tree. Nothing actually gets tagged.
192
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
193
		"  tag='$tag', archive_idx='$idx', ".
194 195 196 197 198 199 200
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
    
    return $idx;

  bad:
#    mysystem("$RM -rf $dir")
#        if (defined($dir));
201 202 203
    DBQueryFatal("delete from archive_views ".
		 "where view='$view' and archive_idx='$idx'")
	if (defined($idx));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
204
    DBQueryFatal("delete from archives where idx='$idx'")
205 206 207 208 209 210 211 212 213 214
	if (defined($idx));
    return -1;
}

#
# Add a file to an archive. Returns -1 if any error. Otherwise return 0.
# All this does is copy the file (and its directory structure) into the
# temporary store. Later, after all the files are in the tree, must
# commit it to the repo. 
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
215
sub ArchiveAdd($$;$$)
216
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
217
    my ($archive_idx, $pathname, $view, $exact) = @_;
218 219 220

    $view = $defaultview
	if (!defined($view));
221

Leigh B. Stoller's avatar
Leigh B. Stoller committed
222 223 224
    $exact = 0
	if (!defined($exact));

225
    if (! -e $pathname || ! -r $pathname) {
226 227
	print STDERR "*** ArchiveFile: $pathname cannot be read!\n";
	return 0;
228 229 230 231 232 233
    }

    #
    # Check that the path does not contain an links to files outside
    # the directory space the user is allowed to access.
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
234
    my $realpath = `$REALPATH $pathname`;
235
    if ($realpath =~ /^([-\w\/\.\+\@,~]+)$/) {
236 237 238 239 240 241 242 243 244 245
	$realpath = $1;
    }
    else {
	print STDERR "ArchiveFile: ".
	    "Bad data returned by realpath: $realpath\n";
    }
    #
    # The file must reside in /proj, /groups, or /users. 
    #
    if (! ($realpath =~ /^\/proj/) &&
246
	! ($realpath =~ /^\/share/) &&
247 248 249 250 251 252 253 254
	! ($realpath =~ /^\/groups/) &&
	! ($realpath =~ /^\/users/)) {
	print STDERR "ArchiveFile: ".
	    "$realpath does not resolve to an allowed directory!\n";
	return -1;
    }
    
    # Strip leading / from the pathname, and taint check it. 
255
    if ($pathname =~ /^[\/]+([-\w\/\.\+\@,~]+)$/) {
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
	$pathname = $1;
    }
    else {
	print STDERR "ArchiveFile: Illegal characters in pathname $pathname\n";
	return -1;
    }

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchiveFile: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveFile: $directory cannot be written!\n";
	return -1;
    }
276
    my $repodir   = "$directory/repo";
277 278
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = "$directory/checkins/$view";
279 280
    
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
281 282 283 284
    # Copy the file in. We use tar on individual files (to retain the
    # directory structure and mode bits, etc). On a directory, use either
    # tar or rsync, depending on whether we want an exact copy (removing
    # files in the target that are not present in the source). 
285
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
286 287 288 289
    if (-f "/${pathname}" || !$exact) {
	mysystem("$TAR cf - -C / $pathname | tar xf - -C $checkin");
    }
    else {
290
	mysystem("$RSYNC -R -ax --delete /${pathname} $checkin");
291 292 293 294 295 296 297 298 299
    }
    if ($?) {
	print STDERR "ArchiveFile: Could not copy in /$pathname\n";
	return -1;
    }
    return 0;
}

#
300 301 302 303 304
# Bring the current contents of the temporary store into the archive as a
# checkpoint (or a savepoint I guess). Implementationlly, its really a
# branch off the current import revision, since it does not become a new
# head revision until the entire branch (all the savepoints) is committed
# later, say when the experiment is swapped out.
305
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
306
sub ArchiveSavePoint($;$$$)
307
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
308
    my ($archive_idx, $savetag, $view, $altdir) = @_;
309 310 311 312 313 314 315 316
    my $cwd;

    $view = $defaultview
	if (!defined($view));

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
317 318 319 320 321 322

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
323
	print STDERR "ArchiveSavePoint: ".
324
	    "Archive '$archive_idx' does not exist in the DB!\n";
325
	goto bad;
326 327
    }
    if (! -d $directory || ! -w $directory) {
328
	print STDERR "ArchiveSavePoint: $directory cannot be written!\n";
329
	goto bad;
330
    }
331
    my $repodir   = "$directory/repo";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
332
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
333 334 335 336 337 338

    # Need to remember where we came from!
    chomp($cwd = `pwd`);
    # Must do the taint check too.
    if ($cwd =~ /^([-\w\.\/]+)$/) {
	$cwd = $1;
339
    }
340 341
    else {
	print STDERR "ArchiveSavePoint: Bad data in $cwd!\n";
342
	goto bad;
343 344
    }

345
    # Get the current tag for the archive.
346 347
    my ($archive_tag);
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag) < 0) {
348 349 350 351 352 353 354 355 356 357 358 359 360 361
	print STDERR "ArchiveSavePoint: ".
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

    # Make up a savetag if one not provided.
    if (!defined($savetag)) {
	my ($seconds, $microseconds) = gettimeofday();
	
	$savetag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
	$savetag .= $microseconds;
	$savetag .= "_savepoint";
    }

362
    # Tags must start with a letter.
363 364 365 366
    if ($savetag =~ /^\d+/) {
	$savetag = "T" . $savetag;
    }
    
367
    #
368
    # Use svn import command. This is nice cause it handles all the
369 370 371
    # subdirs and stuff in one shot, instead of trying to deal with
    # each file and directory individually.
    #
372 373 374 375
    if (! chdir("$checkin")) {
	print STDERR "ArchiveSavePoint: Cannot chdir to $checkin!\n";
	goto bad;
    }
376
    mysystem("$IMPORTER -no_user_input file://$repodir ".
377
	     "          $view/savepoint . > /dev/null")
378 379 380 381 382
	== 0 or goto bad;

    #
    # Create the tag for this savepoint. 
    # 
383
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
384 385 386 387
	     "          file://$repodir/$view/savepoint ".
	     "          file://$repodir/$view/tags/${savetag}")
	== 0 or goto bad;
    
388 389 390 391

    #
    # And record the new tag. 
    # 
392
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
393
		"  tag='$savetag', ".
394
		"  archive_idx='$archive_idx', ".
395
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
396

397
  okay:
398 399 400
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
401 402 403
    return 0;

  bad:
404 405 406
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
407 408 409 410 411 412 413
    return -1;
}

#
# Commit the current contents of the temporary store to the archive.
# Returns -1 if any error. Otherwise return 0.
#
414
sub ArchiveCommit($;$$$)
415
{
416
    my ($archive_idx, $newtag, $view, $altdir) = @_;
417
    my $noactivity = 0;
418 419 420 421 422 423 424 425
    my $cwd;

    $view = $defaultview
	if (!defined($view));

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
426 427 428 429 430 431 432 433

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchiveCommit: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
434
	goto bad;
435 436 437
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCommit: $directory cannot be written!\n";
438
	goto bad;
439
    }
440
    my $repodir   = "$directory/repo";
441 442
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
443 444 445 446 447 448 449 450

    # Need to remember where we came from!
    chomp($cwd = `pwd`);
    # Must do the taint check too.
    if ($cwd =~ /^([-\w\.\/]+)$/) {
	$cwd = $1;
    }
    else {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
451
	print STDERR "ArchiveCommit: Bad data in $cwd!\n";
452
	goto bad;
453 454
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
455 456
    if (! chdir("$directory")) {
	print STDERR "ArchiveCommit: Cannot chdir to $directory!\n";
457
	goto bad;
458 459 460
    }

    # Get the current tags for the archive.
461
    my ($archive_tag, $previous_tag);
462
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag,
463
			      \$previous_tag) < 0) {
464 465 466 467 468 469
	print STDERR "ArchiveCommit: ".
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

    #
470 471
    # Form new tag.
    # 
472 473 474
    my ($seconds, $microseconds) = gettimeofday();
    my $import_tag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $import_tag    .= $microseconds;
475 476

    if (!defined($newtag)) {
477
	$newtag = $import_tag . "_commit";
478 479
    }

480
    # Tags cannot must start with a letter.
481 482 483
    if ($newtag =~ /^\d+/) {
	$newtag = "T" . $newtag;
    }
484

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    #
    # Lets see if there has been any action since the last commit.
    # Check for new tags, and if nothing has happened, just drop a
    # new set of tags in and return.
    #
    my $query_result =
	DBQueryWarn("select tag from archive_tags ".
		    "where archive_idx='$archive_idx' ".
		    "order by idx desc limit 1");
    goto bad
	if (!$query_result || !$query_result->numrows);
    
    my ($tmptag) = $query_result->fetchrow_array();
    if ($tmptag eq $archive_tag) {
	print "ArchiveCommit: Archive is clean; no need to commit.\n";
	$noactivity = 1;
    }
    
503
    #
504 505 506
    # Okay, do the commit to the trunk for this view.
    # 
    if (! $noactivity) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
507 508 509 510 511 512 513 514 515
	#
	# Create a temporary spot to work in.
	# 
	if (! mkdir("merge.$$", 0777)) {
	    print STDERR "ArchiveCommit: Could not mkdir merge.$$: $!\n";
	    goto bad;
	}
	chdir("merge.$$");
	
516
	#
517
	# Check out the current trunk.
518
	#
519 520 521
	mysystem("$SVN checkout $svnopt file://$repodir/$view/trunk")
	    == 0 or goto bad;

522
	#
523 524 525 526 527 528 529 530 531 532
	# Do a merge from the branch off the previous commit tag, with
	# the savepoint. This is merged into the working directory we
	# just checked out above. This will do the work of scheduling
	# additions and deletions.
	#
	mysystem("$SVN merge $svnopt ".
		 "     file://$repodir/$view/tags/${archive_tag}-branch ".
		 "     file://$repodir/$view/savepoint ".
		 "     trunk")
	    == 0 or goto bad;
533

534 535 536 537 538 539
	#
	# Now commit to the trunk!
	#
	mysystem("$SVN commit $svnopt ".
		 "     -m 'Commit merge of ${archive_tag} to trunk' trunk")
	    == 0 or goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
540 541 542 543 544 545 546

	# Clean the temp dir,
	chdir("$directory");
	mysystem("/bin/rm -rf merge.$$");
	if ($?) {
	    print STDERR "ArchiveCommit: Could not remove merge.$$\n";
	}
547
    }
548

549
    # Create a tag in the tags directory for the commit.
550
    mysystem("$SVN copy $svnopt -m 'ArchiveCommit' ".
551 552 553 554
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${newtag}")
	== 0 or goto bad;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
555 556 557
    # Create a tag in the history directory for the commit. The
    # history directory has just the commit tags, so its easy to go
    # back in time.
558
    mysystem("$SVN copy $svnopt -m 'ArchiveCommit' ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
559 560 561 562
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/history/${newtag}")
	== 0 or goto bad;
    
563
    # Create a branch tag in the tags directory to base differences against.
564
    mysystem("$SVN copy $svnopt -m 'ArchiveCommit Branch' ".
565 566 567 568
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${newtag}-branch")
	== 0 or goto bad;
    
569
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
570
		"  tag='$newtag', ".
571
		"  archive_idx='$archive_idx', ".
572 573
		"  date_created=UNIX_TIMESTAMP(now())")
	or goto bad;
574

575
    DBQueryWarn("update archive_views set ".
576
		"  current_tag='$newtag', ".
577
		"  previous_tag='$archive_tag' ".
578 579
		"where archive_idx='$archive_idx' and view='$view'")
	or goto bad;
580 581

    # Clean the temp dir for later.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
   if (0) {
    if (!defined($altdir)) {
	mysystem("/bin/rm -rf $checkin");
	if ($?) {
	    print STDERR "ArchiveCommit: Could not remove $checkin!\n";
	    goto bad;
	}
	if (! mkdir("$checkin", 0777)) {
	    print STDERR "ArchiveCommit: Could not mkdir $checkin: $!\n";
	    goto bad;
	}
	if (! chmod(0777, "$checkin")) {
	    print STDERR "ArchiveCommit: Could not chmod $checkin: $!\n";
	    goto bad;
	}
597
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
598
   }
599

600 601 602
    # And now into the checkout dir to checkout a current copy.
    if (! chdir("$checkout")) {
	print STDERR "ArchiveCommit: Cannot chdir to $checkout!\n";
603
	goto bad;
604
    }
605
    mysystem("$SVN $svnopt update trunk");
606
    if ($?) {
607
	print STDERR "ArchiveCommit: Could not update head revision!\n";
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
	goto bad;
    }
  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

  bad:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return -1;
}

#
# Fork an archive (okay, branch) for use in separate development. Note that
# once forked, there is no join, as that would be impossibly hard to deal
# with cause of conflicts.
#
628
sub ArchiveFork($$;$$$)
629
{
630 631
    my ($archive_idx, $newview, $branchtag, $newtag, $view) = @_;
    my $sourcepoint;
632 633 634 635 636 637 638 639 640 641 642 643 644 645
    my $cwd;

    $view = $defaultview
	if (!defined($view));

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
646
	print STDERR "ArchiveCommit: ".
647 648 649 650 651
	    "Archive '$archive_idx' does not exist in the DB!\n";
	goto bad;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCommit: $directory cannot be written!\n";
652
	goto bad;
653
    }
654
    my $repodir     = "$directory/repo";
655 656 657 658 659 660 661 662 663 664 665 666 667
    my $checkouts   = "$directory/checkouts";
    my $checkout    = "$directory/checkouts/$view";
    my $checkin     = "$directory/checkins/$view";
    my $newcheckout = "$directory/checkouts/$newview";
    my $newcheckin  = "$directory/checkins/$newview";

    # Need to remember where we came from!
    chomp($cwd = `pwd`);
    # Must do the taint check too.
    if ($cwd =~ /^([-\w\.\/]+)$/) {
	$cwd = $1;
    }
    else {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
668
	print STDERR "ArchiveFork: Bad data in $cwd!\n";
669 670 671 672
	goto bad;
    }

    # Get the current tags for the archive.
673
    my ($archive_tag, $previous_tag);
674
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag,
675
			      \$previous_tag) < 0) {
676 677 678 679 680
	print STDERR "ArchiveCommit: ".
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    #
    # Form new tag.
    # 
    my ($seconds, $microseconds) = gettimeofday();
    my $import_tag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $import_tag    .= $microseconds;

    if (!defined($newtag)) {
	$newtag = $import_tag . "_fork";
    }

    # Tags cannot must start with a letter.
    if ($newtag =~ /^\d+/) {
	$newtag = "T" . $newtag;
    }

697 698 699 700 701 702 703 704 705
    # Create new view directories and checkout.
    if (! mkdir("$newcheckin", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $newcheckin: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$newcheckin")) {
	print STDERR "ArchiveCreate: Could not chmod $newcheckin: $!\n";
	goto bad;
    }
706 707

    # Create newview directory in the repo.
708
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	     "          file://$repodir/$newview")
	== 0 or goto bad;

    # Split at the trunk if no branchpoint provided.
    if (defined($branchtag)) {
	$sourcepoint = "tags/$branchtag";
    }
    else {
	$sourcepoint = "trunk"
    }

    # Copy the trunk of the old view.
    mysystem("$SVN copy $svnopt -m 'ArchiveFork' ".
	     "          file://$repodir/$view/$sourcepoint ".
	     "          file://$repodir/$newview/trunk")
	== 0 or goto bad;

    # Do not want to copy the tags/savepoints directories. Add new ones.
727
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
728 729 730 731 732
	     "          file://$repodir/$newview/savepoint ".
	     "          file://$repodir/$newview/tags")
	== 0 or goto bad;

    # Now check it out. This creates the checkouts/$newview directory.
733
    mysystem("cd $checkouts; ".
734
	     "$SVN checkout $svnopt file://$repodir/$newview")
735 736
	== 0 or goto bad;

737 738 739 740 741
    # Now enter the newview (okay, branch) of this archive.
    DBQueryWarn("insert into archive_views set ".
		"  current_tag='$newtag', archive_idx='$archive_idx', ".
		"  view='$newview', ".
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
742
    
743 744 745 746
    # Now enter an initial tag for the new view. Nothing actually gets tagged.
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
		"  tag='$newtag', archive_idx='$archive_idx', ".
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
747

748
  okay:
749 750 751
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
752
    return 0;
753 754

  bad:
755 756 757
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
758
    return -1;
759 760
}

761 762 763 764 765 766 767 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 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
#
# Checkout a copy of the archive, optionally at a particular view/branch.
#
sub ArchiveCheckout($$;$$)
{
    my ($archive_idx, $target, $view, $tag) = @_;
    my $sourcepoint;
    my $cwd;

    $view = $defaultview
	if (!defined($view));

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchiveCheckout: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
	goto bad;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCheckout: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir     = "$directory/repo";

    #
    # We allow target to exist or not exist.
    #
    if (! -e $target) {
	if (! mkdir("$target", 0777)) {
	    print STDERR "ArchiveCheckout: Could not mkdir $target: $!\n";
	    return -1;
	}
	if (! chmod(0777, "$target")) {
	    print STDERR "ArchiveCheckout: ".
		"Could not chmod directory $target: $!\n";
	    return -1;
	}
    }

    # Need to remember where we came from!
    chomp($cwd = `pwd`);
    # Must do the taint check too.
    if ($cwd =~ /^([-\w\.\/]+)$/) {
	$cwd = $1;
    }
    else {
	print STDERR "ArchiveCheckout: Bad data in $cwd!\n";
	goto bad;
    }

    # Where to find what we want.
    if (defined($tag)) {
	$sourcepoint = "tags/$tag";
    }
    else {
	$sourcepoint = "trunk"
    }

    # Now check it out. This creates the $checkouts/$view directory.
    mysystem("cd $target; ".
	     "$SVN checkout $svnopt file://$repodir/$view/$sourcepoint .")
	== 0 or goto bad;
  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

  bad:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return -1;
}

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
#
# Archive the Archive, moving it into the expinfo directory.
# I intend this to be run only when an experiment is terminated.
# No need to have two copies.
#
sub ArchiveArchive($$)
{
    my ($archive_idx, $dirpath) = @_;
    my $target = "$dirpath/Archive";

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
858
	print STDERR "ArchiveArchive: ".
859 860 861
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

    #
    # Need additional check to make sure that it has not already been
    # archived.
    #
    my ($archived, $date_archived);
    
    if (IsArchiveArchived($archive_idx, \$archived, \$date_archived) < 0) {
	return -1;
    }
    if ($archived) {
	print STDERR "ArchiveArchive: ".
	    "Archive '$archive_idx' already archived on $date_archived!\n";
	return 0;
    }
    
878
    if (! -d $directory || ! -w $directory) {
879
	print STDERR "ArchiveArchive: $directory cannot be written!\n";
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
	return -1;
    }

    if (! -e $target) {
	if (! mkdir("$target", 0777)) {
	    print STDERR "ArchiveArchive: Could not mkdir $target: $!\n";
	    return -1;
	}
	if (! chmod(0777, "$target")) {
	    print STDERR "ArchiveArchive: ".
		"Could not chmod directory $target: $!\n";
	    return -1;
	}
    }    

    #
    # Tar up the whole thing and move it across.
    #
898
    mysystem("$TAR cf - -C $directory repo | tar xf - -C $target");
899 900 901 902
    if ($?) {
	print STDERR "ArchiveArchive: Could not copy in $directory\n";
	return -1;
    }
903 904 905 906

    #
    # Update its location in the DB, and remove the old directory.
    # 
907 908 909 910
    DBQueryWarn("update archives set ".
		"   directory='$target', ".
		"   archived=1, ".
		"   date_archived=UNIX_TIMESTAMP(now()) ".
911 912 913 914 915 916 917 918 919
		"where idx='$archive_idx'")
	or return -1;
    
    mysystem("/bin/rm -rf $directory");
    if ($?) {
	print STDERR "ArchiveArchive: ".
	    "Could not remove contents of $directory!\n";
	return -1;
    }
920 921 922 923 924 925 926
    return 0;
}

#
# Destroy an archive. The DB state is retained unless optional flag says
# to clean it.
#
927
sub ArchiveDestroy($$)
928 929 930 931 932 933 934 935 936 937 938 939
{
    my ($archive_idx, $clean) = @_;

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchiveDestroy: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955

    #
    # Need additional check to make sure that it has not already been
    # archived. Do not want to do anything, unless clean is specified.
    #
    my ($archived, $date_archived);
    
    if (IsArchiveArchived($archive_idx, \$archived, \$date_archived) < 0) {
	return -1;
    }
    if ($archived && !$clean) {
	print STDERR "ArchiveDestroy: ".
	    "Archive '$archive_idx' archived on $date_archived!\n";
	return 0;
    }
    
956 957 958 959 960 961 962 963 964 965
    if (! -d $directory || ! -w $directory) {
	return 0;
    }

    mysystem("/bin/rm -rf $directory");
    if ($?) {
	print STDERR "ArchiveDestroy: ".
	    "Could not remove contents of $directory!\n";
	return -1;
    }
966
    if ($clean) {
967 968
	(DBQueryWarn("delete from archive_tags ".
		     "where archive_idx='$archive_idx'") &&
969 970
	 DBQueryWarn("delete from archive_views ".
		     "where archive_idx='$archive_idx'") &&
Leigh B. Stoller's avatar
Leigh B. Stoller committed
971
	 DBQueryWarn("delete from archives ".
972 973 974 975 976 977 978 979 980 981 982 983 984 985
		     "where idx='$archive_idx'")) || return -1;
    }
    return 0;
}

#
# Get the directory for an archive, given its index. Returns -1 on error,
# zero otherwise. 
#
sub GetArchiveDirectory($$)
{
    my ($idx, $rvalp) = @_;
    
    my $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
986
	DBQueryWarn("select directory from archives where idx='$idx'");
987 988 989 990 991 992 993 994 995 996

    return -1
	if (!$query_result || !$query_result->numrows);
    my ($dir) = $query_result->fetchrow_array();

    $$rvalp = $dir
	if (defined($rvalp));
    return 0;
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
#
# See if the archive has already been archived away, and when.
#
sub IsArchiveArchived($$$)
{
    my ($idx, $parch, $pdate) = @_;
    
    my $query_result =
	DBQueryWarn("select archived,FROM_UNIXTIME(date_archived) ".
		    "  from archives where idx='$idx'");

    return -1
	if (!$query_result || !$query_result->numrows);
    
    my ($archived,$date_archived) = $query_result->fetchrow_array();

    $$parch = $archived
	if (defined($parch));
    $$pdate = $date_archived
	if (defined($pdate));
    
    return 0;
}

1021 1022 1023 1024
#
# Get the current tag for an archive, given its index. Returns -1 on error,
# zero otherwise. Place tag in the return pointer.
#
1025
sub GetArchiveCurrentTags($$$;$)
1026
{
1027
    my ($archive_idx, $view, $tagp, $prevp) = @_;
1028 1029
    
    my $query_result =
1030
	DBQueryWarn("select v.current_tag,v.previous_tag ".
1031 1032 1033 1034 1035 1036
		    "    from archive_views as v ".
		    "left join archive_tags as t on ".
		    "     t.archive_idx=v.archive_idx and ".
		    "     t.tag=v.current_tag ".
		    "where v.archive_idx='$archive_idx' and ".
		    "      v.view='$view'");
1037 1038 1039

    return -1
	if (!$query_result);
1040
    my ($tag,$previous) = $query_result->fetchrow_array();
1041
    
1042 1043 1044 1045
    $$tagp = $tag
	if (defined($tagp));
    $$prevp = $previous
	if (defined($prevp));
1046 1047 1048 1049 1050 1051 1052 1053
    return 0;
}

#
# Get the archive index for an experiment. The index is kept in the historical
# experiment_stats table, not the current experiments table. That is cause
# we keep the archive and its DB info around forever with the stats.
#
1054
sub TBExperimentArchiveInfo($$$$)
1055
{
1056
    my ($pid, $eid, $idxp, $viewp) = @_;
1057 1058

    my $query_result =
1059
	DBQueryWarn("select s.archive_idx,e.idx from experiments as e ".
1060 1061 1062 1063 1064 1065
		    "left join experiment_stats as s on s.exptidx=e.idx ".
		    "where e.pid='$pid' and e.eid='$eid'");

    return -1
	if (!$query_result || $query_result->numrows == 0);

1066
    my ($archive_idx,$exptidx) = $query_result->fetchrow_array();
1067

1068 1069 1070
    # Need to deal with no archive yet!
    return 1
	if (!defined($archive_idx) || $archive_idx == 0);
1071 1072 1073 1074 1075

    $$idxp = $archive_idx
	if (defined($idxp));
    $$viewp = "$exptidx"
	if (defined($viewp));
1076
    
1077
    return 0;
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
}

#
# Create a new archive for an experiment. This has to update the
# experiment_stats table with the newly created archive index.
# Then we have to set the current tag for the experiment in the
# resources table for the experiment.
# Returns zero on success, -1 on failure.
#
sub TBCreateExperimentArchive($$)
{
    my ($pid, $eid) = @_;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1091 1092 1093
    return 0
	if (!$MAINSITE || $pid ne $ALLOWEDPID);

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    # Grab experiment indicies we need,
    my $query_result =
	DBQueryWarn("select e.idx,s.rsrcidx from experiments as e ".
		    "left join experiment_stats as s on e.idx=s.exptidx ".
		    "where e.pid='$pid' and e.eid='$eid'");
    if (!$query_result || !$query_result->numrows) {
	return -1;
    }

    my ($exptidx,$rsrcidx) = $query_result->fetchrow_array();
1104 1105 1106 1107 1108
    my $archive_tag = "T${rsrcidx}";

    #
    # Create the new archive and get back the new index. 
    #
1109
    my $archive_idx = ArchiveCreate($archive_tag, "$exptidx");
1110 1111
    return -1
	if ($archive_idx < 0);
1112 1113 1114 1115 1116 1117

    if (! (DBQueryWarn("update experiment_stats set ".
		       "      archive_idx='$archive_idx' ".
		       "where pid='$pid' and eid='$eid' and ".
		       "      exptidx='$exptidx'") &&
	   DBQueryWarn("update experiment_resources set ".
1118
		       "      archive_tag='$archive_tag' ".
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
		       "where idx='$rsrcidx'"))) {
	ArchiveDestroy($archive_idx, 1);
	return -1;
    }
    return 0;
}

#
# Add a file to an experiment archive.
#
sub TBExperimentArchiveAddFile($$$)
{
    my ($pid, $eid, $pathname) = @_;
1132
    my ($archive_idx, $view);
1133

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1134 1135 1136
    return 0
	if (!$MAINSITE || $pid ne $ALLOWEDPID);

1137 1138 1139
    my $rval = TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view);
    return 0
	if ($rval > 0);
1140
    return -1
1141
	if ($rval < 0);
1142

1143
    return ArchiveAdd($archive_idx, $pathname, $view);
1144 1145
}

1146 1147 1148 1149 1150 1151 1152