libArchive.pm.in 56.1 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
Timothy Stack's avatar
Timothy Stack committed
4
# Copyright (c) 2005, 2006 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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
my $MAINSITE    = @TBMAINSITE@;
31 32
my $ARCHSUPPORT = @ARCHIVESUPPORT@;
my $USEARCHIVE  = ($MAINSITE || $ARCHSUPPORT);
33 34
my %ALLOWEDPID  = ("testbed" => 1, "compadres" => 1, "tbres" => 1,
		   "fightfire" => 1);
35 36 37 38 39 40 41 42
# 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";
43
my $CHGRP       = "/usr/bin/chgrp";
44
my $TAR		= "/usr/bin/tar";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
45
my $RSYNC	= "/usr/local/bin/rsync";
46
my $RM		= "/bin/rm";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
my $REALPATH	= "/bin/realpath";
48 49 50
my $SVN         = "/usr/local/bin/svn";
my $SVNADMIN    = "/usr/local/bin/svnadmin";
my $IMPORTER    = "$TB/sbin/svn_load_dirs.pl";
51
my $inittag     = 'root';
52
my $defaultview = 'head';
53
my $debug       = 0;
54
my $svnopt      = ($debug ? "" : "-q");
55 56 57 58 59 60 61 62 63
my $SHAREROOT   = SHAREROOT();
my $SCRATCHROOT = SCRATCHROOT();
my %ROOTS       = (PROJROOT()  => "proj",
		   USERROOT()  => "users",
		   $SHAREROOT  => "share",
		   GROUPROOT() => "groups");
if ($SCRATCHROOT) {
    $ROOTS{$SCRATCHROOT} = "scratch";
}
64

65 66 67 68 69
my $TAGTYPE_USER      = "user";
my $TAGTYPE_COMMIT    = "commit";
my $TAGTYPE_SAVEPOINT = "savepoint";
my $TAGTYPE_INTERNAL  = "internal";

70 71 72 73 74
#
# Set umask so that other people in the project can mess with the archive.
#
umask(0002);

75 76 77 78 79 80 81 82 83 84 85
# On or off
sub doarchiving($)
{
    my ($pid) = @_;
    
    return 1
	if ($USEARCHIVE && exists($ALLOWEDPID{$pid}));
    
    return 0;
}

86 87 88 89 90
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
91 92
    TBDebugTimeStampsOn();    

93 94 95 96
    # Need a big TMPDIR for svn stuff.
    my $tmpdir = $ENV{'TMPDIR'};
    $ENV{'TMPDIR'} = "/usr/testbed/tmp";

97 98
    print STDERR "Running '$command'\n"
	if ($debug);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
99 100

    TBDebugTimeStamp($command);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
101
    my $retval = system($command);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
102
    TBDebugTimeStamp("Done");
103 104
    $ENV{'TMPDIR'} = $tmpdir
	if (defined($tmpdir));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
105 106

    return $retval;
107 108
}

109 110 111 112 113 114
# Another little helper for scripts that include this library.
sub setdebug($)
{
    my ($toggle) = @_;

    if ($toggle) {
115
	$debug  = $toggle;
116 117 118 119 120 121 122 123
	$svnopt = "";
    }
    else {
	$debug  = 0;
	$svnopt = "-q";
    }
}

124 125 126 127
#
# Create a new archive. Returns -1 if any error. Otherwise return
# the new record index.
# 
128
sub ArchiveCreate(;$$$)
129
{
130
    my ($tag, $view, $unix_gid) = @_;
131
    
132 133
    my $idx;
    my $dir;
134 135 136

    $tag = $inittag
	if (!defined($tag));
137 138
    $view = $defaultview
	if (!defined($view));
139

140
    # Tags cannot must start with a letter.
141 142 143
    if ($tag =~ /^\d+/) {
	$tag = "T" . $tag;
    }
144 145 146 147 148

    #
    # Need to create the directory for it, once we have the index.
    # 
    my $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
149
	DBQueryWarn("insert into archives set ".
150
		    "  idx=NULL, ".
151 152 153 154 155 156 157 158 159 160 161 162 163 164
		    "  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;
165 166 167
    if (defined($unix_gid)) {
	mysystem("$CHGRP $unix_gid $dir") == 0 or goto bad;
    }
168

Leigh B. Stoller's avatar
Leigh B. Stoller committed
169
    DBQueryWarn("update archives set directory='$dir' where idx='$idx'")
170 171 172
	or goto bad;

    #
173
    # Make subdirs. One to hold the control tree, and the other
174 175
    # to hold currently checked out versions of the tree. Lastly, we
    # need a place to copyin files before they are added to the repo.
176
    #
177
    my $repodir   = "$dir/repo";
178 179
    my $checkouts = "$dir/checkouts";
    my $checkins  = "$dir/checkins";
180

181 182
    if (! mkdir("$repodir", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $repodir: $!\n";
183 184
	goto bad;
    }
185 186
    if (! chmod(0777, "$repodir")) {
	print STDERR "ArchiveCreate: Could not chmod $repodir: $!\n";
187 188
	goto bad;
    }
189 190
    if (! mkdir("$checkouts", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkouts: $!\n";
191 192
	goto bad;
    }
193 194
    if (! chmod(0777, "$checkouts")) {
	print STDERR "ArchiveCreate: Could not chmod $checkouts: $!\n";
195 196
	goto bad;
    }
197 198
    if (! mkdir("$checkins", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins: $!\n";
199 200
	goto bad;
    }
201 202 203 204 205 206 207 208 209 210
    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";
211 212
	goto bad;
    }
213
    # Initialize the repo.
214
    mysystem("$SVNADMIN create --fs-type fsfs $repodir") == 0
215
	or goto bad;
216 217 218 219
    
    # 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
220
	     "         mkdir $view/history; ".
Timothy Stack's avatar
Timothy Stack committed
221
	     "$SVN import $svnopt -m 'ArchiveCreate' ".
222
	     "     $view file://$repodir/$view")
223 224 225
	== 0 or goto bad;

    # Create a branch tag in the tags directory to base differences against.
226
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
227 228
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${tag}-branch")
229
	== 0 or goto bad;
230 231 232 233 234 235 236 237

    # 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.
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate' ".
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/history/${tag}")
	== 0 or goto bad;
238
    
239 240
    # Now check it out. This creates the $checkouts/$view directory.
    mysystem("cd $checkouts; ".
241
	     "$SVN checkout $svnopt file://$repodir/$view")
242 243
	== 0 or goto bad;

244 245 246 247 248
    # 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;
    
249
    # Now enter an initial tag for the tree. Nothing actually gets tagged.
250 251
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
		"  tag='$tag', archive_idx='$idx', view='$view', ".
252
		"  tagtype='$TAGTYPE_INTERNAL', ".
253 254 255 256 257 258 259
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
    
    return $idx;

  bad:
#    mysystem("$RM -rf $dir")
#        if (defined($dir));
260 261 262
    DBQueryFatal("delete from archive_views ".
		 "where view='$view' and archive_idx='$idx'")
	if (defined($idx));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
263
    DBQueryFatal("delete from archives where idx='$idx'")
264 265 266 267 268
	if (defined($idx));
    return -1;
}

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

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

287
    if (! -e $pathname || ! -r $pathname) {
288 289
	print STDERR "*** ValidatePath: $pathname cannot be read!\n";
	return 1;
290 291 292
    }

    #
293 294
    # Use realpath to check that the path does not contain links to
    # files outside the directory space the user is allowed to access.
295
    # We must taint check the result to keep everyone happy.
296
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
297
    my $realpath = `$REALPATH $pathname`;
298
    if ($realpath =~ /^([-\w\/\.\+\@,~]+)$/) {
299 300 301
	$realpath = $1;
    }
    else {
302
	print STDERR "*** ValidatePath: ".
303
	    "Bad data returned by realpath: $realpath\n";
304
	return -1;
305
    }
306

307
    #
308 309
    # Strip leading /dir from the pathname. We want a relative path to
    # the rootdir so we can copy it in.
310
    #
311
    if ($realpath =~ /^[\/]+(\w+)\/(.+)$/) {
312
	$rootdir  = "/$1";
313
	$pathname = $2;
314 315
    }
    else {
316 317
	print STDERR "*** ValidatePath: ".
	    "Illegal characters in pathname: $realpath\n";
318 319 320 321 322 323 324
	return -1;
    }

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

330 331 332 333 334 335 336 337 338 339
    $$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. 
#
340
sub ArchiveAdd($$;$$$)
341
{
342
    my ($archive_idx, $pathname, $view, $exact, $special) = @_;
343 344 345 346 347 348 349

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

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

350 351 352
    $special = 0
	if (!defined($special));

353 354 355 356 357 358 359 360 361
    # 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.
    #
362 363 364 365 366
    my ($rootdir, $sourcedir, $sourcefile);
    my $rsyncopt = "";
    
    if ($special) {
	#
367 368 369 370 371 372
	# What does this do? 
	# Basically, we copy the last part (directory) to / of the checkin.
	# eg: cp /proj/pid/exp/eid/archive/... /archive of the checkins.
	# This avoids pid/eid tokens in the archive.
	#
	# Last part of path must be a directory.
373 374
	#
	if (! -d $pathname) {
375
	    print STDERR "ArchiveAdd: Must be a directory: $pathname\n";
376 377 378 379 380 381 382 383 384 385 386 387 388
	    return -1;
	}
	my ($filename,$directory,undef) = fileparse($pathname);

	$rootdir    = $filename;
	$sourcedir  = $directory;
	$sourcefile = $filename . "/";
    }
    elsif ($pathname =~ /^[\/]+(\w+)\/([-\w\/\.\+\@,~]+)$/) {
	$rootdir    = $1;
	$sourcedir  = $1;
	$sourcefile = $2;
	$rsyncopt   = "-R";
389 390 391 392 393 394
    }
    else {
	print STDERR "ArchiveAdd: Illegal characters in pathname $pathname\n";
	return -1;
    }

395 396 397 398 399
    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
400
	print STDERR "ArchiveAdd: ".
401 402 403 404
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
    if (! -d $directory || ! -w $directory) {
405
	print STDERR "ArchiveAdd: $directory cannot be written!\n";
406 407
	return -1;
    }
408
    my $repodir   = "$directory/repo";
409
    my $checkin   = "$directory/checkins/$view";
410 411
    
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
412 413 414 415
    # 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). 
416
    #
417 418 419 420
    if (! -e "$checkin/$rootdir") {
	mysystem("$MKDIR $checkin/$rootdir") == 0 or return -1;
    }
    
421 422
    if (-f "/${sourcedir}/${sourcefile}" || !$exact) {
	mysystem("$TAR cf - -C /$sourcedir $sourcefile | ".
423
		 "$TAR xf - -U -C $checkin/$rootdir");
424
	mysystem("$CHMOD 775 $checkin/$rootdir/$sourcefile");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
425 426
    }
    else {
427 428 429
	mysystem("cd /$sourcedir; ".
		 "$RSYNC $rsyncopt -rtgoDlz ".
		 "  --delete ${sourcefile} $checkin/$rootdir");
430 431
    }
    if ($?) {
432
	print STDERR "ArchiveAdd: Could not copy in $pathname\n";
433 434 435 436 437 438
	return -1;
    }
    return 0;
}

#
439 440 441 442 443
# 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.
444
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
445
sub ArchiveSavePoint($;$$$)
446
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
447
    my ($archive_idx, $savetag, $view, $altdir) = @_;
448 449 450 451 452 453 454 455
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
456 457 458 459 460 461

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
462
	print STDERR "ArchiveSavePoint: ".
463
	    "Archive '$archive_idx' does not exist in the DB!\n";
464
	goto bad;
465 466
    }
    if (! -d $directory || ! -w $directory) {
467
	print STDERR "ArchiveSavePoint: $directory cannot be written!\n";
468
	goto bad;
469
    }
470
    my $repodir   = "$directory/repo";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
471
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
472 473 474 475 476 477

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

484
    # Get the current tag for the archive.
485 486
    my ($archive_tag);
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag) < 0) {
487 488 489 490 491 492 493 494 495 496 497 498 499 500
	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";
    }

501
    # Tags must start with a letter.
502 503 504 505
    if ($savetag =~ /^\d+/) {
	$savetag = "T" . $savetag;
    }
    
506
    #
507
    # Use svn import command. This is nice cause it handles all the
508 509 510
    # subdirs and stuff in one shot, instead of trying to deal with
    # each file and directory individually.
    #
511 512 513 514
    if (! chdir("$checkin")) {
	print STDERR "ArchiveSavePoint: Cannot chdir to $checkin!\n";
	goto bad;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
515 516 517
    # Avoid a core file from svn.
    mysystem("ulimit -c 0; $IMPORTER -no_user_input file://$repodir ".
	     "                 $view/savepoint . " .
518
	     ($debug < 2 ? "> /dev/null 2>&1" : ""))
519 520 521 522 523
	== 0 or goto bad;

    #
    # Create the tag for this savepoint. 
    # 
524
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
525 526 527 528
	     "          file://$repodir/$view/savepoint ".
	     "          file://$repodir/$view/tags/${savetag}")
	== 0 or goto bad;
    
529 530 531 532

    #
    # And record the new tag. 
    # 
533
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
534
		"  tag='$savetag', view='$view', ".
535
		"  archive_idx='$archive_idx', ".
536
		"  tagtype='$TAGTYPE_SAVEPOINT', ".
537
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
538

539
  okay:
540 541 542
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
543 544 545
    return 0;

  bad:
546 547 548
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
549 550 551 552 553 554 555
    return -1;
}

#
# Commit the current contents of the temporary store to the archive.
# Returns -1 if any error. Otherwise return 0.
#
556
sub ArchiveCommit($;$$$$)
557
{
558
    my ($archive_idx, $newtag, $mfile, $view, $altdir) = @_;
559
    my $noactivity = 0;
560 561 562 563 564 565 566 567
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
568 569 570 571 572 573 574 575

    #
    # 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";
576
	goto bad;
577 578 579
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCommit: $directory cannot be written!\n";
580
	goto bad;
581
    }
582
    my $repodir   = "$directory/repo";
583 584
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
585 586 587 588 589 590 591 592

    # 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
593
	print STDERR "ArchiveCommit: Bad data in $cwd!\n";
594
	goto bad;
595 596
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
597 598
    if (! chdir("$directory")) {
	print STDERR "ArchiveCommit: Cannot chdir to $directory!\n";
599
	goto bad;
600 601 602
    }

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

    #
612 613
    # Form new tag.
    # 
614 615 616
    my ($seconds, $microseconds) = gettimeofday();
    my $import_tag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $import_tag    .= $microseconds;
617 618

    if (!defined($newtag)) {
619
	$newtag = $import_tag . "_commit";
620 621
    }

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

627 628 629 630 631 632 633
    #
    # 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 ".
634
		    "where archive_idx='$archive_idx' and view='$view' ".
635 636 637 638 639 640 641 642 643
		    "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;
    }
644 645 646 647 648 649 650 651 652 653 654 655 656

    #
    # Message can come from a file. 
    #
    my $message_arg = "-m 'Commit merge of ${archive_tag} to trunk'";

    if (defined($mfile)) {
	if (! -r $mfile) {
	    print STDERR "*** ArchiveCommit: $mfile cannot be read!\n";
	    goto bad;
	}
	$message_arg = "-F $mfile";
    }
657
    
658
    #
659 660 661
    # Okay, do the commit to the trunk for this view.
    # 
    if (! $noactivity) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
662 663 664 665 666 667 668 669 670
	#
	# Create a temporary spot to work in.
	# 
	if (! mkdir("merge.$$", 0777)) {
	    print STDERR "ArchiveCommit: Could not mkdir merge.$$: $!\n";
	    goto bad;
	}
	chdir("merge.$$");
	
671
	#
672
	# Check out the current trunk.
673
	#
674 675 676
	mysystem("$SVN checkout $svnopt file://$repodir/$view/trunk")
	    == 0 or goto bad;

677
	#
678 679 680 681 682 683 684 685 686 687
	# 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;
688

689
	mysystem("$SVN commit $svnopt $message_arg trunk")
690
	    == 0 or goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
691 692 693 694 695 696 697

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

700
    # Create a tag in the tags directory for the commit.
701
    mysystem("$SVN copy $svnopt $message_arg ".
702 703 704 705
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${newtag}")
	== 0 or goto bad;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
706 707 708
    # 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.
709
    mysystem("$SVN copy $svnopt $message_arg ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
710 711 712 713
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/history/${newtag}")
	== 0 or goto bad;
    
714
    # Create a branch tag in the tags directory to base differences against.
715
    mysystem("$SVN copy $svnopt -m 'ArchiveCommit Branch' ".
716 717 718
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${newtag}-branch")
	== 0 or goto bad;
719 720 721 722

    # For putting message into DB.
    my $dclause = (defined($mfile) ? 
		   ", description=" . DBQuoteSpecial(`cat $mfile`) : "");
723
    
724
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
725
		"  tag='$newtag', view='$view', ".
726
		"  archive_idx='$archive_idx', ".
727 728
		"  tagtype='$TAGTYPE_COMMIT', ".
		"  date_created=UNIX_TIMESTAMP(now()) $dclause")
729
	or goto bad;
730

731
    DBQueryWarn("update archive_views set ".
732
		"  current_tag='$newtag', ".
733
		"  previous_tag='$archive_tag' ".
734 735
		"where archive_idx='$archive_idx' and view='$view'")
	or goto bad;
736

737 738 739
    # And now into the checkout dir to checkout a current copy.
    if (! chdir("$checkout")) {
	print STDERR "ArchiveCommit: Cannot chdir to $checkout!\n";
740
	goto bad;
741
    }
742
    mysystem("$SVN $svnopt update trunk");
743
    if ($?) {
744
	print STDERR "ArchiveCommit: Could not update head revision!\n";
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
	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.
#
765
sub ArchiveFork($$;$$$)
766
{
767 768
    my ($archive_idx, $newview, $branchtag, $newtag, $view) = @_;
    my $sourcepoint;
769 770 771 772 773 774 775 776 777 778 779 780 781 782
    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) {
783
	print STDERR "ArchiveFork: ".
784 785 786 787
	    "Archive '$archive_idx' does not exist in the DB!\n";
	goto bad;
    }
    if (! -d $directory || ! -w $directory) {
788
	print STDERR "ArchiveFork: $directory cannot be written!\n";
789
	goto bad;
790
    }
791
    my $repodir     = "$directory/repo";
792 793 794 795 796 797 798 799 800 801 802 803 804
    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
805
	print STDERR "ArchiveFork: Bad data in $cwd!\n";
806 807 808 809
	goto bad;
    }

    # Get the current tags for the archive.
810
    my ($archive_tag, $previous_tag);
811
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag,
812
			      \$previous_tag) < 0) {
813
	print STDERR "ArchiveFork: ".
814 815 816 817
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    #
    # 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;
    }

834 835
    # Create new view directories and checkout.
    if (! mkdir("$newcheckin", 0777)) {
836
	print STDERR "ArchiveFork: Could not mkdir $newcheckin: $!\n";
837 838 839
	goto bad;
    }
    if (! chmod(0777, "$newcheckin")) {
840
	print STDERR "ArchiveFork: Could not chmod $newcheckin: $!\n";
841 842
	goto bad;
    }
843 844

    # Create newview directory in the repo.
845
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
846 847 848
	     "          file://$repodir/$newview")
	== 0 or goto bad;

849 850 851 852 853 854 855 856 857 858 859 860
    #
    # If no branchtag supplied, we want to branch at the trunk. But we still
    # need to mark it with a tag or else we have no idea later what actually
    # happened.
    #
    if (!defined($branchtag)) {
	$branchtag = $import_tag . "_fork";

	mysystem("$SVN copy $svnopt -m 'ArchiveFork' ".
		 "          file://$repodir/$view/trunk ".
		 "          file://$repodir/$view/tags/$branchtag")
	    == 0 or goto bad;
861
    }
862
    $sourcepoint = "tags/$branchtag";
863 864 865 866 867 868 869

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

870 871 872 873 874 875 876
    # Ditto for the savepoints directory. 
    mysystem("$SVN copy $svnopt -m 'ArchiveFork' ".
	     "          file://$repodir/$view/savepoint ".
	     "          file://$repodir/$newview/savepoint")
	== 0 or goto bad;

    # Do not want to copy the tags/history directories. Add new ones.
877
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
878
	     "          file://$repodir/$newview/history ".
879 880 881
	     "          file://$repodir/$newview/tags")
	== 0 or goto bad;

882 883 884 885 886
    # Create a branch tag in the tags directory to base differences against.
    mysystem("$SVN copy $svnopt -m 'ArchiveFork Branch' ".
	     "          file://$repodir/$newview/trunk ".
	     "          file://$repodir/$newview/tags/${newtag}-branch")
	== 0 or goto bad;
887 888 889 890 891 892 893 894

    # 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.
    mysystem("$SVN copy $svnopt -m 'ArchiveFork Branch' ".
	     "          file://$repodir/$newview/trunk ".
	     "          file://$repodir/$newview/history/${newtag}")
	== 0 or goto bad;
895
    
896
    # Now check it out. This creates the checkouts/$newview directory.
897
    mysystem("cd $checkouts; ".
898
	     "$SVN checkout $svnopt file://$repodir/$newview")
899 900
	== 0 or goto bad;

901 902 903 904
    # Now enter the newview (okay, branch) of this archive.
    DBQueryWarn("insert into archive_views set ".
		"  current_tag='$newtag', archive_idx='$archive_idx', ".
		"  view='$newview', ".
905
		"  parent_view='$view', branch_tag='$branchtag', ".
906
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
907
    
908 909 910
    # 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', ".
911
		"  tagtype='$TAGTYPE_INTERNAL', ".
912
		"  view='$newview', ".
913
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
914

915
  okay:
916 917 918
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
919
    return 0;
920 921

  bad:
922 923 924
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
925
    return -1;
926 927
}

928 929 930
#
# Checkout a copy of the archive, optionally at a particular view/branch.
#
931
sub ArchiveCheckout($$;$$$)
932
{
933
    my ($archive_idx, $target, $view, $tag, $subdir) = @_;
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 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 986 987 988 989 990 991
    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"
    }
992 993 994
    # Allowed to check out a particular subdir (but not a file).
    $sourcepoint = $sourcepoint . "/$subdir"
	if (defined($subdir));
995

996
    # Now check it out, although we actually use export to avoid .svn files.
997
    mysystem("cd $target; ".
998 999
	     "$SVN export $svnopt ".
	     "    --force file://$repodir/$view/$sourcepoint .")
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
	== 0 or goto bad;
  okay:
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
    return 0;

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

1014 1015 1016 1017 1018
#
# 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.
#
1019
sub ArchiveArchive($)
1020
{
1021 1022
    my ($archive_idx) = @_;
    my $target = "$ARCHIVEDIR/Archive/$archive_idx";
1023 1024 1025 1026 1027 1028

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
1029
	print STDERR "ArchiveArchive: ".
1030 1031 1032
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

    #
    # Need additional check to make sure that it has not already been
    # archived.
    #
    my ($archived, $date_archived);