libArchive.pm.in 52.9 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 31
my $MAINSITE    = @TBMAINSITE@;
my $ALLOWEDPID  = "testbed";
32 33 34 35 36 37 38 39
# 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";
40
my $CHGRP       = "/usr/bin/chgrp";
41
my $TAR		= "/usr/bin/tar";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
42
my $RSYNC	= "/usr/local/bin/rsync";
43
my $RM		= "/bin/rm";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
44
my $REALPATH	= "/bin/realpath";
45 46 47
my $SVN         = "/usr/local/bin/svn";
my $SVNADMIN    = "/usr/local/bin/svnadmin";
my $IMPORTER    = "$TB/sbin/svn_load_dirs.pl";
48
my $inittag     = 'root';
49
my $defaultview = 'head';
50
my $debug       = 0;
51
my $svnopt      = ($debug ? "" : "-q");
52 53 54 55
my %ROOTS       = ("proj"   => "proj",
		   "users"  => "users",
		   "share"  => "share",
		   "groups" => "groups");
56

57 58 59 60 61
my $TAGTYPE_USER      = "user";
my $TAGTYPE_COMMIT    = "commit";
my $TAGTYPE_SAVEPOINT = "savepoint";
my $TAGTYPE_INTERNAL  = "internal";

62 63 64 65 66
#
# Set umask so that other people in the project can mess with the archive.
#
umask(0002);

67 68 69 70 71 72 73 74 75 76
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

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

77 78 79 80 81 82
# Another little helper for scripts that include this library.
sub setdebug($)
{
    my ($toggle) = @_;

    if ($toggle) {
83
	$debug  = $toggle;
84 85 86 87 88 89 90 91
	$svnopt = "";
    }
    else {
	$debug  = 0;
	$svnopt = "-q";
    }
}

92 93 94 95
#
# Create a new archive. Returns -1 if any error. Otherwise return
# the new record index.
# 
96
sub ArchiveCreate(;$$$)
97
{
98
    my ($tag, $view, $unix_gid) = @_;
99
    
100 101
    my $idx;
    my $dir;
102 103 104

    $tag = $inittag
	if (!defined($tag));
105 106
    $view = $defaultview
	if (!defined($view));
107

108
    # Tags cannot must start with a letter.
109 110 111
    if ($tag =~ /^\d+/) {
	$tag = "T" . $tag;
    }
112 113 114 115 116

    #
    # Need to create the directory for it, once we have the index.
    # 
    my $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
117
	DBQueryWarn("insert into archives set ".
118
		    "  idx=NULL, ".
119 120 121 122 123 124 125 126 127 128 129 130 131 132
		    "  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;
133 134 135
    if (defined($unix_gid)) {
	mysystem("$CHGRP $unix_gid $dir") == 0 or goto bad;
    }
136

Leigh B. Stoller's avatar
Leigh B. Stoller committed
137
    DBQueryWarn("update archives set directory='$dir' where idx='$idx'")
138 139 140
	or goto bad;

    #
141
    # Make subdirs. One to hold the control tree, and the other
142 143
    # to hold currently checked out versions of the tree. Lastly, we
    # need a place to copyin files before they are added to the repo.
144
    #
145
    my $repodir   = "$dir/repo";
146 147
    my $checkouts = "$dir/checkouts";
    my $checkins  = "$dir/checkins";
148

149 150
    if (! mkdir("$repodir", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $repodir: $!\n";
151 152
	goto bad;
    }
153 154
    if (! chmod(0777, "$repodir")) {
	print STDERR "ArchiveCreate: Could not chmod $repodir: $!\n";
155 156
	goto bad;
    }
157 158
    if (! mkdir("$checkouts", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkouts: $!\n";
159 160
	goto bad;
    }
161 162
    if (! chmod(0777, "$checkouts")) {
	print STDERR "ArchiveCreate: Could not chmod $checkouts: $!\n";
163 164
	goto bad;
    }
165 166
    if (! mkdir("$checkins", 0777)) {
	print STDERR "ArchiveCreate: Could not mkdir $checkins: $!\n";
167 168
	goto bad;
    }
169 170 171 172 173 174 175 176 177 178
    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";
179 180
	goto bad;
    }
181 182
    # Initialize the repo.
    mysystem("$SVNADMIN create $repodir") == 0
183
	or goto bad;
184 185 186 187
    
    # 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
188
	     "         mkdir $view/history; ".
Timothy Stack's avatar
Timothy Stack committed
189
	     "$SVN import $svnopt -m 'ArchiveCreate' ".
190
	     "     $view file://$repodir/$view")
191 192 193
	== 0 or goto bad;

    # Create a branch tag in the tags directory to base differences against.
194
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
195 196
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${tag}-branch")
197
	== 0 or goto bad;
198
    
199 200
    # Now check it out. This creates the $checkouts/$view directory.
    mysystem("cd $checkouts; ".
201
	     "$SVN checkout $svnopt file://$repodir/$view")
202 203
	== 0 or goto bad;

204 205 206 207 208
    # 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;
    
209
    # Now enter an initial tag for the tree. Nothing actually gets tagged.
210 211
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
		"  tag='$tag', archive_idx='$idx', view='$view', ".
212
		"  tagtype='$TAGTYPE_INTERNAL', ".
213 214 215 216 217 218 219
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
    
    return $idx;

  bad:
#    mysystem("$RM -rf $dir")
#        if (defined($dir));
220 221 222
    DBQueryFatal("delete from archive_views ".
		 "where view='$view' and archive_idx='$idx'")
	if (defined($idx));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
223
    DBQueryFatal("delete from archives where idx='$idx'")
224 225 226 227 228
	if (defined($idx));
    return -1;
}

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

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

247
    if (! -e $pathname || ! -r $pathname) {
248 249
	print STDERR "*** ValidatePath: $pathname cannot be read!\n";
	return 1;
250 251 252
    }

    #
253 254
    # Use realpath to check that the path does not contain links to
    # files outside the directory space the user is allowed to access.
255
    # We must taint check the result to keep everyone happy.
256
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
257
    my $realpath = `$REALPATH $pathname`;
258
    if ($realpath =~ /^([-\w\/\.\+\@,~]+)$/) {
259 260 261
	$realpath = $1;
    }
    else {
262
	print STDERR "*** ValidatePath: ".
263
	    "Bad data returned by realpath: $realpath\n";
264
	return -1;
265
    }
266

267
    #
268 269
    # Strip leading /dir from the pathname. We want a relative path to
    # the rootdir so we can copy it in.
270
    #
271
    if ($realpath =~ /^[\/]+(\w+)\/(.+)$/) {
272 273
	$rootdir  = $1;
	$pathname = $2;
274 275
    }
    else {
276 277
	print STDERR "*** ValidatePath: ".
	    "Illegal characters in pathname: $realpath\n";
278 279 280 281 282 283 284
	return -1;
    }

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

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
    $$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 ArchiveAdd($$;$$)
{
    my ($archive_idx, $pathname, $view, $exact) = @_;
    my $rootdir;

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

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

    # 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.
    #
    if ($pathname =~ /^[\/]+(\w+)\/([-\w\/\.\+\@,~]+)$/) {
	$rootdir  = $1;
	$pathname = $2;
    }
    else {
	print STDERR "ArchiveAdd: Illegal characters in pathname $pathname\n";
	return -1;
    }

329 330 331 332 333
    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
334
	print STDERR "ArchiveAdd: ".
335 336 337 338
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
    if (! -d $directory || ! -w $directory) {
339
	print STDERR "ArchiveAdd: $directory cannot be written!\n";
340 341
	return -1;
    }
342
    my $repodir   = "$directory/repo";
343 344
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = "$directory/checkins/$view";
345 346
    
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
347 348 349 350
    # 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). 
351
    #
352 353 354 355 356 357
    if (! -e "$checkin/$rootdir") {
	mysystem("$MKDIR $checkin/$rootdir") == 0 or return -1;
    }
    
    if (-f "/${rootdir}/${pathname}" || !$exact) {
	mysystem("$TAR cf - -C /$rootdir $pathname | ".
358 359
		 "$TAR xf - -U -C $checkin/$rootdir");
	mysystem("$CHMOD 775 $checkin/$rootdir/$pathname");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
360 361
    }
    else {
362
	mysystem("cd /$rootdir; ".
363
		 "$RSYNC -R -rtgoDlz --delete ${pathname} $checkin/$rootdir");
364 365
    }
    if ($?) {
366
	print STDERR "ArchiveAdd: Could not copy in /$rootdir/$pathname\n";
367 368 369 370 371 372
	return -1;
    }
    return 0;
}

#
373 374 375 376 377
# 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.
378
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
379
sub ArchiveSavePoint($;$$$)
380
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
381
    my ($archive_idx, $savetag, $view, $altdir) = @_;
382 383 384 385 386 387 388 389
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
390 391 392 393 394 395

    #
    # See if the archive exists and if it does, get the pathname to it.
    #
    my $directory;
    if (GetArchiveDirectory($archive_idx, \$directory) < 0) {
396
	print STDERR "ArchiveSavePoint: ".
397
	    "Archive '$archive_idx' does not exist in the DB!\n";
398
	goto bad;
399 400
    }
    if (! -d $directory || ! -w $directory) {
401
	print STDERR "ArchiveSavePoint: $directory cannot be written!\n";
402
	goto bad;
403
    }
404
    my $repodir   = "$directory/repo";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
405
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
406 407 408 409 410 411

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

418
    # Get the current tag for the archive.
419 420
    my ($archive_tag);
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag) < 0) {
421 422 423 424 425 426 427 428 429 430 431 432 433 434
	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";
    }

435
    # Tags must start with a letter.
436 437 438 439
    if ($savetag =~ /^\d+/) {
	$savetag = "T" . $savetag;
    }
    
440
    #
441
    # Use svn import command. This is nice cause it handles all the
442 443 444
    # subdirs and stuff in one shot, instead of trying to deal with
    # each file and directory individually.
    #
445 446 447 448
    if (! chdir("$checkin")) {
	print STDERR "ArchiveSavePoint: Cannot chdir to $checkin!\n";
	goto bad;
    }
449
    mysystem("$IMPORTER -no_user_input file://$repodir ".
450 451
	     "          $view/savepoint . " .
	     ($debug < 2 ? "> /dev/null" : ""))
452 453 454 455 456
	== 0 or goto bad;

    #
    # Create the tag for this savepoint. 
    # 
457
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
458 459 460 461
	     "          file://$repodir/$view/savepoint ".
	     "          file://$repodir/$view/tags/${savetag}")
	== 0 or goto bad;
    
462 463 464 465

    #
    # And record the new tag. 
    # 
466
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
467
		"  tag='$savetag', view='$view', ".
468
		"  archive_idx='$archive_idx', ".
469
		"  tagtype='$TAGTYPE_SAVEPOINT', ".
470
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
471

472
  okay:
473 474 475
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
476 477 478
    return 0;

  bad:
479 480 481
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
482 483 484 485 486 487 488
    return -1;
}

#
# Commit the current contents of the temporary store to the archive.
# Returns -1 if any error. Otherwise return 0.
#
489
sub ArchiveCommit($;$$$$)
490
{
491
    my ($archive_idx, $newtag, $mfile, $view, $altdir) = @_;
492
    my $noactivity = 0;
493 494 495 496 497 498 499 500
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
501 502 503 504 505 506 507 508

    #
    # 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";
509
	goto bad;
510 511 512
    }
    if (! -d $directory || ! -w $directory) {
	print STDERR "ArchiveCommit: $directory cannot be written!\n";
513
	goto bad;
514
    }
515
    my $repodir   = "$directory/repo";
516 517
    my $checkout  = "$directory/checkouts/$view";
    my $checkin   = (defined($altdir) ? $altdir : "$directory/checkins/$view");
518 519 520 521 522 523 524 525

    # 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
526
	print STDERR "ArchiveCommit: Bad data in $cwd!\n";
527
	goto bad;
528 529
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
530 531
    if (! chdir("$directory")) {
	print STDERR "ArchiveCommit: Cannot chdir to $directory!\n";
532
	goto bad;
533 534 535
    }

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

    #
545 546
    # Form new tag.
    # 
547 548 549
    my ($seconds, $microseconds) = gettimeofday();
    my $import_tag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $import_tag    .= $microseconds;
550 551

    if (!defined($newtag)) {
552
	$newtag = $import_tag . "_commit";
553 554
    }

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

560 561 562 563 564 565 566
    #
    # 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 ".
567
		    "where archive_idx='$archive_idx' and view='$view' ".
568 569 570 571 572 573 574 575 576
		    "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;
    }
577 578 579 580 581 582 583 584 585 586 587 588 589

    #
    # 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";
    }
590
    
591
    #
592 593 594
    # Okay, do the commit to the trunk for this view.
    # 
    if (! $noactivity) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
595 596 597 598 599 600 601 602 603
	#
	# Create a temporary spot to work in.
	# 
	if (! mkdir("merge.$$", 0777)) {
	    print STDERR "ArchiveCommit: Could not mkdir merge.$$: $!\n";
	    goto bad;
	}
	chdir("merge.$$");
	
604
	#
605
	# Check out the current trunk.
606
	#
607 608 609
	mysystem("$SVN checkout $svnopt file://$repodir/$view/trunk")
	    == 0 or goto bad;

610
	#
611 612 613 614 615 616 617 618 619 620
	# 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;
621

622
	mysystem("$SVN commit $svnopt $message_arg trunk")
623
	    == 0 or goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
624 625 626 627 628 629 630

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

633
    # Create a tag in the tags directory for the commit.
634
    mysystem("$SVN copy $svnopt $message_arg ".
635 636 637 638
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${newtag}")
	== 0 or goto bad;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
639 640 641
    # 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.
642
    mysystem("$SVN copy $svnopt $message_arg ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
643 644 645 646
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/history/${newtag}")
	== 0 or goto bad;
    
647
    # Create a branch tag in the tags directory to base differences against.
648
    mysystem("$SVN copy $svnopt -m 'ArchiveCommit Branch' ".
649 650 651
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${newtag}-branch")
	== 0 or goto bad;
652 653 654 655

    # For putting message into DB.
    my $dclause = (defined($mfile) ? 
		   ", description=" . DBQuoteSpecial(`cat $mfile`) : "");
656
    
657
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
658
		"  tag='$newtag', view='$view', ".
659
		"  archive_idx='$archive_idx', ".
660 661
		"  tagtype='$TAGTYPE_COMMIT', ".
		"  date_created=UNIX_TIMESTAMP(now()) $dclause")
662
	or goto bad;
663

664
    DBQueryWarn("update archive_views set ".
665
		"  current_tag='$newtag', ".
666
		"  previous_tag='$archive_tag' ".
667 668
		"where archive_idx='$archive_idx' and view='$view'")
	or goto bad;
669

670 671 672
    # And now into the checkout dir to checkout a current copy.
    if (! chdir("$checkout")) {
	print STDERR "ArchiveCommit: Cannot chdir to $checkout!\n";
673
	goto bad;
674
    }
675
    mysystem("$SVN $svnopt update trunk");
676
    if ($?) {
677
	print STDERR "ArchiveCommit: Could not update head revision!\n";
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
	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.
#
698
sub ArchiveFork($$;$$$)
699
{
700 701
    my ($archive_idx, $newview, $branchtag, $newtag, $view) = @_;
    my $sourcepoint;
702 703 704 705 706 707 708 709 710 711 712 713 714 715
    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) {
716
	print STDERR "ArchiveFork: ".
717 718 719 720
	    "Archive '$archive_idx' does not exist in the DB!\n";
	goto bad;
    }
    if (! -d $directory || ! -w $directory) {
721
	print STDERR "ArchiveFork: $directory cannot be written!\n";
722
	goto bad;
723
    }
724
    my $repodir     = "$directory/repo";
725 726 727 728 729 730 731 732 733 734 735 736 737
    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
738
	print STDERR "ArchiveFork: Bad data in $cwd!\n";
739 740 741 742
	goto bad;
    }

    # Get the current tags for the archive.
743
    my ($archive_tag, $previous_tag);
744
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag,
745
			      \$previous_tag) < 0) {
746
	print STDERR "ArchiveFork: ".
747 748 749 750
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    #
    # 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;
    }

767 768
    # Create new view directories and checkout.
    if (! mkdir("$newcheckin", 0777)) {
769
	print STDERR "ArchiveFork: Could not mkdir $newcheckin: $!\n";
770 771 772
	goto bad;
    }
    if (! chmod(0777, "$newcheckin")) {
773
	print STDERR "ArchiveFork: Could not chmod $newcheckin: $!\n";
774 775
	goto bad;
    }
776 777

    # Create newview directory in the repo.
778
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
779 780 781
	     "          file://$repodir/$newview")
	== 0 or goto bad;

782 783 784 785 786 787 788 789 790 791 792 793
    #
    # 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;
794
    }
795
    $sourcepoint = "tags/$branchtag";
796 797 798 799 800 801 802

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

803 804 805 806 807 808 809
    # 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.
810
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
811
	     "          file://$repodir/$newview/history ".
812 813 814
	     "          file://$repodir/$newview/tags")
	== 0 or goto bad;

815 816 817 818 819 820
    # 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;
    
821
    # Now check it out. This creates the checkouts/$newview directory.
822
    mysystem("cd $checkouts; ".
823
	     "$SVN checkout $svnopt file://$repodir/$newview")
824 825
	== 0 or goto bad;

826 827 828 829
    # Now enter the newview (okay, branch) of this archive.
    DBQueryWarn("insert into archive_views set ".
		"  current_tag='$newtag', archive_idx='$archive_idx', ".
		"  view='$newview', ".
830
		"  parent_view='$view', branch_tag='$branchtag', ".
831
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
832
    
833 834 835
    # 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', ".
836
		"  tagtype='$TAGTYPE_INTERNAL', ".
837
		"  view='$newview', ".
838
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
839

840
  okay:
841 842 843
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
844
    return 0;
845 846

  bad:
847 848 849
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
850
    return -1;
851 852
}

853 854 855
#
# Checkout a copy of the archive, optionally at a particular view/branch.
#
856
sub ArchiveCheckout($$;$$$)
857
{
858
    my ($archive_idx, $target, $view, $tag, $subdir) = @_;
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
    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"
    }
917 918 919
    # Allowed to check out a particular subdir (but not a file).
    $sourcepoint = $sourcepoint . "/$subdir"
	if (defined($subdir));
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

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

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

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
#
# 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) {
953
	print STDERR "ArchiveArchive: ".
954 955 956
	    "Archive '$archive_idx' does not exist in the DB!\n";
	return -1;
    }
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

    #
    # Need additional check to make sure that it has not already been
    # archived.
    #
    my ($archived, $date_archived);
    
    if (IsArchiveArchived($archive_idx, \$archived, \$date_archived) < 0) {
	return -1;
    }
    if ($archived) {
	print STDERR "ArchiveArchive: ".
	    "Archive '$archive_idx' already archived on $date_archived!\n";
	return 0;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
972 973 974 975 976 977 978 979 980 981 982

    # Is it shared? If so, certainly do not archive it!
    my $shared;
    if (IsArchiveShared($archive_idx, \$shared) < 0) {
	return -1;
    }
    if ($shared) {
	print STDERR "ArchiveArchive: ".
	    "Archive '$archive_idx' is shared; not archiving!\n";
	return 0;
    }
983
    
984
    if (! -d $directory || ! -w $directory) {
985
	print STDERR "ArchiveArchive: $directory cannot be written!\n";
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
	return -1;
    }

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

    #
    # Tar up the whole thing and move it across.
    #
1004
    mysystem("$TAR cf - -C $directory repo | tar xf - -C $target");
1005 1006 1007 1008
    if ($?) {
	print STDERR "ArchiveArchive: Could not copy in $directory\n";
	return -1;
    }
1009 1010 1011 1012

    #
    # Update its location in the DB, and remove the old directory.
    # 
1013 1014 1015 1016
    DBQueryWarn("update archives set ".
		"   directory='$target', ".
		"   archived=1, ".
		"   date_archived=UNIX_TIMESTAMP(now()) ".
1017 1018 1019 1020 1021 1022 1023 1024 1025
		"where idx='$archive_idx'")
	or return -1;
    
    mysystem("/bin/rm -rf $directory");
    if ($?) {
	print STDERR "ArchiveArchive: ".
	    "Could not remove contents of $directory!\n";
	return -1;
    }
1026 1027 1028 1029 1030 1031 1032
    return 0;
}

#
# Destroy an archive. The DB state is retained unless optional flag says
# to clean it.
#
1033
sub ArchiveDestroy($$;$)
1034
{
1035 1036 1037 1038
    my ($archive_idx, $clean, $view) = @_;

    $view = $defaultview
	if (!defined($view));
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

    #
    # 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;
    }
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

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

1069 1070 1071
    # Is it shared? If so, certainly do not delete it!
    my $shared;
    if (IsArchiveShared($archive_idx, \$shared) < 0) {
1072 1073
	return -1;
    }
1074

1075 1076 1077 1078 1079 1080 1081 1082
    if (! $shared) {
	mysystem("/bin/rm -rf $directory");
	if ($?) {
	    print STDERR "ArchiveDestroy: ".
		"Could not remove contents of $directory!\n";
	    return -1;
	}
    }
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    elsif ($clean) {
	my $checkout  = "$directory/checkouts/$view";
	my $checkin   = "$directory/checkins/$view";

	mysystem("/bin/rm -rf $checkout $checkin");
	if ($?) {
	    print STDERR "ArchiveDestroy: ".
		"Could not remove contents of $directory!\n";
	    return -1;
	}
    }
1094
    
1095
    if ($clean) {
1096
	(DBQueryWarn("delete from archive_tags ".