libArchive.pm.in 32.9 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 30 31 32 33 34 35 36 37 38 39 40
use English;
use File::stat;
use File::Basename;
use POSIX qw(strftime);
use Time::HiRes qw(gettimeofday);

# Configure variables
my $TB		= "@prefix@";
# 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";
my $RM		= "/bin/rm";
my $CVSBIN      = "/usr/bin/cvs";
41
my $inittag     = 'root';
42
my $defaultview = 'head';
43
my $debug       = 1;
44
my $cvsopt      = ($debug ? "" : "-q");
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

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

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

#
# Create a new archive. Returns -1 if any error. Otherwise return
# the new record index.
# 
60
sub ArchiveCreate(;$$)
61
{
62
    my ($tag, $view) = @_;
63
    
64 65
    my $idx;
    my $dir;
66 67 68

    $tag = $inittag
	if (!defined($tag));
69 70
    $view = $defaultview
	if (!defined($view));
71 72 73 74 75

    # CVS tags cannot must start with a letter.
    if ($tag =~ /^\d+/) {
	$tag = "T" . $tag;
    }
76 77 78 79 80 81

    #
    # Need to create the directory for it, once we have the index.
    # 
    my $query_result =
	DBQueryWarn("insert into file_archives set ".
82
		    "  idx=NULL, ".
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
		    "  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;

    DBQueryWarn("update file_archives set directory='$dir' where idx='$idx'")
	or goto bad;

    #
102 103 104
    # Make subdirs. One to hold the CVS control tree, and the other
    # to hold currently checked out versions of the tree. Lastly, we
    # need a place to copyin files before they are added to the repo.
105
    #
106 107 108
    my $cvsdir    = "$dir/repo";
    my $checkouts = "$dir/checkouts";
    my $checkins  = "$dir/checkins";
109 110 111 112 113 114

    if (! mkdir("$cvsdir", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $cvsdir: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$cvsdir")) {
115
	print STDERR "ArchiveCreate: Could not chmod $cvsdir: $!\n";
116 117
	goto bad;
    }
118 119
    if (! mkdir("$checkouts", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkouts: $!\n";
120 121
	goto bad;
    }
122 123
    if (! chmod(0777, "$checkouts")) {
	print STDERR "ArchiveCreate: Could not chmod $checkouts: $!\n";
124 125
	goto bad;
    }
126 127
    if (! mkdir("$checkins", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins: $!\n";
128 129
	goto bad;
    }
130 131 132 133 134 135 136 137 138 139
    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";
140 141 142
	goto bad;
    }
    # Init the CVS control files.
143
    mysystem("$CVSBIN $cvsopt -d $cvsdir init") == 0
144 145 146
	or goto bad;
    # Create an stub directory and import it as "root"
    mysystem("cd $dir; mkdir ignore; cd ignore; ".
147 148
	     "$CVSBIN $cvsopt -d $cvsdir import ".
	     "-m 'Initialize' root $tag ${tag}_init")
149
	== 0 or goto bad;
150 151 152 153
    # Now check it out. This creates the $checkouts/$view directory.
    mysystem("cd $checkouts; ".
	     "$CVSBIN $cvsopt -d $cvsdir checkout root; ".
	     "/bin/mv root ${view}")
154 155
	== 0 or goto bad;

156 157 158 159 160
    # 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;
    
161 162
    # Now enter an initial tag for the tree. Nothing actually gets tagged.
    DBQueryWarn("insert into archive_tags set ".
163
		"  tag='$tag', archive_idx='$idx', revision='1.1', ".
164 165 166 167 168 169 170
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
    
    return $idx;

  bad:
#    mysystem("$RM -rf $dir")
#        if (defined($dir));
171 172 173
    DBQueryFatal("delete from archive_views ".
		 "where view='$view' and archive_idx='$idx'")
	if (defined($idx));
174 175 176 177 178 179 180 181 182 183 184
    DBQueryFatal("delete from file_archives where idx='$idx'")
	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. 
#
185
sub ArchiveAdd($$;$)
186
{
187 188 189 190
    my ($archive_idx, $pathname, $view) = @_;

    $view = $defaultview
	if (!defined($view));
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 244 245

    if (! -e $pathname || ! -r $pathname) {
	print STDERR "ArchiveFile: $pathname cannot be read!\n";
	return -1;
    }

    if (! -f $pathname) {
	print STDERR "ArchiveFile: $pathname must be a plain file!\n";
	return -1;
    }
    #
    # Check that the path does not contain an links to files outside
    # the directory space the user is allowed to access.
    #
    my $realpath = `realpath $pathname`;
    if ($realpath =~ /^([-\w\/\.\+\@,]+)$/) {
	$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/) &&
	! ($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. 
    if ($pathname =~ /^[\/]+([-\w\/\.\+\@,]+)$/) {
	$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;
    }
246 247 248
    my $cvsdir    = "$directory/repo";
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = "$directory/checkins/$view";
249 250 251 252 253
    
    #
    # See if the file is already in the archive. We currently deal with
    # just files; directories are gonna be a pain in the butt.
    #
254
    my $target_path = "$checkin/$pathname";
255 256 257 258 259 260

    #
    # The file should not already exist in the temporary store. 
    #
    if (-e $target_path) {
	print STDERR "ArchiveFile: ".
261
	    "WARNING: $pathname already exists in archive '$archive_idx'!\n";
262 263 264 265 266 267
    }

    #
    # Not in the archive. Copy the file in. We use tar cause we
    # want to retain the directory structure and mode bits, etc.
    #
268
    mysystem("$TAR cf - -C / $pathname | tar xf - -C $checkin");
269 270 271 272 273 274 275 276
    if ($?) {
	print STDERR "ArchiveFile: Could not copy in /$pathname\n";
	return -1;
    }
    return 0;
}

#
277 278 279 280 281
# 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.
282
#
283
sub ArchiveSavePoint($;$$)
284
{
285 286 287 288 289 290 291 292 293
    my ($archive_idx, $savetag, $view) = @_;
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
294 295 296 297 298 299

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
300
	print STDERR "ArchiveSavePoint: ".
301
	    "Archive '$archive_idx' does not exist in the DB!\n";
302
	goto bad;
303 304
    }
    if (! -d $directory || ! -w $directory) {
305
	print STDERR "ArchiveSavePoint: $directory cannot be written!\n";
306
	goto bad;
307
    }
308 309 310
    my $cvsdir    = "$directory/repo";
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = "$directory/checkins/$view";
311 312 313 314 315 316

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

323 324
    # Get the current tag for the archive.
    my ($archive_tag, $archive_revision);
325
    if (GetArchiveCurrentTags($archive_idx, $view,
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
			      \$archive_tag, \$archive_revision) < 0) {
	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";
    }

341
    # CVS tags must start with a letter.
342 343 344 345
    if ($savetag =~ /^\d+/) {
	$savetag = "T" . $savetag;
    }
    
346 347 348 349 350
    #
    # Use cvs import command. This is nice cause it handles all the
    # subdirs and stuff in one shot, instead of trying to deal with
    # each file and directory individually.
    #
351 352 353 354 355 356 357
    # NOTE: Need to specify the current "vendor" branch to import on,
    # or else cvs always uses 1.1.1. After each commit to the head, we
    # bump this so that the savepoints are logically distinct and clearly
    # associated with its head branch. 
    #
    my $rev  = "${archive_revision}.1";
    my $bopt = "-b $rev";
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

    if (! chdir("$checkout")) {
	print STDERR "ArchiveSavePoint: Cannot chdir to $checkout!\n";
	goto bad;
    }
    #
    # Ack! We need to set the default branch to match the head revision.
    # I think CVS is totally screwed up on this! 
    #
    mysystem("rcs -b${rev} ".
	     "`$CVSBIN $cvsopt -d $cvsdir -q log -R`");

    # Now do the import.
    if (! chdir("$checkin")) {
	print STDERR "ArchiveSavePoint: Cannot chdir to $checkin!\n";
	goto bad;
    }
375 376
    mysystem("$CVSBIN $cvsopt -d $cvsdir import $bopt ".
	   "-m 'SavePoint' root $archive_tag $savetag");
377
    if ($?) {
378
	print STDERR "ArchiveCommit: Could not import from $checkin!\n";
379
	goto bad;
380
    }
381 382 383 384

    #
    # And record the new tag. 
    # 
385
    DBQueryWarn("insert into archive_tags set ".
386
		"  tag='$savetag', revision='${archive_revision}', ".
387
		"  archive_idx='$archive_idx', ".
388
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
389

390 391 392 393 394 395 396 397 398 399 400
    # And now into the checkout dir to checkout a current copy.
    if (! chdir("$checkout")) {
	print STDERR "ArchiveSavePoint: Cannot chdir to $checkout!\n";
	goto bad;
    }
    mysystem("$CVSBIN $cvsopt -d $cvsdir update -dP -r $rev");
    if ($?) {
	print STDERR "ArchiveSavePoint: Could not checkout revision!\n";
	goto bad;
    }

401
  okay:
402 403 404
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
405 406 407
    return 0;

  bad:
408 409 410
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
411 412 413 414 415 416 417
    return -1;
}

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

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

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

    #
    # 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";
437
	goto bad;
438 439 440
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCommit: $directory cannot be written!\n";
441
	goto bad;
442
    }
443 444 445
    my $cvsdir    = "$directory/repo";
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
446 447 448 449 450 451 452 453 454

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

458 459 460
    if (! chdir("$checkin")) {
	print STDERR "ArchiveCommit: Cannot chdir to $checkin!\n";
	goto bad;
461 462 463 464
    }

    # Get the current tags for the archive.
    my ($archive_tag, $archive_revision, $previous_tag);
465
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag,
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
			      \$archive_revision, \$previous_tag) < 0) {
	print STDERR "ArchiveCommit: ".
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

    #
    # Lets see if there has been any action since the last commit.
    # Check for new tags. 
    #
    my $query_result =
	DBQueryWarn("select tag from archive_tags ".
		    "where archive_idx='$archive_idx' ".
		    "order by date_created 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";
	goto okay;
    }

    if (!defined($newtag)) {
	my ($seconds, $microseconds) = gettimeofday();
	
	$newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
	$newtag .= $microseconds;
	$newtag .= "_commit";
    }

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

    # Clean the temp dir for next phase.
503
    mysystem("/bin/rm -rf $checkin/*");
504
    if ($?) {
505
	print STDERR "ArchiveCommit: Could not clean $checkin!\n";
506
	goto bad;
507 508 509
    }

    #
510
    # Form a new head revision and branch tag.
511
    #
512 513 514 515 516 517 518 519 520
    my $next_revision;
    if ($archive_revision =~ /^(\d*)\.(\d*)$/) {
	$next_revision = $1 . "." . ($2 + 1);
    }
    else {
	print STDERR "ArchiveCommit: ".
	    "Could not parse revision $archive_revision!\n";
	goto bad;
    }
521 522

    #
523 524
    # If this is the first commit of the archive, then just checkout
    # and commit to a new head revision. 
525
    #
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    if ($archive_revision eq "1.1") {
	mysystem("$CVSBIN $cvsopt -d $cvsdir checkout root");
	if ($?) {
	    print STDERR "ArchiveCommit: ".
		"Could not checkout $archive_tag!\n";
	    goto bad;
	}
    }
    else {
	#
	# Need to merge. Do a fresh checkout, merging the current import branch
	# into the head revsion.
	#
	# Yuck. Need to clear the -b (default branch) or else the merge
	# commit fails for some reason that makes no sense to me, but
	# must make sense to someone at CVS headquarters.
	#
	mysystem("$CVSBIN $cvsopt -d $cvsdir ".
		 "checkout -r $archive_revision root");
	if ($?) {
	    print STDERR "ArchiveCommit: ".
		"Could not checkout revision $archive_revision!\n";
	    goto bad;
	}
	
	mysystem("$CVSBIN $cvsopt -d $cvsdir admin -b root");
	if ($?) {
	    print STDERR "ArchiveCommit: ".
		"Could not clear the default branch!\n";
	    goto bad;
	}
	
	mysystem("$CVSBIN $cvsopt -d $cvsdir update -A ".
		 "-j $previous_tag -j $archive_tag root");
	if ($?) {
	    print STDERR "ArchiveCommit: ".
		"Could not checkout and merge $archive_tag into head.!\n";
	    goto bad;
	}
565 566
    }

567 568 569 570 571
    #
    # And then commit it back to the head revision, using bumped rev number.
    #
    mysystem("$CVSBIN $cvsopt -d $cvsdir commit -f -R -r $next_revision ".
	     "-m 'Commit merge of ${archive_tag} with head'");
572 573 574
    if ($?) {
	print STDERR "ArchiveCommit: ".
	    "Could not commit merge back to the repository!\n";
575
	goto bad;
576
    }
577 578 579 580 581 582 583 584 585

    #
    # Ack! We need to advance the default branch to match the head revision.
    # I think CVS is totally screwed up on this! 
    #
    mysystem("rcs -b${next_revision}.1 ".
	     "`$CVSBIN $cvsopt -d $cvsdir -q log -R`");

    DBQueryWarn("insert into archive_tags set ".
586
		"  tag='$newtag', revision='${next_revision}', ".
587
		"  archive_idx='$archive_idx', ".
588 589
		"  date_created=UNIX_TIMESTAMP(now())")
	or goto bad;
590

591 592
    DBQueryWarn("update archive_views set ".
		"  current_tag='$newtag', ".
593
		"  previous_tag='$archive_tag' ".
594 595
		"where archive_idx='$archive_idx' and view='$view'")
	or goto bad;
596 597

    # Clean the temp dir for later.
598
    mysystem("/bin/rm -rf $checkin/*");
599
    if ($?) {
600
	print STDERR "ArchiveCommit: Could not clean $checkin!\n";
601
	goto bad;
602 603 604
    }

    # And lets tag the tree for good measure with a commit tag.
605
    mysystem("$CVSBIN $cvsopt -d $cvsdir rtag -r $next_revision $newtag root");
606
    if ($?) {
607
	print STDERR "ArchiveCommit: Could not rtag with $newtag!\n";
608
	goto bad;
609 610
    }

611 612 613
    # And now into the checkout dir to checkout a current copy.
    if (! chdir("$checkout")) {
	print STDERR "ArchiveCommit: Cannot chdir to $checkout!\n";
614
	goto bad;
615
    }
616
    mysystem("$CVSBIN $cvsopt -d $cvsdir update -dP -r $next_revision");
617
    if ($?) {
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
	print STDERR "ArchiveCommit: Could not checkout head revision!\n";
	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.
#
sub ArchiveFork($$;$)
{
    my ($archive_idx, $newview, $view) = @_;
    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) {
656
	print STDERR "ArchiveCommit: ".
657 658 659 660 661
	    "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";
662
	goto bad;
663
    }
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
    my $cvsdir      = "$directory/repo";
    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 {
	print STDERR "ArchiveSavePoint: Bad data in $cwd!\n";
	goto bad;
    }

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

    # 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;
    }
    # Now checkout new view; this creates the $checkouts/$newview directory.
    mysystem("cd $checkouts; ".
	     "$CVSBIN $cvsopt -d $cvsdir checkout -r $archive_revision root; ".
	     "/bin/mv root ${newview}")
	== 0 or goto bad;

    

708
  okay:
709 710 711
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
712
    return 0;
713 714

  bad:
715 716 717
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
718
    return -1;
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
}

#
# 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) {
	print STDERR "ArchiveCommit: ".
	    "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;
    }
744
    my $cvsdir  = "$directory/repo";
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

    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.
    #
761
    mysystem("$TAR cf - -C $cvsdir . | tar xf - -C $target");
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
    if ($?) {
	print STDERR "ArchiveArchive: Could not copy in $directory\n";
	return -1;
    }
    return 0;
}

#
# Destroy an archive. The DB state is retained unless optional flag says
# to clean it.
#
sub ArchiveDestroy($;$)
{
    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;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveDestroy: $directory does not exist!\n";
	return 0;
    }

    mysystem("/bin/rm -rf $directory");
    if ($?) {
	print STDERR "ArchiveDestroy: ".
	    "Could not remove contents of $directory!\n";
	return -1;
    }
    if (defined($clean) && $clean) {
	(DBQueryWarn("delete from archive_tags ".
		     "where archive_idx='$archive_idx'") &&
800 801
	 DBQueryWarn("delete from archive_views ".
		     "where archive_idx='$archive_idx'") &&
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
	 DBQueryWarn("delete from file_archives ".
		     "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 =
	DBQueryWarn("select directory from file_archives where idx='$idx'");

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

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

#
# Get the current tag for an archive, given its index. Returns -1 on error,
# zero otherwise. Place tag in the return pointer.
#
832
sub GetArchiveCurrentTags($$$;$$)
833
{
834
    my ($archive_idx, $view, $tagp, $revnump, $prevp) = @_;
835 836
    
    my $query_result =
837 838 839 840 841 842 843
	DBQueryWarn("select v.current_tag,t.revision,v.previous_tag ".
		    "    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'");
844 845 846

    return -1
	if (!$query_result);
847
    my ($tag,$revision,$previous) = $query_result->fetchrow_array();
848
    
849 850 851 852 853 854
    $$tagp = $tag
	if (defined($tagp));
    $$revnump = $revision
	if (defined($revnump));
    $$prevp = $previous
	if (defined($prevp));
855 856 857 858 859 860 861 862
    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.
#
863
sub TBExperimentArchiveInfo($$$$)
864
{
865
    my ($pid, $eid, $idxp, $viewp) = @_;
866 867

    my $query_result =
868
	DBQueryWarn("select s.archive_idx,e.idx from experiments as e ".
869 870 871 872 873 874
		    "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);

875
    my ($archive_idx,$exptidx) = $query_result->fetchrow_array();
876 877

    return -1
878 879 880 881 882 883
	if (!defined($archive_idx));

    $$idxp = $archive_idx
	if (defined($idxp));
    $$viewp = "$exptidx"
	if (defined($viewp));
884
    
885
    return 0;
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
}

#
# 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) = @_;

    # 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();
909 910 911 912 913
    my $archive_tag = "T${rsrcidx}";

    #
    # Create the new archive and get back the new index. 
    #
914
    my $archive_idx = ArchiveCreate($archive_tag, "$exptidx");
915 916
    return -1
	if ($archive_idx < 0);
917 918 919 920 921 922

    if (! (DBQueryWarn("update experiment_stats set ".
		       "      archive_idx='$archive_idx' ".
		       "where pid='$pid' and eid='$eid' and ".
		       "      exptidx='$exptidx'") &&
	   DBQueryWarn("update experiment_resources set ".
923
		       "      archive_tag='$archive_tag' ".
924 925 926 927 928 929 930 931 932 933 934 935 936
		       "where idx='$rsrcidx'"))) {
	ArchiveDestroy($archive_idx, 1);
	return -1;
    }
    return 0;
}

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

    return -1
940
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
941

942
    return ArchiveAdd($archive_idx, $pathname, $view);
943 944 945
}

#
946
# SavePoint an experiment archive. 
947
#
948 949 950
sub TBExperimentArchiveSavePoint($$$)
{
    my ($pid, $eid, $tagext) = @_;
951
    my ($archive_idx, $view);
952 953

    return -1
954
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
955 956

    #
957
    # Derive a tag that contains some useful info?
958 959 960 961 962 963
    #
    my ($seconds, $microseconds) = gettimeofday();
    my $newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $newtag .= int($microseconds / 1000);
    $newtag .= "_${tagext}";

964
    return ArchiveSavePoint($archive_idx, $newtag, $view);
965 966 967 968 969 970 971 972
}

#
# Setup for a swapmod. A pain in the butt!
#
sub TBExperimentArchivePreSwapMod($$)
{
    my ($pid, $eid) = @_;
973
    my ($archive_idx, $view);
974 975

    return -1
976
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
977 978 979 980 981 982 983 984 985 986 987

    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchivePreSwapMod: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchivePreSwapMod: $directory cannot be written!\n";
	return -1;
    }
988 989
    my $checkin    = "$directory/checkins/$view";
    my $preswapdir = "${checkin}.preswap";
990 991

    #
992
    # Derive a tag that says something useful?
993 994 995 996 997 998 999 1000 1001 1002
    #
    my ($seconds, $microseconds) = gettimeofday();
    my $newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $newtag .= int($microseconds / 1000);
    $newtag .= "_preswapmod";

    #
    # Do a savepoint just for grins,
    #
    return -1
1003
	if (ArchiveSavePoint($archive_idx, $newtag, $view) != 0);
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

    #
    # Make a copy of the current tree, since its easier to rollback
    # if I just wait before doing a commit (until swapmod really finishes).
    #
    if (-e $preswapdir) {
	system("/bin/rm -rf $preswapdir");
	if (-e $preswapdir) {
	    print STDERR
		"ArchivePreSwapMod: Could not delete old preswap dir!\n";
	    return -1;
	}
    }
    if (! mkdir("$preswapdir", 0777)) {
	print STDERR "ArchivePreSwapMod: Could not mkdir $preswapdir: $!\n";
	return -1;
    }
    if (! chmod(0777, "$preswapdir")) {
	print STDERR "ArchivePreSwapMod: ".
	    "Could not chmod directory $preswapdir: $!\n";
	goto bad;
    }
    
1027
    mysystem("$TAR cf - -C $checkin . | tar xf - -C $preswapdir");
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    if ($?) {
	print STDERR "ArchivePreSwapMod: Could not copy to $preswapdir\n";
	goto bad;
    }
    return 0;

  bad:
    # Be sure to remove the new directory!
    if (-e $preswapdir) {
	system("/bin/rm -rf $preswapdir");
	if (-e $preswapdir) {
	    print STDERR
		"ArchivePreSwapMod: Could not delete new preswap dir!\n";
	}
    }
    return -1;
}

#
# Rollback from a failed swapmod.
#
sub TBExperimentArchiveRollBack($$)
{
    my ($pid, $eid) = @_;
1052
    my ($archive_idx, $view);
1053 1054

    return -1
1055
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchiveRollBack: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveRollBack: $directory cannot be written!\n";
	return -1;
    }
1067 1068
    my $checkin    = "$directory/checkins/$view";
    my $preswapdir = "${checkin}.preswap";
1069 1070 1071 1072 1073 1074 1075 1076

    # In case we bailed out really early in the swapmod path.
    return 0
	if (! -e $preswapdir);

    #
    # Restore the old (preswap) tree to the current tree.
    #
1077 1078 1079
    if (-e $checkin) {
	system("/bin/rm -rf $checkin");
	if (-e $checkin) {
1080 1081 1082 1083 1084
	    print STDERR
		"ArchiveRollBack: Could not delete old preswap dir!\n";
	    return -1;
	}
    }
1085
    system("/bin/mv -f $preswapdir $checkin");
1086 1087
    if ($?) {
	print STDERR "ArchiveRollBack: ".
1088
	    "Could not mv $preswapdir to $checkin\n";
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
	return -1;
    }
    return 0;
}

#
# Swapmod completed okay. Need to commit the old preswap directory and
# move forward. 
#
sub TBExperimentArchiveSwapModCommit($$)
1099 1100
{
    my ($pid, $eid) = @_;
1101
    my ($archive_idx, $view);
1102

1103
    return -1
1104
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
	print STDERR "ArchivePreSwapMod: ".
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchivePreSwapMod: $directory cannot be written!\n";
	return -1;
    }
1116 1117
    my $checkin    = "$directory/checkins/$view";
    my $preswapdir = "${checkin}.preswap";
1118 1119

    #
1120
    # We need this below.
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    #
    my $query_result =
	DBQueryWarn("select 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 ($rsrcidx) = $query_result->fetchrow_array();

1131 1132 1133
    #
    # Derive a useful tag.
    # 
1134 1135 1136 1137 1138 1139
    my ($seconds, $microseconds) = gettimeofday();
    my $newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $newtag .= int($microseconds / 1000);
    $newtag .= "_swapmod";

    return -1
1140
	if (ArchiveCommit($archive_idx, $newtag, $view, $preswapdir) != 0);
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

    if (!DBQueryWarn("update experiment_resources set ".
		     "      archive_tag='$newtag' ".
		     "where idx='$rsrcidx'")) {
	return -1;
    }

    #
    # Remove the preswap dir, but if it fails keep going. Will catch it
    # next time above.
    # 
    system("/bin/rm -rf $preswapdir");
    if ($?) {
	print STDERR "*** ArchiveRollBack: Could not rm $preswapdir\n";
    }

    ($seconds, $microseconds) = gettimeofday();
    $newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $newtag .= int($microseconds / 1000);
    $newtag .= "_postswapmod";

    #
    # Do a savepoint on the new tree.
    #
    return -1
1166
	if (ArchiveSavePoint($archive_idx, $newtag, $view) != 0);
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176

    return 0;
}

#
# Commit an experiment archive. 
#
sub TBCommitExperimentArchive($$$)
{
    my ($pid, $eid, $tagext) = @_;
1177
    my ($archive_idx, $view);
1178

1179
    return -1
1180
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
1181 1182

    #
1183
    # Need this below.
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    #
    my $query_result =
	DBQueryWarn("select 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 ($rsrcidx) = $query_result->fetchrow_array();

1194 1195 1196
    #
    # Derive a tag.
    #
1197 1198 1199 1200 1201 1202
    my ($seconds, $microseconds) = gettimeofday();
    my $newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $newtag .= int($microseconds / 1000);
    $newtag .= "_${tagext}";

    return -1
1203
	if (ArchiveCommit($archive_idx, $newtag, $view) != 0);
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218

    if (!DBQueryWarn("update experiment_resources set ".
		     "      archive_tag='$newtag' ".
		     "where idx='$rsrcidx'")) {
	return -1;
    }
    return 0;
}

#
# Archive an experiment archive to the save area.
# 
sub TBArchiveExperimentArchive($$)
{
    my ($pid, $eid) = @_;
1219
    my ($archive_idx, $view);
1220

1221 1222
    return -1
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
1223 1224

    return ArchiveArchive($archive_idx, TBExptLogDir($pid, $eid));
1225 1226 1227 1228 1229 1230 1231 1232 1233
}

#
# Delete an experiment archive. This just deletes it from the active area.
# Its historical DB state is retained.
#
sub TBDeleteExperimentArchive($$)
{
    my ($pid, $eid) = @_;
1234
    my ($archive_idx, $view);
1235

1236 1237
    return -1
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247

    return ArchiveDestroy($archive_idx, 0);
}

#
# Destroy an experiment archive. Totally flush it from the system.
#
sub TBDestroyExperimentArchive($$)
{
    my ($pid, $eid) = @_;
1248
    my ($archive_idx, $view);
1249

1250 1251
    return -1
	if (TBExperimentArchiveInfo($pid, $eid, \$archive_idx, \$view) < 0);
1252 1253 1254 1255 1256 1257

    return ArchiveDestroy($archive_idx, 1);
}

# _Always_ make sure that this 1 is at the end of the file...
1;