Archive.pm.in 41.5 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2005-2010 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#
package Archive;

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

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

# Must come after package declaration!
use libdb;
use libtestbed;
use Project;
use Experiment;
use Template;
use English;
use File::stat;
use File::Basename;
use Data::Dumper;
use POSIX qw(strftime getgid);
use Time::HiRes qw(gettimeofday);
use overload ('""' => 'Stringify');

# Configure variables
my $TB		= "@prefix@";
my $MAINSITE    = @TBMAINSITE@;
my $ARCHSUPPORT = @ARCHIVESUPPORT@;
51
my $USEARCHIVE  = $ARCHSUPPORT;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 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 111 112 113 114 115 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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
my %ALLOWEDPID  = ("testbed" => 1);
# 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 $SUCHOWN     = "$TB/sbin/suchown";
my $CHGRP       = "/usr/bin/chgrp";
my $TAR		= "/usr/bin/tar";
my $RSYNC	= "/usr/local/bin/rsync";
my $RM		= "/bin/rm";
my $REALPATH	= "/bin/realpath";
my $ZIP         = "/usr/local/bin/zip";
my $UNZIP       = "/usr/local/bin/unzip";
my $ZIPINFO     = "/usr/local/bin/zipinfo";
my $DU          = "/usr/bin/du";
my $DIFF        = "/usr/bin/diff";
my $inittag     = 'root';
my $defaultview = 'head';
my $REPO        = "ziprepo";
my $TAGVERSION  = 1;		# 0 is from SVN.
my $debug       = 1;
my $zipopt      = ($debug ? "-v" : "-q");
my $SHAREROOT   = SHAREROOT();
my $SCRATCHROOT = SCRATCHROOT();
my %ROOTS       = (PROJROOT()  => "proj",
		   USERROOT()  => "users",
		   $SHAREROOT  => "share",
		   GROUPROOT() => "groups");
if ($SCRATCHROOT) {
    $ROOTS{$SCRATCHROOT} = "scratch";
}

# Cache of instances to avoid regenerating them.
my %archives	= ();

my $TAGTYPE_USER      = "user";
my $TAGTYPE_COMMIT    = "commit";
my $TAGTYPE_SAVEPOINT = "savepoint";
my $TAGTYPE_INTERNAL  = "internal";

#
# Set umask so that other people in the project can mess with the archive.
#
umask(0002);

# On or off
sub doarchiving($$)
{
    my ($pid, $eid) = @_;

    return 0
	if (! $USEARCHIVE);

    my $project = Project->Lookup($pid);
    return 0
	if (!defined($project));
    
    my $experiment = Experiment->Lookup($pid, $eid);
    return 0
	if (!defined($experiment));

    # The experiment might be the one underlying a template.
    my $template = Template->LookupByPidEid($pid, $eid);
    
    return 1
	if (($experiment->IsInstance() || defined($template)) && 
	    (exists($ALLOWEDPID{$pid}) || $project->allow_workbench()));
    
    return 0;
}

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

    TBDebugTimeStampsOn();    

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

    TBDebugTimeStamp($command);
    my $retval = system($command);
    TBDebugTimeStamp("Done");

    return $retval;
}

# Another little helper for scripts that include this library.
sub setdebug($)
{
    my ($toggle) = @_;

    if ($toggle) {
	$debug  = $toggle;
	$zipopt = "-v";
    }
    else {
	$debug  = 0;
	$zipopt = "-q";
    }
}

#
# Lookup and create a class instance to return.
#
sub Lookup($$)
{
    my ($class, $archive_idx) = @_;

    # Look in cache first
    return $archives{$archive_idx}
        if (exists($archives{$archive_idx}));

    return undef
	if (! ($archive_idx =~ /^\d+$/));

    my $query_result =
	DBQueryWarn("select * from archives where idx='$archive_idx'");

    return undef
	if (!$query_result || !$query_result->numrows);

    my $self            = {};
    $self->{"DBROW"}    = $query_result->fetchrow_hashref();
    $self->{"VIEWS"}    = {};
    bless($self, $class);

    # Add to cache.
    $archives{$archive_idx} = $self;
    return $self;
}
# accessors
sub field($$)  { return ((! ref($_[0])) ? -1 : $_[0]->{'DBROW'}->{$_[1]}); }
sub idx($)		{ return field($_[0], 'idx'); }
sub unix_gid($)		{ return field($_[0], 'unix_gid'); }
sub directory($)        { return field($_[0], 'directory'); }
sub date_created($)     { return field($_[0], 'date_created'); }
sub archived($)         { return field($_[0], 'archived'); }
sub date_archived($)    { return field($_[0], 'date_archived'); }

# For views.
sub View($$)
{
    my ($self, $view) = @_;

    return undef
	if (! ref($self));

    my $idx = $self->idx();

    my $query_result =
	DBQueryWarn("select * from archive_views ".
		    "where archive_idx='$idx' and view='$view'");

    return undef
	if (!$query_result || !$query_result->numrows);

    return $query_result->fetchrow_hashref();
}

# For revisions
sub Revision($$$)
{
    my ($self, $view, $tag) = @_;

    return undef
	if (! ref($self));

    my $idx = $self->idx();

    my $query_result =
	DBQueryWarn("select * from archive_revisions ".
		    "where archive_idx='$idx' and ".
		    "      view='$view' and tag='$tag'");

    return undef
	if (!$query_result || !$query_result->numrows);

    return $query_result->fetchrow_hashref();
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $idx = $self->idx();

    my $query_result =
	DBQueryWarn("select * from archives where idx='$idx'");

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

    $self->{"DBROW"}  = $query_result->fetchrow_hashref();
    $self->{"VIEWS"}  = {};
    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $idx = $self->idx();

    return "[Archive: $idx]";
}

#
# Create a new archive. Returns -1 if any error. Otherwise return
# the new record index.
# 
sub Create($;$$)
{
    my ($class, $view, $unix_gid) = @_;
    
    my $idx;
    my $dir;

    $view = $defaultview
	if (!defined($view));
    $unix_gid = POSIX::getgid()
	if (!defined($unix_gid));

    #
    # Need to create the directory for it, once we have the index.
    # 
    my $query_result =
	DBQueryWarn("insert into archives set ".
		    "  idx=NULL, date_created=UNIX_TIMESTAMP(now())");

    return undef
	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;
    if (defined($unix_gid)) {
	mysystem("$CHGRP $unix_gid $dir") == 0 or goto bad;
    }

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

    #
    # Make subdirs. One to hold the 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.
    #
    my $repodir   = "$dir/$REPO";
    my $checkouts = "$dir/checkouts";
    my $checkins  = "$dir/checkins";

    if (! mkdir("$repodir", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $repodir: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$repodir")) {
	print STDERR "ArchiveCreate: Could not chmod $repodir: $!\n";
	goto bad;
    }
    if (! mkdir("$checkouts", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkouts: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$checkouts")) {
	print STDERR "ArchiveCreate: Could not chmod $checkouts: $!\n";
	goto bad;
    }
    if (! mkdir("$checkins", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins: $!\n";
	goto bad;
    }
    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";
	goto bad;
    }
    if (! mkdir("$repodir/$view", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins/$view: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$repodir/$view")) {
	print STDERR "ArchiveCreate: Could not chmod $checkins/$view: $!\n";
	goto bad;
    }
    
    # Now enter the default view (okay, branch) of this archive.
    DBQueryWarn("insert into archive_views set ".
		"  current_tag=NULL, archive_idx='$idx', view='$view', ".
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;

    return Archive->Lookup($idx);

  bad:
#    mysystem("$RM -rf $dir")
#        if (defined($dir));
    if (defined($idx)) {
	DBQueryFatal("delete from archive_views ".
		     "where view='$view' and archive_idx='$idx'");
	DBQueryFatal("delete from archives where idx='$idx'");
    }
    return undef;
}

#
# Helper function for below; Checks that a path is safe and legal.
#
sub ValidatePath($)
{
    my ($ppath)  = @_;
    # We get a pointer so we can return the new path.
    my $pathname = $$ppath;
    my $rootdir;

    # Taint check path before handing off to shell below.
    if ($pathname =~ /^([-\w\/\.\+\@,~]+)$/) {
	$pathname = $1;
    }
    else {
	print STDERR "*** ValidatePath: illegal characters in '$pathname'\n";
	return 1;
    }

402 403 404
    # XXX For template checkout/commit via xmlrpc interface
    $pathname =~ s/^\/q//;

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 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
    if (! -e $pathname || ! -r $pathname) {
	print STDERR "*** ValidatePath: $pathname cannot be read!\n";
	return 1;
    }

    #
    # Use realpath to check that the path does not contain links to
    # files outside the directory space the user is allowed to access.
    # We must taint check the result to keep everyone happy.
    #
    my $realpath = `$REALPATH $pathname`;
    if ($realpath =~ /^([-\w\/\.\+\@,~]+)$/) {
	$realpath = $1;
    }
    else {
	print STDERR "*** ValidatePath: ".
	    "Bad data returned by realpath: $realpath\n";
	return -1;
    }

    #
    # Strip leading /dir from the pathname. We want a relative path to
    # the rootdir so we can copy it in.
    #
    if ($realpath =~ /^[\/]+(\w+)\/(.+)$/) {
	$rootdir  = "/$1";
	$pathname = $2;
    }
    else {
	print STDERR "*** ValidatePath: ".
	    "Illegal characters in pathname: $realpath\n";
	return -1;
    }

    #
    # The file must reside in one of the Emulab "root" filesystems.
    #
    if (! exists($ROOTS{$rootdir})) {
	print STDERR "*** ValidatePath: ".
	    "$realpath does not resolve to an allowed directory!\n";
	return -1;
    }

    $$ppath = $realpath;
    return 0;
}
    
#
# 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. 
#
sub Add($$;$$$)
{
    my ($self, $pathname, $view, $exact, $special) = @_;

    return -1
	if (! ref($self));

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

    $exact = 0
	if (!defined($exact));

    $special = 0
	if (!defined($special));

    # This returns a taint checked value in $pathname.
    if (ValidatePath(\$pathname) != 0) {
	print STDERR "ArchiveAdd: Could not validate pathname $pathname\n";
	return -1;
    }

    #
    # Strip leading /dir from the pathname, we need it below.
    #
    my ($rootdir, $sourcedir, $sourcefile);
    my $rsyncopt = "";
    
    if ($special) {
	#
	# What does this do? 
	# Basically, we copy the last part (directory) to / of the checkin.
	# eg: cp /proj/pid/exp/eid... /exp of the checkins.
	# This avoids pid/eid tokens in the archive.
	#
	# Last part of path must be a directory.
	#
	if (! -d $pathname) {
	    print STDERR "ArchiveAdd: Must be a directory: $pathname\n";
	    return -1;
	}
	$rootdir    = "exp";
	$sourcedir  = $pathname;
	$sourcefile = "./";
    }
    elsif ($pathname =~ /^[\/]+(\w+)\/([-\w\/\.\+\@,~]+)$/) {
	$rootdir    = $1;
	$sourcedir  = $1;
	$sourcefile = $2;
	$rsyncopt   = "-R";
    }
    else {
	print STDERR "ArchiveAdd: Illegal characters in pathname $pathname\n";
	return -1;
    }

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveAdd: $directory cannot be written!\n";
	return -1;
    }
    my $checkin   = "$directory/checkins/$view";

    #
    # If the target rootdir exists and is not writable by the current
    # user, then run a chown over the whole subdir. This will avoid
    # avoid permission problems later during the rsync/tar ops below.
    #
    if (-e "$checkin/$rootdir" && ! -o "$checkin/$rootdir") {
	mysystem("$SUCHOWN $checkin/$rootdir") == 0 or return -1
    }
    
    #
    # 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). 
    #
    if (! -e "$checkin/$rootdir") {
	mysystem("$MKDIR $checkin/$rootdir") == 0 or return -1
    }
    
    if (-f "/${sourcedir}/${sourcefile}" || !$exact) {
	mysystem("$TAR cf - -C /$sourcedir $sourcefile | ".
		 "$TAR xf - -U -C $checkin/$rootdir");
	mysystem("$CHMOD 775 $checkin/$rootdir/$sourcefile");
    }
    else {
	mysystem("cd /$sourcedir; ".
		 "$RSYNC $rsyncopt -rtgoDlz ".
		 "  --delete ${sourcefile} $checkin/$rootdir");
    }
    if ($?) {
	print STDERR "ArchiveAdd: Could not copy in $pathname\n";
	return -1;
    }
    return 0;
}

#
# Do a diff of the checkin directory against provided directory to
# determine if anything has changed.
#
564
sub Diff($$;$$)
565
{
566 567
    my ($self, $pathname, $view, @exceptions) = @_;
    my $exclude_arg = "";
568 569 570 571 572 573 574 575 576 577 578 579

    return -1
	if (! ref($self));

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

    # This returns a taint checked value in $pathname.
    if (ValidatePath(\$pathname) != 0) {
	print STDERR "ArchiveDiff: Could not validate pathname $pathname\n";
	return -1;
    }
580 581 582 583 584 585

    if (@exceptions) {
	foreach my $exception (@exceptions) {
	    $exclude_arg .= " '--exclude=$exception'";
	}
    }
586 587 588 589 590 591 592 593 594
    
    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveAdd: $directory cannot be written!\n";
	return -1;
    }
595 596
    # See Add() above for why we add "exp"
    my $checkin   = "$directory/checkins/$view/exp";
597 598 599 600 601 602 603 604 605 606

    #
    # If the target rootdir exists and is not writable by the current
    # user, then run a chown over the whole subdir. This will avoid
    # avoid permission problems later during the rsync/tar ops below.
    #
    if (-e "$checkin" && ! -o "$checkin") {
	mysystem("$SUCHOWN $checkin") == 0 or return -1
    }

607
    my $retval = mysystem("$DIFF -q -r $exclude_arg $checkin $pathname");
608 609 610 611 612 613 614 615 616 617 618 619 620
    return 0
	if ($retval == 0);
    return 1
	if ($retval >> 8 == 1);

    # A real problem.
    return -1;
}

#
# Commit the current contents of the temporary store to the archive.
# Returns -1 if any error. Otherwise return 0.
#
621
sub Commit($;$$$$$)
622
{
623
    my ($self, $newtag, $comment, $mfile, $view, $altdir) = @_;
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 656 657 658 659 660 661 662 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
    my $noactivity = 0;
    my $cwd;

    return -1
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return -1
	if (!defined($View));

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

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCommit: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir   = "$directory/$REPO/$view";
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");

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

    if (! chdir("$checkin")) {
	print STDERR "ArchiveCommit: Cannot chdir to $checkin!\n";
	goto bad;
    }

    # Get the revision and user tag for the archive/view.
    my $current_tag  = $View->{'current_tag'};
    my $oldprev_tag  = $View->{'previous_tag'};
    my $revision     = $View->{'revision'};

    # args for new records.
    my $parent_revision = (defined($revision)    ? "'$revision'"    : "NULL");
    my $previous_tag    = (defined($current_tag) ? "'$current_tag'" : "NULL");

    #
    # Message can come from a file.
    #
    my $description = "'Commit Archive'";
	
    if (defined($mfile)) {
	if (! -r $mfile) {
	    print STDERR "*** ArchiveCommit: $mfile cannot be read!\n";
	    goto bad;
	}
	$description = DBQuoteSpecial(`cat $mfile`);
    }
690 691 692
    elsif (defined($comment)) {
	$description = DBQuoteSpecial($comment);
    }
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 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 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768

    #
    # Create a new revision record so I can get the revision number.
    # Need to update the tag later.
    #
    my $query_result =
	DBQueryWarn("insert into archive_revisions set revision=NULL, ".
		    "  archive_idx='$archive_idx', view='$view', ".
		    "  parent_revision=$parent_revision, ".
		    "  description=$description, ".
		    "  date_created=UNIX_TIMESTAMP(now())") or goto bad;

    my $newrevision = $query_result->insertid;
    my $zipfile     = "$repodir/$newrevision";
    $newtag         = (defined($newtag) ? $newtag : "R${newrevision}");
    
    #
    # Okay, zip up the checkin directory. This becomes a new "revision"
    #
    mysystem("$ZIP $zipopt -y -r $zipfile .") == 0 or goto bad;

    #
    # Enter new tag and revision now that we got it all.
    #
    DBQueryWarn("update archive_views set ".
		"  revision='$newrevision', ".
		"  current_tag='$newtag', ".
		"  previous_tag=$previous_tag ".
		"where archive_idx='$archive_idx' and view='$view'")
	or goto bad;

    DBQueryWarn("update archive_revisions set ".
		"  tag='$newtag' ".
		"where archive_idx='$archive_idx' and revision='$newrevision'")
	or goto bad;

    # Backwards compat
    DBQueryWarn("insert into archive_tags set idx=NULL, version=$TAGVERSION, ".
		"  tag='$newtag', view='$view', ".
		"  archive_idx='$archive_idx', ".
		"  tagtype='$TAGTYPE_COMMIT', ".
		"  date_created=UNIX_TIMESTAMP(now())")
	or goto bad;

  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

  bad:
    if (defined($newrevision)) {
	# args for new records.
	$revision     = (defined($revision)    ? "'$revision'"    : "NULL");
	$current_tag  = (defined($current_tag) ? "'$current_tag'" : "NULL");
	$previous_tag = (defined($oldprev_tag) ? "'$oldprev_tag'" : "NULL");
	
	DBQueryWarn("update archive_views set ".
		    "  revision=$revision, ".
		    "  current_tag=$current_tag, ".
		    "  previous_tag=$previous_tag ".
		    "where archive_idx='$archive_idx' and view='$view'");
	DBQueryFatal("update archive_revisions set ".
		     "  tag=$current_tag ".
		     "where archive_idx='$archive_idx' ".
		     "      and revision='$newrevision'");
	DBQueryWarn("delete from archive_revisions ".
		    "where revision='$newrevision' and ".
		    "      archive_idx='$archive_idx'");
    }
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return -1;
}

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 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
#
# Revise is a lot like commit, except that we are changing an arbitrary
# revision, not the head of the view. 
#
sub Revise($$$$$$$)
{
    my ($self, $oldtag, $newtag, $comment, $mfile, $view, $dir) = @_;
    my $noactivity = 0;
    my $cwd;

    return -1
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return -1
	if (!defined($View));

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

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveRevise: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir   = "$directory/$REPO/$view";
    my $checkin   = $dir;

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

    if (! chdir("$checkin")) {
	print STDERR "ArchiveRevise: Cannot chdir to $checkin!\n";
	goto bad;
    }

    my $revision_row = $self->Revision($view, $oldtag);
    if (!defined($revision_row)) {
	print STDERR "ArchiveRevise: Could not find revision for $oldtag!\n";
	goto bad;
    }
    my $parent_revision = $revision_row->{'revision'};

    #
    # Message can come from a file.
    #
    my $description = "'Revise Archive'";
	
    if (defined($mfile)) {
	if (! -r $mfile) {
	    print STDERR "*** ArchiveRevise: $mfile cannot be read!\n";
	    goto bad;
	}
	$description = DBQuoteSpecial(`cat $mfile`);
    }
    elsif (defined($comment)) {
	$description = DBQuoteSpecial($comment);
    }

    #
    # Create a new revision record so I can get the revision number.
    # Need to update the tag later.
    #
    my $query_result =
	DBQueryWarn("insert into archive_revisions set revision=NULL, ".
		    "  archive_idx='$archive_idx', view='$view', ".
		    "  parent_revision=$parent_revision, ".
		    "  description=$description, ".
		    "  date_created=UNIX_TIMESTAMP(now())") or goto bad;

    my $newrevision = $query_result->insertid;
    my $zipfile     = "$repodir/$newrevision";
    $newtag         = (defined($newtag) ? $newtag : "R${newrevision}");
    
    #
    # Okay, zip up the checkin directory. This becomes a new "revision"
    #
    mysystem("$ZIP $zipopt -y -r $zipfile .") == 0 or goto bad;

    DBQueryWarn("update archive_revisions set ".
		"  tag='$newtag' ".
		"where archive_idx='$archive_idx' and revision='$newrevision'")
	or goto bad;

    # Backwards compat
    DBQueryWarn("insert into archive_tags set idx=NULL, version=$TAGVERSION, ".
		"  tag='$newtag', view='$view', ".
		"  archive_idx='$archive_idx', ".
		"  tagtype='$TAGTYPE_COMMIT', ".
		"  date_created=UNIX_TIMESTAMP(now())")
	or goto bad;

  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

  bad:
    if (defined($newrevision)) {
	DBQueryWarn("delete from archive_revisions ".
		    "where revision='$newrevision' and ".
		    "      archive_idx='$archive_idx'");
    }
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return -1;
}

#
# Also like commit, but just replaces the zip archive file.
#
sub Replace($$$)
{
    my ($self, $oldtag, $view) = @_;
    my $cwd;

    return -1
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return -1
	if (!defined($View));

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

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveReplace: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir   = "$directory/$REPO/$view";
    my $checkin   = "$directory/checkins/$view"; 

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

    if (! chdir("$checkin")) {
	print STDERR "ArchiveReplace: Cannot chdir to $checkin!\n";
	goto bad;
    }

    my $revision_row = $self->Revision($view, $oldtag);
    if (!defined($revision_row)) {
	print STDERR "ArchiveReplace: Could not find revision for $oldtag!\n";
	goto bad;
    }
    my $revision = $revision_row->{'revision'};
    my $zipfile  = "$repodir/${revision}.zip";
    my $savefile = "$repodir/${revision}.save";

    if (-e $zipfile) {
	# print STDERR "ArchiveReplace: renaming $zipfile to $savefile\n";
956
if (!rename($zipfile, $savefile)) {
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
	    print STDERR "ArchiveReplace: Could not backup $zipfile!\n";
	    goto bad;
	}
    }
    
    #
    # Okay, zip up the checkin directory. This becomes a new "revision"
    #
    mysystem("$ZIP $zipopt -y -r $zipfile .") == 0 or goto bad;

  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

  bad:
    if (defined($zipfile) && -e $savefile) {
	if (!rename($savefile, $zipfile)) {
	    print STDERR "ArchiveReplace: Could not restore $zipfile!\n";
	    goto bad;
	}
    }
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return -1;
}

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
#
# Fork an archive (okay, branch) for use in separate development.
#
sub Fork($$;$$)
{
    my ($self, $newview, $newtag, $view) = @_;
    my $cwd;

    return -1
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return -1
	if (!defined($View));

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

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveFork: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir     = "$directory/$REPO/$view";
    my $newrepodir  = "$directory/$REPO/$newview";
    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 "ArchiveFork: Bad data in $cwd!\n";
	goto bad;
    }

    # Get the revision and user tag for the archive/view.
    my $current_tag  = $View->{'current_tag'};
    my $revision     = $View->{'revision'};

    # Not allowed to fork an archive with no revisions
    goto bad
	if (!defined($revision));

    # Create new view directories.
    if (! mkdir("$newrepodir", 0777)) {
	print STDERR "ArchiveFork: Could not mkdir $newrepodir: $!\n";
	goto bad;
    }
    if (! mkdir("$newcheckin", 0777)) {
	print STDERR "ArchiveFork: Could not mkdir $newcheckin: $!\n";
	goto bad;
    }
    if (! chmod(0777, "$newcheckin")) {
	print STDERR "ArchiveFork: Could not chmod $newcheckin: $!\n";
	goto bad;
    }

    #
    # Create a new revision record so I can get the revision number.
    # Need to update the tag later.
    #
    my $query_result =
	DBQueryWarn("insert into archive_revisions set revision=NULL, ".
		    "  archive_idx='$archive_idx', view='$newview', ".
		    "  parent_revision='$revision',".
		    "  description='Archive Fork from $view/$revision', ".
		    "  date_created=UNIX_TIMESTAMP(now())") or goto bad;

    my $newrevision = $query_result->insertid;
    my $newzipfile  = "$newrepodir/${newrevision}.zip";
    my $oldzipfile  = "$repodir/${revision}.zip";
    $newtag         = (defined($newtag) ? $newtag : "R${newrevision}");

    # Make a copy of the zip file; this is probably silly, but at least
    # I know I've got a clean copy later. Revisit this.
    mysystem("/bin/cp -p $oldzipfile $newzipfile") == 0 or goto bad;
    
    # Now enter the newview (okay, branch) of this archive.
    DBQueryWarn("insert into archive_views set ".
		"  archive_idx='$archive_idx', current_tag='$newtag', ".
		"  view='$newview', revision='$newrevision', ".
		"  parent_view='$view', parent_revision='$revision', ".
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;

    DBQueryWarn("update archive_revisions set ".
		"  tag='$newtag' ".
		"where archive_idx='$archive_idx' and revision='$newrevision'")
	or goto bad;

    # backwards compat
    DBQueryWarn("insert into archive_tags set idx=NULL, version=$TAGVERSION, ".
		"  tag='$newtag', archive_idx='$archive_idx', ".
		"  tagtype='$TAGTYPE_INTERNAL', ".
		"  view='$newview', ".
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;

  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

  bad:
    if (defined($newrevision)) {
	DBQueryWarn("delete from archive_views ".
		    "where archive_idx='$archive_idx' and view='$newview'");
	DBQueryWarn("delete from archive_tags ".
		    "where archive_idx='$archive_idx' and view='$newview' ".
		    "  and tag='$newtag'");
	DBQueryWarn("delete from archive_revisions ".
		    "where revision='$newrevision' and ".
		    "      archive_idx='$archive_idx'");
    }
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return -1;
}

#
# Checkout a copy of the archive, optionally at a particular view/branch.
#
1123
sub Checkout($$;$$@)
1124
{
1125
    my ($self, $target, $view, $tag, @subdirs) = @_;
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 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 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    my $cwd;

    return -1
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return -1
	if (!defined($View));

    # Cannot checkout if there are no revisions.
    return -1
	if (!defined($View->{'revision'}));

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

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCheckout: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir = "$directory/$REPO/$view";

    #
    # 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.
    my $revision;
    
    if (defined($tag)) {
	my $revision_row = $self->Revision($view, $tag);

	if (!defined($revision_row)) {
	    print STDERR "ArchiveCheckout: ".
		"Could not locate a revision for $view/$tag in $self\n";
	    goto bad;
	}
	$revision = $revision_row->{'revision'};
    }
    else {
	# Trunk, sorta.
	$revision = $View->{'revision'};
    }
    my $zipfile = "$repodir/$revision";
1201 1202 1203 1204 1205 1206 1207 1208 1209

    # Append * to directories.
    for (my $i = 0; $i < scalar(@subdirs); $i++) {
	my $subdir = $subdirs[$i];

	if ($subdir =~ /\/$/) {
	    $subdirs[$i] .= "*";
	}
    }
1210
    
1211 1212 1213
    # Allowed to check out a set of files/dirs
    my $subdir_arg = (! @subdirs ? "" :
		      join(" ", map("'" . $_ . "'", @subdirs)));
1214 1215 1216 1217 1218 1219

    # unzip has a different verbose option.
    my $unzipopt = ($debug ? "" : "-q");

    # Now check it out
    if (my $rval = mysystem("cd $target; ".
1220
			    "$UNZIP $unzipopt -o -u $zipfile $subdir_arg")) {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
	# Allow for exit(11) from unzip, which says the requested files
	# where not in the archive. Not really an error.
	goto bad
	    if ($rval >> 8 != 11);
    }

  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

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

#
# List contents of archive. 
#
sub List($$;$$$$)
{
    my ($self, $prval, $view, $long, $tag, $subdir) = @_;
    my @filelist = ();
    my $cwd;

    return -1
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return -1
	if (!defined($View));

    # Cannot list if there are no revisions.
    return -1
	if (!defined($View->{'revision'}));

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

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveList: $directory cannot be written!\n";
	goto bad;
    }
    my $repodir = "$directory/$REPO/$view";

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

    # Where to find what we want.
    my $revision;
    
    if (defined($tag)) {
	my $revision_row = $self->Revision($view, $tag);

	if (!defined($revision_row)) {
	    print STDERR "ArchiveList: ".
		"Could not locate a revision for $view/$tag in $self\n";
	    goto bad;
	}
	$revision = $revision_row->{'revision'};
    }
    else {
	# Trunk, sorta.
	$revision = $View->{'revision'};
    }
    my $zipfile = "$repodir/$revision";
    
    # Allowed to check out a particular subdir (but not a file).
    $subdir = (defined($subdir) ? "'$subdir/*'" : "");

    # Long or short listing ...
    my $zipinfoopt = ($long ? "-l" : "-1");

    #
    # Start a subprocess that does the listing, and then read it back.
    #
    if (!open(LIST, "$ZIPINFO $zipinfoopt $zipfile $subdir |")) {
	print STDERR "ArchiveList: Could not start $ZIPINFO!\n";
	goto bad;
    }
    while (<LIST>) {
	if (!defined($prval)) {
	    print $_;
	}
	else {
	    chomp($_);
	    push(@filelist, $_);
	}
    }
    goto bad
	if (! close(LIST));

    @$prval = @filelist
	if (defined($prval));
    
  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

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

#
# DU contents of archive repo.
#
sub DU($$)
{
    my ($self, $prval) = @_;
    my $cwd;

    return -1
	if (! ref($self));

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory = $self->directory();
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveList: $directory cannot be written!\n";
	return -1;
    }
    my $repo = "$directory/$REPO";

    #
    # Start a subprocess that does the du, and then read it back.
    #
    if (!open(DU, "$DU -s -k $repo |")) {
	print STDERR "ArchiveDU: Could not start du!\n";
	return -1;
    }
    my $line;
    
    while (<DU>) {
	chomp($_);
	$line = $_;
    }
    return -1
	if (! close(DU));

    if ($line =~ /^(\d+)\s+/) {
	$$prval = $1;
	return 0;
    }
    return -1;
}

#
# 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 Archive($$)
{
    my ($self, $view) = @_;

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

    return -1
	if (! ref($self));

    my $archive_idx  = $self->idx();
    my $target       = "$ARCHIVEDIR/Archive/$archive_idx";
    my $directory    = $self->directory();
    
    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 600) !=
	    TBSCRIPTLOCK_OKAY());

    #
    # Need additional check to make sure that it has not already been
    # archived.
    #
    if ($self->archived()) {
	print STDERR "ArchiveArchive: ".
	    "Archive $self already archived on ". $self->date_archived() ."\n";
	goto okay;
    }

    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveArchive: $directory cannot be written!\n";
	goto bad;
    }

    # Is it shared? If so, certainly do not archive it!
    my $shared = $self->IsShared();
    if (! defined($shared)) {
	goto bad;
    }
    if ($shared) {
	print STDERR "ArchiveArchive: ".
	    "Archive '$archive_idx' is shared; not archiving!\n";

	#
	# Even if shared, we want to clean out the current view since
	# those files are no longer needed.
	#
	my $checkouts = "$directory/checkouts/$view";
	my $checkins  = "$directory/checkins/$view";

	#
	# If the target dir exists and is not writable by the current
	# user, then run a chown over the whole subdir. This will avoid
	# avoid permission problems during the rm.
	#
	if (-e "$checkouts" && ! -o "$checkouts") {
	    mysystem("$SUCHOWN $checkouts");
	}
	if (-e "$checkins" && ! -o "$checkins") {
	    mysystem("$SUCHOWN $checkins");
	}
	mysystem("/bin/rm -rf $checkins $checkouts");
	goto okay;
    }
    
    if (! -e $target) {
	if (! mkdir("$target", 0777)) {
	    print STDERR "ArchiveArchive: Could not mkdir $target: $!\n";
	    goto bad;
	}
	if (! chmod(0777, "$target")) {
	    print STDERR "ArchiveArchive: ".
		"Could not chmod directory $target: $!\n";
	    goto bad;
	}
    }    
    mysystem("$RSYNC -a --delete $directory/$REPO $target");
    if ($?) {
	print STDERR "ArchiveArchive: Could not copy $directory/$REPO.\n";
	goto bad;
    }

    #
    # Update its location in the DB, and remove the old directory.
    # 
    DBQueryWarn("update archives set ".
		"   directory='$target', ".
		"   archived=1, ".
		"   date_archived=UNIX_TIMESTAMP(now()) ".
		"where idx='$archive_idx'")
	or goto bad;
    
    mysystem("/bin/rm -rf $directory");
    if ($?) {
	print STDERR "ArchiveArchive: ".
	    "Could not remove contents of $directory!\n";
	goto bad;
    }

  okay:
    TBScriptUnlock();
    return 0;

  bad:
    TBScriptUnlock();
    return -1;
}

#
# Destroy an archive. The DB state is retained unless optional flag says
# to clean it.
#
1511
sub Destroy($$;$$)
1512
{
1513
    my ($self, $clean, $view, $force) = @_;
1514 1515 1516

    $view = $defaultview
	if (!defined($view));
1517 1518
    $force = 0
	if (!defined($force));
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533

    return -1
	if (! ref($self));

    my $archive_idx  = $self->idx();
    my $directory    = $self->directory();
    
    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 600) !=
	    TBSCRIPTLOCK_OKAY());

    #
    # Need additional check to make sure that it has not already been
    # archived. Do not want to do anything, unless clean is specified.
    #
1534
    if ($self->archived() && !$force) {
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	print STDERR "ArchiveArchive: ".
	    "Archive $self archived on ". $self->date_archived() ."\n";
	goto okay;
    }
    if (! -d $directory || ! -w $directory) {
	goto okay;
    }

    # Is it shared? If so, certainly do not delete it!
    my $shared = $self->IsShared();
    if (! defined($shared)) {
	goto bad;
    }
1548
    if (!$shared || $force) {
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
	mysystem("/bin/rm -rf $directory");
	if ($?) {
	    print STDERR "ArchiveDestroy: ".
		"Could not remove contents of $directory!\n";
	    goto bad;
	}
    }
    elsif ($clean) {
	my $checkout  = "$directory/checkouts/$view";
	my $checkin   = "$directory/checkins/$view";
	my $repodir   = "$directory/$REPO/$view";

	mysystem("/bin/rm -rf $checkout $checkin");
	if ($?) {
	    print STDERR "ArchiveDestroy: ".
		"Could not remove contents of $directory!\n";
	    goto bad;
	}
    }
    
    if ($clean) {
	(DBQueryWarn("delete from archive_tags ".
		     "where archive_idx='$archive_idx' and view='$view'") &&
	 DBQueryWarn("delete from archive_views ".
		     "where archive_idx='$archive_idx' and view='$view'") &&
	 DBQueryWarn("delete from archive_revisions ".
		     "where archive_idx='$archive_idx' and view='$view'"))
	    || goto bad;
	
	if (! $shared) {
	    DBQueryWarn("delete from archives ".
			"where idx='$archive_idx'") || goto bad;
	}
    }
  okay:
    TBScriptUnlock();
    return 0;

  bad:
    TBScriptUnlock();
    return -1;
}

#
# See if the archive is shared amongst more then one experiment. This
# only looks at current experiments. Once an archive is archived, not
# sure what we will do if the user want to branch from it. 
#
sub IsShared($)
{
    my ($self) = @_;

    my $idx = $self->idx();
    
    my $query_result =
	DBQueryWarn("select e.pid,e.eid,s.archive_idx from experiments as e ".
		    "left join experiment_stats as s on s.exptidx=e.idx ".
		    "where s.archive_idx='$idx'");

    return undef
	if (!$query_result);

    return ($query_result->numrows > 1);
}

#
# See if a tag is unique to the archive.
#
sub IsTagUnique($$;$)
{
    my ($self, $tag, $view) = @_;
    
    $view = $defaultview
	if (!defined($view));

    my $idx = $self->idx();

    my $query_result =
	DBQueryWarn("select revision from archive_revisions ".
		    "where archive_idx='$idx' and ".
		    "      view='$view' and tag='$tag'");
    return undef
	if (!$query_result);

    return ($query_result->numrows == 0);
}

1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
#
# Generate a tag. Nothing special, just a convenience function.
#
sub GenerateTag($$)
{
    my ($self, $tagext) = @_;
    my $newtag;
    
    my ($seconds, $microseconds) = gettimeofday();
    $newtag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $newtag .= int($microseconds / 1000);
    $newtag .= "_${tagext}";

    return $newtag;
}

1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
#
# Return pointer to zip archive file.
#
sub ZipFile($;$$)
{
    my ($self, $view, $tag) = @_;

    return undef
	if (! ref($self));
    my $archive_idx  = $self->idx();

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

    my $View = $self->View($view);
    return undef
	if (!defined($View));

    # Cannot list if there are no revisions.
    return undef
	if (!defined($View->{'revision'}));

    my $directory = $self->directory();
    my $repodir   = "$directory/$REPO/$view";

    # Where to find what we want.
    my $revision;
    
    if (defined($tag)) {
	my $revision_row = $self->Revision($view, $tag);

	if (!defined($revision_row)) {
	    print STDERR "ArchiveList: ".
		"Could not locate a revision for $view/$tag in $self\n";
	    return undef;
	}
	$revision = $revision_row->{'revision'};
    }
    else {
	# Trunk, sorta.
	$revision = $View->{'revision'};
    }
    return "$repodir/${revision}.zip";
}


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