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

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

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

69 70 71 72 73 74 75 76 77 78 79
# On or off
sub doarchiving($)
{
    my ($pid) = @_;
    
    return 1
	if ($USEARCHIVE && exists($ALLOWEDPID{$pid}));
    
    return 0;
}

80 81 82 83 84
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
85 86
    TBDebugTimeStampsOn();    

87 88 89 90
    # Need a big TMPDIR for svn stuff.
    my $tmpdir = $ENV{'TMPDIR'};
    $ENV{'TMPDIR'} = "/usr/testbed/tmp";

91 92
    print STDERR "Running '$command'\n"
	if ($debug);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
93 94

    TBDebugTimeStamp($command);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
95
    my $retval = system($command);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
96
    TBDebugTimeStamp("Done");
97 98
    $ENV{'TMPDIR'} = $tmpdir
	if (defined($tmpdir));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
99 100

    return $retval;
101 102
}

103 104 105 106 107 108
# Another little helper for scripts that include this library.
sub setdebug($)
{
    my ($toggle) = @_;

    if ($toggle) {
109
	$debug  = $toggle;
110 111 112 113 114 115 116 117
	$svnopt = "";
    }
    else {
	$debug  = 0;
	$svnopt = "-q";
    }
}

118 119 120 121
#
# Create a new archive. Returns -1 if any error. Otherwise return
# the new record index.
# 
122
sub ArchiveCreate(;$$$)
123
{
124
    my ($tag, $view, $unix_gid) = @_;
125
    
126 127
    my $idx;
    my $dir;
128 129 130

    $tag = $inittag
	if (!defined($tag));
131 132
    $view = $defaultview
	if (!defined($view));
133

134
    # Tags cannot must start with a letter.
135 136 137
    if ($tag =~ /^\d+/) {
	$tag = "T" . $tag;
    }
138 139 140 141 142

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
163
    DBQueryWarn("update archives set directory='$dir' where idx='$idx'")
164 165 166
	or goto bad;

    #
167
    # Make subdirs. One to hold the control tree, and the other
168 169
    # to hold currently checked out versions of the tree. Lastly, we
    # need a place to copyin files before they are added to the repo.
170
    #
171
    my $repodir   = "$dir/repo";
172 173
    my $checkouts = "$dir/checkouts";
    my $checkins  = "$dir/checkins";
174

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

    # Create a branch tag in the tags directory to base differences against.
220
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
221 222
	     "          file://$repodir/$view/trunk ".
	     "          file://$repodir/$view/tags/${tag}-branch")
223
	== 0 or goto bad;
224 225 226 227 228 229 230 231

    # 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;
232
    
233 234
    # Now check it out. This creates the $checkouts/$view directory.
    mysystem("cd $checkouts; ".
235
	     "$SVN checkout $svnopt file://$repodir/$view")
236 237
	== 0 or goto bad;

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

  bad:
#    mysystem("$RM -rf $dir")
#        if (defined($dir));
254 255 256
    DBQueryFatal("delete from archive_views ".
		 "where view='$view' and archive_idx='$idx'")
	if (defined($idx));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
257
    DBQueryFatal("delete from archives where idx='$idx'")
258 259 260 261 262
	if (defined($idx));
    return -1;
}

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

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

281
    if (! -e $pathname || ! -r $pathname) {
282 283
	print STDERR "*** ValidatePath: $pathname cannot be read!\n";
	return 1;
284 285 286
    }

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

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

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

324 325 326 327 328 329 330 331 332 333
    $$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. 
#
334
sub ArchiveAdd($$;$$$)
335
{
336
    my ($archive_idx, $pathname, $view, $exact, $special) = @_;
337 338 339 340 341 342 343

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

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

344 345 346
    $special = 0
	if (!defined($special));

347 348 349 350 351 352 353 354 355
    # 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.
    #
356 357 358 359 360
    my ($rootdir, $sourcedir, $sourcefile);
    my $rsyncopt = "";
    
    if ($special) {
	#
361 362 363 364 365 366
	# 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.
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
	#
	if (! -d $pathname) {
	    print STDERR "ArchiveAdd: Must be a direcotory: $pathname\n";
	    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";
383 384 385 386 387 388
    }
    else {
	print STDERR "ArchiveAdd: Illegal characters in pathname $pathname\n";
	return -1;
    }

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

#
433 434 435 436 437
# 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.
438
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
439
sub ArchiveSavePoint($;$$$)
440
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
441
    my ($archive_idx, $savetag, $view, $altdir) = @_;
442 443 444 445 446 447 448 449
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
450 451 452 453 454 455

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

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

478
    # Get the current tag for the archive.
479 480
    my ($archive_tag);
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag) < 0) {
481 482 483 484 485 486 487 488 489 490 491 492 493 494
	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";
    }

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

    #
    # Create the tag for this savepoint. 
    # 
518
    mysystem("$SVN copy $svnopt -m 'ArchiveCreate Branch' ".
519 520 521 522
	     "          file://$repodir/$view/savepoint ".
	     "          file://$repodir/$view/tags/${savetag}")
	== 0 or goto bad;
    
523 524 525 526

    #
    # And record the new tag. 
    # 
527
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
528
		"  tag='$savetag', view='$view', ".
529
		"  archive_idx='$archive_idx', ".
530
		"  tagtype='$TAGTYPE_SAVEPOINT', ".
531
		"  date_created=UNIX_TIMESTAMP(now())") or goto bad;
532

533
  okay:
534 535 536
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
537 538 539
    return 0;

  bad:
540 541 542
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
543 544 545 546 547 548 549
    return -1;
}

#
# Commit the current contents of the temporary store to the archive.
# Returns -1 if any error. Otherwise return 0.
#
550
sub ArchiveCommit($;$$$$)
551
{
552
    my ($archive_idx, $newtag, $mfile, $view, $altdir) = @_;
553
    my $noactivity = 0;
554 555 556 557 558 559 560 561
    my $cwd;

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

    return -1
	if (TBScriptLock("archive_${archive_idx}", 0, 120) !=
	    TBSCRIPTLOCK_OKAY());
562 563 564 565 566 567 568 569

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

    # 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
587
	print STDERR "ArchiveCommit: Bad data in $cwd!\n";
588
	goto bad;
589 590
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
591 592
    if (! chdir("$directory")) {
	print STDERR "ArchiveCommit: Cannot chdir to $directory!\n";
593
	goto bad;
594 595 596
    }

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

    #
606 607
    # Form new tag.
    # 
608 609 610
    my ($seconds, $microseconds) = gettimeofday();
    my $import_tag  = POSIX::strftime("T20%y%m%d-%H%M%S-", localtime());
    $import_tag    .= $microseconds;
611 612

    if (!defined($newtag)) {
613
	$newtag = $import_tag . "_commit";
614 615
    }

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

621 622 623 624 625 626 627
    #
    # 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 ".
628
		    "where archive_idx='$archive_idx' and view='$view' ".
629 630 631 632 633 634 635 636 637
		    "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;
    }
638 639 640 641 642 643 644 645 646 647 648 649 650

    #
    # 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";
    }
651
    
652
    #
653 654 655
    # Okay, do the commit to the trunk for this view.
    # 
    if (! $noactivity) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
656 657 658 659 660 661 662 663 664
	#
	# Create a temporary spot to work in.
	# 
	if (! mkdir("merge.$$", 0777)) {
	    print STDERR "ArchiveCommit: Could not mkdir merge.$$: $!\n";
	    goto bad;
	}
	chdir("merge.$$");
	
665
	#
666
	# Check out the current trunk.
667
	#
668 669 670
	mysystem("$SVN checkout $svnopt file://$repodir/$view/trunk")
	    == 0 or goto bad;

671
	#
672 673 674 675 676 677 678 679 680 681
	# 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;
682

683
	mysystem("$SVN commit $svnopt $message_arg trunk")
684
	    == 0 or goto bad;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
685 686 687 688 689 690 691

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

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

    # For putting message into DB.
    my $dclause = (defined($mfile) ? 
		   ", description=" . DBQuoteSpecial(`cat $mfile`) : "");
717
    
718
    DBQueryWarn("insert into archive_tags set idx=NULL, ".
719
		"  tag='$newtag', view='$view', ".
720
		"  archive_idx='$archive_idx', ".
721 722
		"  tagtype='$TAGTYPE_COMMIT', ".
		"  date_created=UNIX_TIMESTAMP(now()) $dclause")
723
	or goto bad;
724

725
    DBQueryWarn("update archive_views set ".
726
		"  current_tag='$newtag', ".
727
		"  previous_tag='$archive_tag' ".
728 729
		"where archive_idx='$archive_idx' and view='$view'")
	or goto bad;
730

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

    # Get the current tags for the archive.
804
    my ($archive_tag, $previous_tag);
805
    if (GetArchiveCurrentTags($archive_idx, $view, \$archive_tag,
806
			      \$previous_tag) < 0) {
807
	print STDERR "ArchiveFork: ".
808 809 810 811
	    "Archive '$archive_idx' does not have a current tag!\n";
	goto bad;
    }

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    #
    # 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;
    }

828 829
    # Create new view directories and checkout.
    if (! mkdir("$newcheckin", 0777)) {
830
	print STDERR "ArchiveFork: Could not mkdir $newcheckin: $!\n";
831 832 833
	goto bad;
    }
    if (! chmod(0777, "$newcheckin")) {
834
	print STDERR "ArchiveFork: Could not chmod $newcheckin: $!\n";
835 836
	goto bad;
    }
837 838

    # Create newview directory in the repo.
839
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
840 841 842
	     "          file://$repodir/$newview")
	== 0 or goto bad;

843 844 845 846 847 848 849 850 851 852 853 854
    #
    # 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;
855
    }
856
    $sourcepoint = "tags/$branchtag";
857 858 859 860 861 862 863

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

864 865 866 867 868 869 870
    # 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.
871
    mysystem("$SVN mkdir $svnopt -m 'ArchiveFork' ".
872
	     "          file://$repodir/$newview/history ".
873 874 875
	     "          file://$repodir/$newview/tags")
	== 0 or goto bad;

876 877 878 879 880
    # 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;
881 882 883 884 885 886 887 888

    # 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;
889
    
890
    # Now check it out. This creates the checkouts/$newview directory.
891
    mysystem("cd $checkouts; ".
892
	     "$SVN checkout $svnopt file://$repodir/$newview")
893 894
	== 0 or goto bad;

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

909
  okay:
910 911 912
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
913
    return 0;
914 915

  bad:
916 917 918
    TBScriptUnlock();
    chdir($cwd)
	if (defined($cwd));
919
    return -1;
920 921
}

922 923 924
#
# Checkout a copy of the archive, optionally at a particular view/branch.
#
925
sub ArchiveCheckout($$;$$$)
926
{
927
    my ($archive_idx, $target, $view, $tag, $subdir) = @_;
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 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
    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"
    }
986 987 988
    # Allowed to check out a particular subdir (but not a file).
    $sourcepoint = $sourcepoint . "/$subdir"
	if (defined($subdir));
989

990
    # Now check it out, although we actually use export to avoid .svn files.
991
    mysystem("cd $target; ".
992 993
	     "$SVN export $svnopt ".
	     "    --force file://$repodir/$view/$sourcepoint .")
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	== 0 or goto bad;
  okay