libinstall.pm.in 25.5 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2003-2019 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24
#
#
25 26
# A simple library for use in the installation scripts, to make them
# seem a little more legitimate, instead of the quick hacks they are.
27
#
Leigh Stoller's avatar
Leigh Stoller committed
28
use POSIX qw(strftime);
29
use Exporter;
30 31 32 33 34
use vars qw(@EXPORT $TOP_SRCDIR $TOP_OBJDIR 
	    $SQL_UPDATE_MAJOR_REVISION $INSTALL_UPDATE_MAJOR_REVISION 
	    $MAGIC_TESTBED_VERSION $MAGIC_TESTBED_START $MAGIC_TESTBED_END);

@EXPORT = qw($TOP_SRCDIR $TOP_OBJDIR
35
	     $SQL_UPDATE_MAJOR_REVISION $INSTALL_UPDATE_MAJOR_REVISION
36
	     $MAGIC_TESTBED_VERSION $MAGIC_TESTBED_START $MAGIC_TESTBED_END);
Leigh Stoller's avatar
Leigh Stoller committed
37

38 39 40 41 42
# Change these if the major numbers in sql/updates or install/updates
# are changed.
$SQL_UPDATE_MAJOR_REVISION	= 4;
$INSTALL_UPDATE_MAJOR_REVISION	= 5;

43 44 45
# Configure vars
$TOP_SRCDIR	= "@top_srcdir@";

46 47 48 49 50
#
# Make sure that output gets printed right away
#
$| = 1;

51
#
52
# Magic string that shows up in files already edited 
53
#
54 55 56
$MAGIC_TESTBED_VERSION = $INSTALL_UPDATE_MAJOR_REVISION + ".0";
$MAGIC_TESTBED_START   = "Added by Emulab - Version: ";
$MAGIC_TESTBED_END     = "End of Emulab added section";
57

58 59
sub MAGIC_TESTBED_START { $MAGIC_TESTBED_START . $MAGIC_TESTBED_VERSION; }
sub MAGIC_TESTBED_END   { $MAGIC_TESTBED_END; }
60

61
# Used by update-install to bump the version number.
62
sub SET_TESTBED_VERSION($)  { $MAGIC_TESTBED_VERSION = $_[0]; }
63

64 65 66 67
# Set by update-install.
my $impotent   = 0;
my $logfp;
sub SET_IMPOTENT_MODE($)	    { $impotent = 1; $logfp = $_[0]; };
68
sub IMPOTENT_MODE()		    { return $impotent; }
69
sub SET_LOG_OUTPUT($)		    { $logfp = $_[0]; };
70

71 72 73 74 75
#
# Some programs we may call
#
my $FETCH = "/usr/bin/fetch";

76 77 78 79 80 81 82 83
#
# Figure out which directory we live in, so that some stages can do thing
# relative to it.
#
$TOP_OBJDIR = `/usr/bin/dirname $0`;
chomp $TOP_OBJDIR;
$TOP_OBJDIR = "$TOP_OBJDIR/..";

84 85 86 87
# Real path to the source dir.
$TOP_SRCDIR = `realpath $TOP_SRCDIR`;
chomp $TOP_SRCDIR;

88 89 90 91 92 93 94
#
# Let's pretend perl's exception mechanism has a sane name for the function
# that raises an exception
#
sub throw(@) {
    die @_,"\n";
}
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
#
# Start a new installation phase
#
sub Phase($$$) {
    my ($name, $descr, $coderef) = @_;

    push @libinstall::phasestack, $name;
    push @libinstall::descrstack, $descr;
    
    #
    # Okay, this will probably earn me my own special circle in Perl Hell. Use
    # dynamic scoping to allow data to be passed inbetween indirectly recursive
    # calls of Phase(). hasSubPhase is used to determine if we were called
    # recursively in the eval(). skipped and nonSkipped let us figure out if
    # all child calls were skipped. But, we have to give this information to
    # our parent _after_ we declare our own. So, we use references. Damn!
    #
 
    $hasSubPhase++;
    my $firstSubPhase = ($hasSubPhase == 1);
    local $hasSubPhase = 0;
    
    my $parentNonSkipped = \$nonSkipped;
    my $parentSkipped = \$skipped;
    local $nonSkipped = 0;
    local $skipped = 0;
    
    local $depth = ($depth? $depth +1 : 1);
    my $isSubPhase = ($depth > 1);

    my $descrstring = "| " x ($depth -1) . $descr;
127
    if ($firstSubPhase) {
128
	print "\n";
129
	printf $logfp "\n"
130
	    if (defined($logfp));
131 132
    }
    printf "%-50s", $descrstring;
133
    printf $logfp "%-50s", $descrstring
134
	if (defined($logfp));
135 136 137 138 139 140

    #
    # Clear these, as we don't want to see the outputs of previous phases
    #
    @libinstall::lastExecOutput = ();
    $libinstall::lastCommand = undef;
141
    @libinstall::loglines = ();
142 143 144 145 146 147 148 149 150 151 152 153 154 155

    #
    # Cool! TWO levels of Perl Hell just for me!
    # We pretend we have real exceptions, here. The way this works, we _expect_
    # something to call die(), which is how you throw exceptions in perl. Neat,
    # huh? The three calls below (Phase?*()) are the ones that do this.
    #
    eval { &$coderef(); };

    #
    # Prepare for printing!
    #
    my $message = "";
    my $die = 0;
156
    my $stop = 0;
157
    if ($hasSubPhase) {
158
	print  "| " x ($depth -1) . "+-" . "--" x (24 - $depth) . "> ";
159 160
	print $logfp  "| " x ($depth -1) . "+-" . "--" x (24 - $depth) . "> "
	    if (defined($logfp));
161 162 163 164 165 166 167
    }

    #
    # Check the exception thrown by the eval()
    #
    SWITCH: for ($@) {
	(/^skip$/) && do {
168
	    print "[ Skipped ($libinstall::reason) ]\n";
169
	    print $logfp "[ Skipped ($libinstall::reason) ]\n"
170
		if (defined($logfp));
171 172 173 174 175 176 177 178 179 180
	    $$parentSkipped++;
	    $libinstall::phaseResults{$name} = $_;
	    last SWITCH;
	};

	(/^fail$/) && do {
	    print "[ Failed    ]\n";
	    $$parentNonSkipped++;
	    $libinstall::phaseResults{$name} = $_;
	    $die = 1;
181
	    $message = "$libinstall::reason";
182 183 184 185 186 187 188 189 190
	    if ($isSubPhase) {
		#
		# Propagate failure up the tree
		#
		PhaseFail($libinstall::reason);
	    }
	    last SWITCH;
	};

191 192 193
	(/^stop$/) && do {
	    print "[ Stopped    ]\n";
	    print $logfp "[ Stopped ($libinstall::reason) ]\n"
194
		if (defined($logfp));
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	    $$parentNonSkipped++;
	    $message = "$libinstall::reason";
	    if ($impotent) {
		$libinstall::phaseResults{$name} = "succeed";
	    }
	    else {
		$libinstall::phaseResults{$name} = $_;
		$stop = 1;
		if ($isSubPhase) {
		    #
		    # Propagate failure up the tree
		    #
		    PhaseStop($libinstall::reason);
		}
	    }
	    last SWITCH;
	};

213 214 215 216
	(undef || /^$/ || /^succeed$/) && do {
	    #
	    # If we're a parent, and all sub-phases got skipped, we did too
	    #
Leigh Stoller's avatar
Leigh Stoller committed
217 218
	    my $stamp = POSIX::strftime("%H:%M:%S", localtime());
	    
219
	    if ($hasSubPhase && $skipped && ($nonSkipped == 0)) {
Leigh Stoller's avatar
Leigh Stoller committed
220
		print "[ Skipped   ] ($stamp)\n";
221
		print $logfp "[ Skipped   ]\n"
222
		    if (defined($logfp));
223 224 225
		$libinstall::phaseResults{$name} = "skip";
		$$parentSkipped++;
	    } else {
226 227
		if (defined($logfp)) {
		    print $logfp "[ Succeeded ]\n";
228
		    
229 230 231 232 233
		    print $logfp 
			"> " . join("\n> ", @libinstall::loglines) . "\n"
			if (@libinstall::loglines);
		}
		if ($impotent) {
234 235 236 237 238
		    print "[ $libinstall::reason ]\n";
		}
		else {
		    print "[ Succeeded ] ($stamp)\n";
		}
239 240 241 242 243 244 245 246 247 248 249
		$$parentNonSkipped++;
		$libinstall::phaseResults{$name} = "succeed";
	    }
	    last SWITCH;
	};

	#
	# Default case - shouldn't get here, unless something called die with
	# the wrong value
	#
	print "[ ERROR     ]\n";
250 251
	print $logfp "[ ERROR     ]\n"
	    if (defined($logfp));
252 253 254 255 256 257 258 259 260 261 262 263
	$$parentNonSkipped++;
	$message = "Internal error - Bad exception:\n$_";
	$libinstall::phaseResults{$name} = "fail";
        $die = 1;
	if ($isSubPhase) {
	    #
	    # Propagate failure up the tree
	    #
	    PhaseFail($message);
	}
    }

264 265 266 267
    #
    # If we decided that we need to stop, do that now
    #
    if ($stop) {
268 269 270 271 272 273 274 275 276
	my $message =
	    "\n" .
	    "############################################################\n" .
	    "Installation stopped in phase $name. The reason is:\n" .
	    "$message\n" .
	    "############################################################\n";
	print $message;
	print $logfp $message
	    if (defined($logfp));
277 278 279
	exit -1;
    }

280 281 282 283
    #
    # If we decided that we need to die, do that now
    #
    if ($die) {
284 285 286 287 288
	my $message = 
	    "\n##### Installation failed in phase $name:\n" . "$message\n";
	print $message;
	print $logfp $message
	    if (defined($logfp));
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	PrintPhaseTrace();
	PrintLastOutput();
	print "Please send the above output to testbed-ops\@emulab.net\n";
	exit -1;
    }

    #
    # Pop ourselves off the phase stack!
    #
    pop @libinstall::phasestack;
    pop @libinstall::descrstack;

}

#
# Signal that the current phase has suceeded
#
sub PhaseSucceed(;$) {
    ($libinstall::reason) = (@_);
    if (!$libinstall::reason) {
	$libinstall::reason = "succeeded";
    }
    throw "succeed";
}

#
# Signal that the current phase has failed
#
sub PhaseFail($) {
    ($libinstall::reason) = (@_);
    throw "fail";
}

322 323 324 325 326 327 328 329
#
# Signal that the current phase needs to stop so the user can do something.
#
sub PhaseStop($) {
    ($libinstall::reason) = (@_);
    throw "stop";
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
#
# Signal that the current phase is being skipped
#
sub PhaseSkip($) {
    ($libinstall::reason) = (@_);
    throw "skip";
}

#
# Check to see if a previous phase was skipped. Returns 1 if it was, 0 if not
#
sub PhaseWasSkipped($) {
    my ($phase) = (@_);
    return ($libinstall::phaseResults{$phase} &&
    	($libinstall::phaseResults{$phase} =~ /^skip$/));
}

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
#
# For impotent mode.
#
sub PhaseWouldHave($) {
    ($libinstall::reason) = (@_);
    throw "succeed";
}

#
# Also for impotent mode; detailed logging.
#
sub PhaseLog(@) {
    (@libinstall::loglines) = (@_);
}

#
# Also for impotent mode; log differences to a file.
#
sub DiffFiles($$) {
    my ($src,$dst) = @_;

    return
	if (!$impotent);

    if (! -e $dst) {
	my $stuff = `cat $src`;
	PhaseLog(split('\n', $stuff));
    }
    my $diff = `diff $src $dst`;
    PhaseLog(split('\n', $diff));
}
    
379 380 381 382 383 384
#
# Check to see if the phase is already done, as evidenced by the existance of
# a file
#
sub DoneIfExists($) {
    my ($filename) = @_;
385
    if (!$filename) { PhaseFail("Bad filename passed to DoneIfExists"); }
386
    if (-e $filename) {
387
	PhaseSkip("File already exists");
388 389 390
    }
}

391 392 393 394 395 396 397
#
# Same as above, but done if it doesn't exist
#
sub DoneIfDoesntExist($) {
    my ($filename) = @_;
    if (!$filename) { PhaseFail("Bad filename passed to DoneIfExists"); }
    if (!-e $filename) {
398
	PhaseSkip("File does not exist");
399 400 401
    }
}

402 403 404 405 406 407 408 409 410 411 412 413
#
# Check to see if the phase is already done, as evidenced by the existance
# and executability of a file.
#
sub DoneIfExecutable($) {
    my ($filename) = @_;
    if (!$filename) { PhaseFail("Bad filename passed to DoneIfExecutable"); }
    if (-x "$filename") {
	PhaseSkip("File already exists and is executable");
    }
}

414 415 416 417 418 419
#
# Check to see if the phase is already done, as evidenced by the existance of
# comments within a file
#
sub DoneIfEdited($) {
    my ($filename) = @_;
420
    if (!$filename) { PhaseFail("Bad filename passed to DoneIfEdited"); }
421
    my $magic_string = MAGIC_TESTBED_START();
422
    open(FH,$filename) or return;
423
    if (grep /$magic_string/, <FH>) {
424
        close(FH);
425
	PhaseSkip("File has already been edited");
426
    }
427
    close(FH);
428 429
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
#
# Similar to DoneIfEdited, but look for the existance of a user specified
# string in the file.
#
sub DoneIfContains($$) {
    my ($filename,$magic_string) = @_;
    if (!$filename) { PhaseFail("Bad filename passed to DoneIfContains"); }
    open(FH,$filename) or return;
    if (grep /$magic_string/, <FH>) {
        close(FH);
	PhaseSkip("File already contains desired info");
    }
    close(FH);
}

445 446 447 448
#
# Check to see if the phase is already done, as evidenced by the fact that two
# files are identical
#
449
sub DoneIfIdentical($$) {
450 451 452 453
    my ($filename1,$filename2) = @_;
    if (!$filename1 || !$filename2) {
	PhaseFail("Bad filename passed to DoneIfIdentical");
    }
454 455 456
    if (!-e $filename1 || !-e $filename2) {
	return;
    }
457 458
    system("cmp -s $filename1 $filename2");
    if (! $?) {
459
	PhaseSkip("Files has not changed");
460 461 462
    }
}

463 464 465
#
# Done if package installed.
#
466 467 468 469 470 471
sub DoneIfPackageInstalled($;$) {
    my ($pname,$exact) = @_;

    $exact = 0
	if (!defined($exact));
    if (InstalledPackage($pname, $exact)) {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	PhaseSkip("already installed");
    }
}

#
# Backup a file or fail.
#
sub BackUpFileFatal($)
{
    my ($filename) = @_;
    my $suffix     = time();
    my $backup     = $filename . "-" . $suffix;

    PhaseFail("$filename does not exist")
	if (! -e $filename);
Leigh Stoller's avatar
Leigh Stoller committed
487 488 489 490 491 492 493

    if (-e $backup) {
	sleep(1);
	$backup = $filename . "-" . time();
	PhaseFail("$backup already exists")
	    if (-e $backup);
    }
494 495 496

    ExecQuietFatal("/bin/cp -p $filename $backup")
	if (!$impotent);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542

    # Update the comment.
    $libinstall::reason = "Backed up to $backup";
}

#
# Delete a file or fail.
#
sub DeleteFileFatal($)
{
    my ($filename) = @_;

    PhaseSucceed("Already deleted")
	if (! -e $filename);

    ExecQuietFatal("/bin/rm -f $filename")
	if (!$impotent);

    # Update the comment.
    $libinstall::reason = "Deleted $filename";
}

#
# Rename a directory or fail. 
#
sub BackupDirectoryFatal($)
{
    my ($path) = @_;
    my $suffix = time();
    my $backup = $path . "-" . $suffix;

    PhaseFail("$path does not exist")
	if (! -e $path);

    if (-e $backup) {
	sleep(1);
	$backup = $path . "-" . time();
	PhaseFail("$backup already exists")
	    if (-e $backup);
    }

    ExecQuietFatal("rsync -a $path/ $backup")
	if (!$impotent);
    
    # Update the comment.
    $libinstall::reason = "Backed up to $backup";
543 544
}

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
#
# Check to see if filesystem already mounted
#
sub DoneIfMounted($)
{
    my ($dir) = @_;

    #
    # Grab the output of the mount command and parse. 
    #
    if (! open(MOUNT, "/sbin/mount|")) {
	PhaseFail("Cannot run mount command");
    }
    while (<MOUNT>) {
	if ($_ =~ /^([-\w\.\/:\(\)]+) on ([-\w\.\/]+) \((.*)\)$/) {
	    # Search for nfs string in the option list.
	    foreach my $opt (split(',', $3)) {
		if ($opt eq "nfs") {
		    if ($dir eq $2) {
			close(MOUNT);
565
			PhaseSkip("NFS dir already mounted");
566 567 568 569 570 571 572 573 574
		    }
		}
	    }
	}
    }
    close(MOUNT);
    return;
}

575 576 577 578 579 580 581 582 583 584
#
# Append some text to a configuration file, with a special testbed tag that 
# will help inform the user of what's been done, and help future invocations
# tell that this has already been done. Returns undef if it succeeds, or
# an error string if it fails
# TODO - handle alternate comment characters
# TODO - handle files that it's OK to create
#
sub AppendToFile($@) {
    my ($filename, @lines) = @_;
585

586 587 588 589
    if (defined($logfp)) {
	print $logfp "Append to file: $filename\n";
	print $logfp "@lines\n";
    }
590 591 592 593
    if ($impotent) {
	PhaseWouldHave("append to $filename");
	return undef;
    }
594 595 596 597 598 599
    if (!-e $filename) {
	return "File $filename does not exist";
    }
    open(FH,">>$filename") or return "Unable to open $filename for ".
	"writing: $!";

600
    print FH "# " . MAGIC_TESTBED_START() . "\n";
601
    print FH map "$_\n", @lines;
602
    print FH "# " . MAGIC_TESTBED_END() . "\n";
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

    close(FH);

    return undef;
}

#
# Same as above, but call PhaseFail on failure
#
sub AppendToFileFatal($@) {
    my ($filename,@lines) = @_;
    my $error = AppendToFile($filename,@lines);
    if ($error) {
	PhaseFail($error);
    }
}

#
# Create a new file (must not already exist), and fill it with the given
# contents. Returns undef if successful, or an error message otherwise.
#
sub CreateFile($;@) {
    my ($filename,@lines) = @_;
626

627 628 629 630
    if (defined($logfp)) {
	print $logfp "Create file: $filename\n";
	print $logfp "@lines\n";
    }
631 632 633 634
    if ($impotent) {
	PhaseWouldHave("create $filename");
	return undef;
    }
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    if (-e $filename) {
	return "File $filename already exists";
    }
    open(FH,">$filename") or return "Unable to open $filename for ".
	"writing: $!";

    if (@lines) {
	print FH map "$_\n", @lines;
    }

    close FH;
    return undef;    
}

#
# Same as above, but call PhaseFail on failure
#
sub CreateFileFatal($@) {
    my ($filename,@lines) = @_;
    my $error = CreateFile($filename,@lines);
    if ($error) {
	PhaseFail($error);
    }
}

#
# Execute a program, hiding its stdout and stderr from the user, but saving
662 663 664
# them for later use. Returns the exit value of the program if used in scalar
# context, or an array composed of the exit status and output if used in array
# context.
665 666 667 668 669 670
#
sub ExecQuiet(@) {
    #
    # Use a pipe read, so that we save away the output
    #
    my $commandstr = join(" ",@_);
671 672 673 674 675 676

    if ($impotent) {
	PhaseWouldHave("exec($commandstr)");
        return 0;
    }
    
677 678 679 680 681 682 683 684 685
    my @output = ();
    open(PIPE,"$commandstr 2>&1 |") or return -1;
    while (<PIPE>) {
	push @output, $_;
    }
    close(PIPE);

    my $exit_value  = $? >> 8;

686 687 688 689 690 691 692 693 694 695 696 697
    #
    # Detailed logging.
    #
    if (defined($logfp)) {
	print $logfp "\n";
	print $logfp "Exec('$commandstr')\n";
	if (@output) {
	    print $logfp "@output";
	    print $logfp "\n";
	}
    }

698 699 700
    @libinstall::lastExecOutput = @output;
    $libinstall::lastCommand = $commandstr;

701 702 703 704 705
    if (wantarray) {
	return ($exit_value, @output);
    } else {
	return $exit_value;
    }
706 707 708 709 710 711 712 713
}

#
# Same as the above, but the current phase fails if the program returns a non-0
# exit status.
#
sub ExecQuietFatal(@) {
    if (ExecQuiet(@_)) {
714 715
	my $msg = join(' ', @_);
	PhaseFail("Unable to execute: '$msg'");
716 717 718
    }
}

719
#
720
# Signal a daemon, if it's PID file exists. If we can't kill it, we assume that
721 722 723 724 725
# it's because it wasn't running, and skip the phase. Fails if it has trouble
# reading the pid file.
# Takes the name of the daemon as an argument, and assumes
# that the pid file is /var/run/$name.pid
#
726 727
sub SignalDaemon($$) {
    my ($name,$sig) = @_;
728 729 730 731 732 733 734 735
    my $pidfile = "/var/run/$name.pid";
    PhaseSkip("$name is not running") unless (-e $pidfile);
    open(PID,$pidfile) or PhaseFail("Unable to open pidfile $pidfile");
    my $pid = <PID>;
    chomp $pid;
    close PID;

    PhaseFail("Bad pid ($pid) in $pidfile\n") unless ($pid =~ /^\d+$/);
736 737 738 739 740 741 742

    if ($impotent) {
	PhaseWouldHave("signal($sig) $name");
	return;
    }
    if (!kill($sig, $pid)) {
	PhaseSkip("$name is not running");
743 744 745
    }
}

746 747 748 749 750 751
sub HUPDaemon($) {
    my ($name) = @_;

    SignalDaemon($name, 'HUP');
}

752 753 754
#
# Restart a daemon if running. Do not start if not running.
#
755 756
sub RestartDaemon($;$) {
    my ($name, $path) = @_;
757 758 759 760 761 762 763 764 765 766 767 768 769 770

    my $pidfile = "$VARRUN/${name}.pid";

    if (! -e "$VARRUN/stated.pid") {
	PhaseSkip("Testbed not running");
    }
    if (!-e $pidfile) {
	PhaseSkip("$name not running");
    }
    if ($impotent) {
	PhaseWouldHave("restart $name");
	return 1;
    }
    SignalDaemon($name, 'TERM');
771
    sleep(1);
772 773 774
    $path = "$TBROOT/sbin/$name"
	if (!defined($path));
    if (ExecQuiet($path) == 0) {
775 776 777 778 779
	PhaseSucceed("$name started");
    }
    PhaseFail("Could not start $name");
}

780 781 782 783 784 785
#
# Fetch a file from the network, using any protocol supported by fetch(1).
# Arguments are URL and a local filename. Retunrns 1 if succesful, 0 if not.
#
sub FetchFile($$) {
    my ($URL, $localname) = @_;
786 787 788 789 790 791

    if ($impotent) {
	PhaseLog("$URL --> $filename");
	PhaseWouldHave("fetch $URL");
	return 1;
    }
792 793
    if (ExecQuiet("$FETCH --retry --timeout=30 --retry-delay=15 ".
		  "  -o $localname $URL")) {
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
	return 0;
    } else {
	return 1;
    }
}

#
# Same as above, but failure is fatal
#
sub FetchFileFatal($$) {
    my ($URL, $localname) = @_;
    if (!FetchFile($URL,$localname)) {
	PhaseFail("Unable to fetch $URL");
    }
}

810 811
#
# Locate the proper version of a package to install by looking
812 813
# at the available package tarballs. Note that we do "ls -t"
# so that if there is more than one package, we will return the latest.
814
#
815
# Must be called "in phase" since we will PhaseFail on errors.
816 817 818 819 820 821 822
#
sub GetPackage($$) {
    my ($prefix, $packagedir) = @_;

    PhaseFail("Must provide -p (packagedir) argument!")
	if (!$packagedir);

823
    my @pname = `ls -t $packagedir/$prefix-*.txz 2>/dev/null`;
824
    if ($?) {
825
	@pname = `ls -t $packagedir/$prefix-*.tbz 2>/dev/null`;
826
	if ($?) {
827
	    @pname = `ls -t $packagedir/$prefix-*.tgz 2>/dev/null`;
828 829 830
	    PhaseFail("Cannot find $prefix package in $packagedir!")
		if ($?);
	}
831
    }
832
    chomp(@pname);
833

834 835 836 837 838 839 840 841 842 843
    if (@pname > 1) {
	# if it matched more than one package, find one with exactly one '-'
	foreach my $pn (@pname) {
	    if ($pn =~ /^$packagedir\/$prefix-[^-]+\.t[bgx]z$/) {
		return $pn;
	    }
	}
    }

    return $pname[0];
844 845
}

846 847 848 849 850 851 852 853 854 855 856 857 858 859
#
# Return the name of any installed package matching the given regex or exact
# name (if $exact != 0). If there are multiple matches, we warn and return
# the first. Return undef if no match.
#
sub InstalledPackage($$) {
    my ($pname, $exact) = @_;
    my (@foo, $args);

    if (-x "/usr/sbin/pkg_info") {
	# note: use extended REs to match new pkg tool
	$args = $exact ? "-I" : "-I -X";
	@foo = `pkg_info $args $pname 2>/dev/null`;
    } elsif (-x "/usr/sbin/pkg") {
860
	$args = $exact ? "-E" : "-E -x";
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
	@foo = `pkg info $args $pname 2>/dev/null`;
    } else {
	PhaseFail("No package tools found!?");
    }

    if ($? == 0 && @foo > 0) {
	if (@foo > 1) {
	    print STDERR "WARNING: '$pname' matches multiple packages, returning first\n";
	}
	if ($foo[0] =~ /^(\S+)/) {
	    return $1;
	}
    }
    return undef;
}

sub AddPackage($$) {
    my ($pname, $packagedir) = @_;

    if (-x "/usr/sbin/pkg_add") {
	ExecQuietFatal("env PKG_PATH=$packagedir pkg_add $pname");
    } elsif (-x "/usr/sbin/pkg") {
Mike Hibler's avatar
Mike Hibler committed
883 884 885 886 887 888 889 890 891
	# must have the prefix
	if ($pname !~ /^$packagedir\//) {
	    $pname = "$packagedir/$pname";
	}
	# and the suffix
	if ($pname !~ /\.txz$/) {
	    $pname .= ".txz";
	}
	ExecQuietFatal("pkg add $pname");
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    } else {
	PhaseFail("No package tools found!?");
    }
}

sub DelPackage($$$) {
    my ($pname, $recursive, $fatal) = @_;
    my ($cmd, $args);

    $args = "-f";
    if (-x "/usr/sbin/pkg_delete") {
	$cmd = "pkg_delete";
	$args .= " -r"
	    if ($recursive);
    } elsif (-x "/usr/sbin/pkg") {
	$cmd = "pkg delete";
	$args .= " -y";
	$args .= " -R"
	    if ($recursive);
    } else {
	PhaseFail("No package tools found!?");
    }
Mike Hibler's avatar
Mike Hibler committed
914
    $args .= " -x $pname";
915 916 917 918 919 920 921 922

    if ($fatal) {
	ExecQuietFatal("$cmd $args");
    } else {
	ExecQuiet("$cmd $args");
    }
}

923 924 925 926
#
# Print out the phase stack that got us here
#
sub PrintPhaseTrace() {
927 928
    my $message =
	"-------------------- Phase Stack ----------------------------\n";
929 930 931 932 933
    my @tmpphase = @libinstall::phasestack;
    my @tmpdescr = @libinstall::descrstack;
    my ($phase, $descr);
    while (@tmpdescr) {
	($phase, $descr) = (pop @tmpphase, pop @tmpdescr);
934
	$message .= sprintf "%-10s %-50s\n", $phase, $descr;
935
    }
936 937 938 939 940 941
    $message .=
	"--------------------------------------------------------------\n";

    print $message;
    print $logfp $message
	if (defined($logfp));
942 943 944 945 946 947 948 949 950
}

#
# Print out the ouput of the last command that ran
#
sub PrintLastOutput() {
    if (!$libinstall::lastCommand) {
	return;
    }
951 952 953 954 955 956 957 958
    my $message =
	"------------------------------------------ Last Command Output\n" .
	"Command: $libinstall::lastCommand\n" .
	"@libinstall::lastExecOutput" .
	"--------------------------------------------------------------\n";
    print $message;
    print $logfp $message
	if (defined($logfp));
959 960
}

961 962 963 964
sub LastOutput() {
    if (!$libinstall::lastCommand) {
	return ();
    }
965 966 967 968
    return ("------------------------------------------ Last Command Output\n",
	    "Command: $libinstall::lastCommand\n",
	    @libinstall::lastExecOutput,
	    "--------------------------------------------------------------\n");
969 970
}

Leigh Stoller's avatar
Leigh Stoller committed
971 972 973 974 975 976 977 978 979 980
#
# Get me a secret
#
sub GenSecretKey()
{
    my $key=`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
    chomp($key);
    return $key;
}

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
sub EscapeShellArg($)
{
    my ($str) = @_;
    my @chars  = split('', $str);
    my $result = "";

    foreach my $ch (@chars) {
        if ($ch eq '\'') {
            $result = $result . "\'\\\'";
	}
	$result = $result . "$ch";
    }
    return "'$result'";
}

#
# Update a file. The idea here is to comment out particular lines, as
# described by the patterns, and then add the new lines.
#
# Returns undef if it succeeds, or an error string if it fails.
#
sub UpdateFileFatal($$@)
{
    my ($filename, $patterns, @lines) = @_;
    my $old = "";
    my $new = "";

    if (! -e $filename) {
	PhaseFail("Bad filename passed to UpdateFile");
    }
    open(FH,$filename) or
	PhaseFail("Cannot open $filename for reading");
    while (<FH>) {
	$old .= $_;

	foreach my $pat (@$patterns) {
	    if ($_ =~ $pat) {
		# XXX Deal with other file types (different comment char)
		$new .= '# ';
		last;
	    }
	}
	$new .= $_;
      pass:
    }
    close(FH);
    PhaseSkip("No changes made")
1028
	if (@patterns && $old eq $new);
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

    # Stash old copy.
    BackUpFileFatal($filename);
    DeleteFileFatal($filename);
    # and create new version.
    CreateFileFatal($filename, $new . join("\n", @lines));
    return undef;
}

#
# Check to see if the phase is already done, as evidenced by the existence of
# the *exact* text block in the file.
#
sub DoneIfUpdated($@)
{
    my ($filename, @lines) = @_;
    my $block   = join("\n", @lines);

    if (! -e $filename) {
	PhaseFail("No such file $filename");
    }
    open(FH, $filename) or
	PhaseFail("Could not open $filename");
    local $/;
    my $content = <FH>;
    close(FH);

    PhaseSkip("Already updated")
	if ($content =~ /^($block)$/m);
}

#
# Update a file by doing the equivalent of query/replace.
#
# Returns undef if it succeeds, or an error string if it fails.
#
sub QueryReplaceFileFatal($$)
{
    my ($filename, $replacements) = @_;
    my $old = "";
    my $new = "";

    if (! -e $filename) {
	PhaseFail("Bad filename passed to UpdateFile");
    }
    open(FH,$filename) or
	PhaseFail("Cannot open $filename for reading");
    while (<FH>) {
	$old .= $_;

	foreach my $ref (@$replacements) {
	    my ($pat,$repl) = @$ref;
	    
	    if ($_ =~ $pat) {
		$_ =~ s/$pat/$repl/ee;
		last;
	    }
	}
	$new .= $_;
      pass:
    }
    close(FH);
    PhaseSkip("No changes made")
	if ($old eq $new);

    # Stash old copy.
    BackUpFileFatal($filename);
    DeleteFileFatal($filename);
    # and create new version.
    CreateFileFatal($filename, $new);
    return undef;
}

#
# Get the subject of a certificate, broken into the parts.
#
sub ParseCertificate($)
{
    my ($filename) = @_;
    my %results = ();

    if (! -e $filename) {
	return undef;
    }
    my $subject = `openssl x509 -subject -noout -in $filename`;
    return undef
	if ($?);
    chomp($subject);
    my @parts = split('/', $subject);
    foreach my $part (@parts) {
	my ($key,$val) = split('=', $part);
	$results{$key} = $val;
    }
    return \%results;
}

1125
1;