libinstall.pm.in 24.7 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2003-2014 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
#
# Check to see if the phase is already done, as evidenced by the existance of
# comments within a file
#
sub DoneIfEdited($) {
    my ($filename) = @_;
408
    if (!$filename) { PhaseFail("Bad filename passed to DoneIfEdited"); }
409
    my $magic_string = MAGIC_TESTBED_START();
410
    open(FH,$filename) or return;
411
    if (grep /$magic_string/, <FH>) {
412
        close(FH);
413
	PhaseSkip("File has already been edited");
414
    }
415
    close(FH);
416 417 418 419 420 421
}

#
# Check to see if the phase is already done, as evidenced by the fact that two
# files are identical
#
422
sub DoneIfIdentical($$) {
423 424 425 426
    my ($filename1,$filename2) = @_;
    if (!$filename1 || !$filename2) {
	PhaseFail("Bad filename passed to DoneIfIdentical");
    }
427 428 429
    if (!-e $filename1 || !-e $filename2) {
	return;
    }
430 431
    system("cmp -s $filename1 $filename2");
    if (! $?) {
432
	PhaseSkip("Files has not changed");
433 434 435
    }
}

436 437 438
#
# Done if package installed.
#
439 440 441 442 443 444
sub DoneIfPackageInstalled($;$) {
    my ($pname,$exact) = @_;

    $exact = 0
	if (!defined($exact));
    if (InstalledPackage($pname, $exact)) {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
	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
460 461 462 463 464 465 466

    if (-e $backup) {
	sleep(1);
	$backup = $filename . "-" . time();
	PhaseFail("$backup already exists")
	    if (-e $backup);
    }
467 468 469

    ExecQuietFatal("/bin/cp -p $filename $backup")
	if (!$impotent);
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515

    # 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";
516 517
}

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
#
# 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);
538
			PhaseSkip("NFS dir already mounted");
539 540 541 542 543 544 545 546 547
		    }
		}
	    }
	}
    }
    close(MOUNT);
    return;
}

548 549 550 551 552 553 554 555 556 557
#
# 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) = @_;
558

559 560 561 562
    if (defined($logfp)) {
	print $logfp "Append to file: $filename\n";
	print $logfp "@lines\n";
    }
563 564 565 566
    if ($impotent) {
	PhaseWouldHave("append to $filename");
	return undef;
    }
567 568 569 570 571 572
    if (!-e $filename) {
	return "File $filename does not exist";
    }
    open(FH,">>$filename") or return "Unable to open $filename for ".
	"writing: $!";

573
    print FH "# " . MAGIC_TESTBED_START() . "\n";
574
    print FH map "$_\n", @lines;
575
    print FH "# " . MAGIC_TESTBED_END() . "\n";
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

    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) = @_;
599

600 601 602 603
    if (defined($logfp)) {
	print $logfp "Create file: $filename\n";
	print $logfp "@lines\n";
    }
604 605 606 607
    if ($impotent) {
	PhaseWouldHave("create $filename");
	return undef;
    }
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    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
635 636 637
# 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.
638 639 640 641 642 643
#
sub ExecQuiet(@) {
    #
    # Use a pipe read, so that we save away the output
    #
    my $commandstr = join(" ",@_);
644 645 646 647 648 649

    if ($impotent) {
	PhaseWouldHave("exec($commandstr)");
        return 0;
    }
    
650 651 652 653 654 655 656 657 658
    my @output = ();
    open(PIPE,"$commandstr 2>&1 |") or return -1;
    while (<PIPE>) {
	push @output, $_;
    }
    close(PIPE);

    my $exit_value  = $? >> 8;

659 660 661 662 663 664 665 666 667 668 669 670
    #
    # Detailed logging.
    #
    if (defined($logfp)) {
	print $logfp "\n";
	print $logfp "Exec('$commandstr')\n";
	if (@output) {
	    print $logfp "@output";
	    print $logfp "\n";
	}
    }

671 672 673
    @libinstall::lastExecOutput = @output;
    $libinstall::lastCommand = $commandstr;

674 675 676 677 678
    if (wantarray) {
	return ($exit_value, @output);
    } else {
	return $exit_value;
    }
679 680 681 682 683 684 685 686
}

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

692
#
693
# Signal a daemon, if it's PID file exists. If we can't kill it, we assume that
694 695 696 697 698
# 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
#
699 700
sub SignalDaemon($$) {
    my ($name,$sig) = @_;
701 702 703 704 705 706 707 708
    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+$/);
709 710 711 712 713 714 715

    if ($impotent) {
	PhaseWouldHave("signal($sig) $name");
	return;
    }
    if (!kill($sig, $pid)) {
	PhaseSkip("$name is not running");
716 717 718
    }
}

719 720 721 722 723 724
sub HUPDaemon($) {
    my ($name) = @_;

    SignalDaemon($name, 'HUP');
}

725 726 727
#
# Restart a daemon if running. Do not start if not running.
#
728 729
sub RestartDaemon($;$) {
    my ($name, $path) = @_;
730 731 732 733 734 735 736 737 738 739 740 741 742 743

    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');
744
    sleep(1);
745 746 747
    $path = "$TBROOT/sbin/$name"
	if (!defined($path));
    if (ExecQuiet($path) == 0) {
748 749 750 751 752
	PhaseSucceed("$name started");
    }
    PhaseFail("Could not start $name");
}

753 754 755 756 757 758
#
# 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) = @_;
759 760 761 762 763 764

    if ($impotent) {
	PhaseLog("$URL --> $filename");
	PhaseWouldHave("fetch $URL");
	return 1;
    }
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    if (ExecQuiet("$FETCH -o $localname $URL")) {
	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");
    }
}

782 783
#
# Locate the proper version of a package to install by looking
784 785
# 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.
786
#
787
# Must be called "in phase" since we will PhaseFail on errors.
788 789 790 791 792 793 794
#
sub GetPackage($$) {
    my ($prefix, $packagedir) = @_;

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

795
    my @pname = `ls -t $packagedir/$prefix-*.txz 2>/dev/null`;
796
    if ($?) {
797
	@pname = `ls -t $packagedir/$prefix-*.tbz 2>/dev/null`;
798
	if ($?) {
799
	    @pname = `ls -t $packagedir/$prefix-*.tgz 2>/dev/null`;
800 801 802
	    PhaseFail("Cannot find $prefix package in $packagedir!")
		if ($?);
	}
803
    }
804
    chomp(@pname);
805

806 807 808 809 810 811 812 813 814 815
    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];
816 817
}

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
#
# 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") {
	$args = $exact ? "" : "-x";
	@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
855 856 857 858 859 860 861 862 863
	# must have the prefix
	if ($pname !~ /^$packagedir\//) {
	    $pname = "$packagedir/$pname";
	}
	# and the suffix
	if ($pname !~ /\.txz$/) {
	    $pname .= ".txz";
	}
	ExecQuietFatal("pkg add $pname");
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
    } 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!?");
    }
    $args .= "-x $pname";

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

895 896 897 898
#
# Print out the phase stack that got us here
#
sub PrintPhaseTrace() {
899 900
    my $message =
	"-------------------- Phase Stack ----------------------------\n";
901 902 903 904 905
    my @tmpphase = @libinstall::phasestack;
    my @tmpdescr = @libinstall::descrstack;
    my ($phase, $descr);
    while (@tmpdescr) {
	($phase, $descr) = (pop @tmpphase, pop @tmpdescr);
906
	$message .= sprintf "%-10s %-50s\n", $phase, $descr;
907
    }
908 909 910 911 912 913
    $message .=
	"--------------------------------------------------------------\n";

    print $message;
    print $logfp $message
	if (defined($logfp));
914 915 916 917 918 919 920 921 922
}

#
# Print out the ouput of the last command that ran
#
sub PrintLastOutput() {
    if (!$libinstall::lastCommand) {
	return;
    }
923 924 925 926 927 928 929 930
    my $message =
	"------------------------------------------ Last Command Output\n" .
	"Command: $libinstall::lastCommand\n" .
	"@libinstall::lastExecOutput" .
	"--------------------------------------------------------------\n";
    print $message;
    print $logfp $message
	if (defined($logfp));
931 932
}

933 934 935 936
sub LastOutput() {
    if (!$libinstall::lastCommand) {
	return ();
    }
937 938 939 940
    return ("------------------------------------------ Last Command Output\n",
	    "Command: $libinstall::lastCommand\n",
	    @libinstall::lastExecOutput,
	    "--------------------------------------------------------------\n");
941 942
}

Leigh Stoller's avatar
Leigh Stoller committed
943 944 945 946 947 948 949 950 951 952
#
# 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;
}

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
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")
	if ($old eq $new);

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

1097
1;