localize_mfs.in 13.6 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2010-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 27 28 29 30 31 32 33
#
use English;
use strict;
use Getopt::Std;
use Data::Dumper;

#
# Localize an MFS (FreeBSD or Linux variants).
#
sub usage()
{
34
    print("Usage: localize_mfs [-d] [-c vga|sio|sio2|sio3|sio4|null] <path>\n");
35 36
    exit(-1);
}
37
my $optlist = "dc:i";
38
my $debug   = 0;
39
my $igbcruft= 0;
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

#
# Configure variables
#
my $TB		= "@prefix@";
my $ETCDIR	= "$TB/etc";
my $ELABINELAB  = @ELABINELAB@;
my $MFSCONSOLE  = "@NODECONSOLE@";
my $OURTIMEZONE = "@OURTIMEZONE@";

# Need these below.
my $FBSD_MAJOR;
my $FBSD_MINOR;

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use emdb;
use libEmulab;

my $CHGRP	= "/usr/bin/chgrp";
my $CHMOD	= "/bin/chmod";
my $MKDIR	= "/bin/mkdir";
my $CHOWN	= "/usr/sbin/chown";
my $CAT		= "/bin/cat";
my $CP		= "/bin/cp";
my $MV		= "/bin/mv";
my $RM		= "/bin/rm";
my $PW		= "/usr/sbin/pw";
my $CPIO	= "/usr/bin/cpio";
my $SED		= "/usr/bin/sed";
my $MOUNT	= "/sbin/mount";
my $UMOUNT	= "/sbin/umount";
my $MDCONFIG    = "/sbin/mdconfig";
my $AUTHKEYS	= "/root/.ssh/authorized_keys";
my $ZONEINFO    = "/usr/share/zoneinfo";
my $IMAGEKEYS_DIR = "$ETCDIR/image_hostkeys";
89
my $NTPCONF	= "$ETCDIR/image_ntp.conf";
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

# Protos
sub fatal($);
sub LocalizeBSD();
sub LocalizeLinux($);
sub ExecQuiet($);

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
108 109 110
if (defined($options{"i"})) {
    $igbcruft = 1;
}
111 112 113
if (defined($options{"c"})) {
    $MFSCONSOLE = $options{"c"};
}
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
usage() 
    if (@ARGV != 1);
my $path = $ARGV[0];

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

if (`uname -r` =~ /^(\d+)\.(\d+)/) {
    $FBSD_MAJOR = $1;
    $FBSD_MINOR = $2;
}
else {
    fatal("Could not determine what version of FreeBSD you are running!");
}

chdir($path) or
    fatal("Could not chdir to $path");

#
# We must have a password hash in the DB.
#
my $passhash;

if (!GetSiteVar("images/root_password", \$passhash)) {
    fatal("Could not get sitevar images/root_password");
}
if ($passhash eq "") {
    fatal("The sitevar images/root_password is not set!");
}

#
# Figure out what kind of thing to localize.
#
if (-e "boot" && -e "boot/mfsroot") {
148
    print "Localizing FreeBSD MFS $path/boot/mfsroot ...\n";
149 150 151 152 153
    LocalizeBSD();
    exit(0);
}
foreach my $extension ("lzma", "bz2", "gz") {
    if (-e "initramfs.${extension}") {
154
	print "Localizing Linux MFS $path/initramfs.$extension ...\n";
155 156 157 158
	LocalizeLinux($extension);
	exit(0);
    }
    if (-e "initramfs") {
159
	print "Localizing Linux MFS $path/initramfs ...\n";
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
	LocalizeLinux("");
	exit(0);
    }
}
# Oops, do not know what to do.
fatal("Do not know what to do with $path");

#
# Localize a FreeBSD MFS.
#
sub LocalizeBSD()
{
    my $configed = 0;
    my $mounted  = 0;
    my $mpoint   = "/mfsmount";
    my $mfsroot  = "mfsroot";

    if (-e "boot") {
	chdir("boot") or
	    fatal("Could not chdir into boot directory");
    }
    if (! -e $mpoint) {
	system("$MKDIR $mpoint") == 0
	    or fatal("Could not mkdir $mpoint");
    }
    
    my $Undo = sub () {
	if ($mounted) {
	    ExecQuiet("$UMOUNT $mpoint") == 0
		or fatal("Could not unmount $mpoint: mfsroot is still active!");
	}
	if ($configed) {
	    my $cmd = ($FBSD_MAJOR >= 5 ?
		       "$MDCONFIG -d -u 2" : "vnconfig -u vn1");
	    
	    ExecQuiet($cmd) == 0
		or fatal("Could not unconfig: mfsroot is still active!");
	}
    };

200
    #
Leigh Stoller's avatar
Leigh Stoller committed
201
    # Map from $MFSCONSOLE to config setting.
202 203 204
    #
    my %consmap = (
	"sio"  => "com",
205
	"sio1" => "com",
206
	"sio2" => "com",
207 208
	"sio3" => "com",
	"sio4" => "com",
209 210 211
	"vga"  => "vid",
	"null" => "null"
    );
Leigh Stoller's avatar
Leigh Stoller committed
212 213
    if (!exists($consmap{$MFSCONSOLE})) {
	fatal("Do not know what to do with console: $MFSCONSOLE");
214 215
    }

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    #
    # Work on a copy.
    #
    ExecQuiet("$CP -pf $mfsroot ${mfsroot}.new") == 0
	or fatal("Could not make a copy of $mfsroot");

    #
    # Mount up the MFS.
    #
    my $cmd = ($FBSD_MAJOR >= 5 ? 
	       "$MDCONFIG -a -t vnode -f ${mfsroot}.new -u 2" :
	       "vnconfig -c vn1 ${mfsroot}.new");
    ExecQuiet($cmd) == 0
	or goto bad;
    $configed = 1;

    $cmd = ($FBSD_MAJOR >= 5 ?
	    "$MOUNT /dev/md2 $mpoint" : "$MOUNT /dev/vn1 $mpoint");
    ExecQuiet($cmd) == 0
	or goto bad;
    $mounted = 1;

    #
    # Okay, now we can localize
    #
    if (! -e "$mpoint/root/.ssh" &&
	ExecQuiet("$MKDIR -m 700 $mpoint/root/.ssh")) {
	goto bad;
    }
    if ($ELABINELAB &&
	# Combine with outer boss root user ssh keys.
	ExecQuiet("$CAT $AUTHKEYS > $mpoint/root/.ssh/authorized_keys2")) {
	goto bad;
    }
    # And add the current boss root user ssh keys.
    if (ExecQuiet("$CAT /root/.ssh/*.pub >> $mpoint/root/.ssh/authorized_keys2") ||
	ExecQuiet("$CHMOD 600 $mpoint/root/.ssh/authorized_keys2")) {
	goto bad;
    }
    # Boss certificate. Need emulab.pem for TPM. 
    ExecQuiet("$CP -p $ETCDIR/emulab.pem $ETCDIR/client.pem $mpoint/etc/emulab")
	== 0 or goto bad;
    # All MFSs and images get the same ssh host keys.
    ExecQuiet("$CP -p $IMAGEKEYS_DIR/* $mpoint/etc/ssh")
	== 0 or goto bad;
    # Copy boss timezone into the MFS.
    ExecQuiet("$CP -p $ZONEINFO/$OURTIMEZONE $mpoint/etc/localtime")
	== 0 or goto bad;
264 265 266
    # Copy image version of ntp.conf into the MFS.
    ExecQuiet("$CP -p $NTPCONF $mpoint/etc/ntp.conf")
	== 0 or goto bad;
267
    # Localize the root/toor password from the sitevar
268
    ExecQuiet("echo '$passhash' | $PW -V $mpoint/etc usermod toor -H 0")
269
	== 0 or goto bad;
270
    ExecQuiet("echo '$passhash' | $PW -V $mpoint/etc usermod root -H 0")
271 272
	== 0 or goto bad;

273 274 275 276 277 278 279 280
    #
    # IGB cruft; See the comment in loader.conf.orig about this. 
    #
    if ($igbcruft) {
	ExecQuiet("$SED -i -e 's,^#kern\.ipc\.nmb,kern.ipc.nmb,' " .
		  "     loader.conf.orig") == 0 or goto bad;
    }

281
    #
282 283 284 285 286 287 288
    # Console handling.
    #
    # Since 2013, the 8.x MFSes don't require customization for the
    # console type. The console is instead chosen based on the pxeboot
    # that booted the MFS (i.e., pxeboot customizes the instance of the MFS).
    #
    # We detect this by looking for a particular comment in loader.conf.orig.
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
    my $magicstr = "XXX note that pxeboot will now setup the console";
    if (system("grep -q '$magicstr' loader.conf.orig")) {
	# Localize the console to use.
	my $consdev = $consmap{$MFSCONSOLE} . "console";
	ExecQuiet("echo 'console=\"$consdev\"' >> loader.conf.orig")
	    == 0 or goto bad;

	#
	# XXX tmp hack.
	# If console is VGA, create the magic file that tells slicefix
	# to ensure that serial console is disabled in any FreeBSD image
	# that is loaded (in case the machine has no serial port).
	# We should have a more general way to set the console on a per
	# node basis.
	#
	if ($MFSCONSOLE eq "vga") {
	    ExecQuiet("$CP /dev/null $mpoint/etc/emulab/isvgaonly") == 0
		or goto bad;
	    # Fix for a paths.sh messup on the MFS.
	    if (-e "$mpoint/etc/testbed" &&
		ExecQuiet("$CP /dev/null $mpoint/etc/testbed/isvgaonly")) {
		goto bad;
	    }
	}
	else {
	    unlink("$mpoint/etc/emulab/isvgaonly")
		if (-e "$mpoint/etc/emulab/isvgaonly");
	    unlink("$mpoint/etc/testbed/isvgaonly")
		if (-e "$mpoint/etc/testbed/isvgaonly");
319 320 321
	}
    }
    else {
322 323 324 325 326 327 328 329 330 331
	my $cstr = $MFSCONSOLE;
	$cstr = "sio1" if ($cstr eq "sio");

	print "*** NOTE: This MFS is console-neutral.\n".
	    "  To set the console type to \"$cstr\" globally, rename\n".
	    "    /tftpboot/pxeboot.emu-$cstr to be /tftpboot/pxeboot.emu.\n".
	    "  To set the console to \"$cstr\" for a particular node type, edit the\n".
	    "    appropriate node type entry in the web page and add/modify the\n".
	    "    \"pxe_boot_path\" attribute setting the value to\n".
	    "    \"/tftpboot/pxeboot.emu-$cstr\".\n";
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    }

    #
    # Mark as "localized". This tells slicefix that it should copy all
    # the above stuff into the image.
    #
    ExecQuiet("$CP /dev/null $mpoint/.localized")
	== 0 or goto bad;
    
    &$Undo();

    #
    # Now copy back and compress. 
    #
    ExecQuiet("$MV -f $mfsroot ${mfsroot}.old") == 0
	or fatal("Could not save old $mfsroot");
    ExecQuiet("$MV -f ${mfsroot}.new ${mfsroot}") == 0
	or fatal("Could not rename new $mfsroot");
    ExecQuiet("./prepare") == 0
	or fatal("Could not prepare the MFS");
    
    return 0;

  bad:
    &$Undo();
    exit(1);
}

#
361
# Localize a Linux MFS
362 363 364 365 366 367 368 369 370
#
sub LocalizeLinux($)
{
    my ($extension) = @_;
    my $compression;
    my $mpoint   = "extracted_initramfs";
    my $initfs   = "initramfs";

    if ($extension eq "lzma") {
371 372 373 374 375 376 377 378
	if (-x "/usr/bin/lzma") {
	    $compression = "lzma";
	} elsif (-x "/usr/local/bin/lzma") {
	    $compression = "/usr/local/bin/lzma";
	} else {
	    fatal("Cannot find lzma command; ".
		  "you may need to install the archivers/xz port");
	}
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    }
    elsif ($extension eq "bz2") {
	$compression = "bzip2";
    }
    elsif ($extension eq "gz") {
	$compression = "gzip";
    }

    ExecQuiet("$RM -rf $mpoint") == 0
	or fatal("Could not remove old $mpoint directory");
    ExecQuiet("$MKDIR $mpoint") == 0
	or fatal("Could not create $mpoint directory");
    chdir("$mpoint") or
	    fatal("Could not chdir into $mpoint directory");
    
    # Extract
    if (defined($compression)) {
396
	ExecQuiet("$compression -dc < ../${initfs}.${extension} | cpio -idum")
397 398 399 400 401 402 403 404 405 406
	    == 0 or fatal("Could not extract ${initfs}.${extension}");
    }
    else {
	ExecQuiet("$CPIO -idu < ../${initfs}") == 0
	    or fatal("Could not extract ${initfs}");
    }

    #
    # Okay, now we can localize
    #
407 408
    if (! -e "root/.ssh" &&
	ExecQuiet("$MKDIR -m 700 root/.ssh")) {
409 410 411 412
	goto bad;
    }
    if ($ELABINELAB &&
	# Combine with outer boss root user ssh keys.
413
	ExecQuiet("$CAT $AUTHKEYS > root/.ssh/authorized_keys")) {
414 415 416
	goto bad;
    }
    # And add the current boss root user ssh keys.
417 418
    if (ExecQuiet("$CAT /root/.ssh/*.pub >> root/.ssh/authorized_keys") ||
	ExecQuiet("$CHMOD 600 root/.ssh/authorized_keys")) {
419 420 421
	goto bad;
    }
    # Boss certificate. Need emulab.pem for TPM. 
422
    ExecQuiet("$CP -p $ETCDIR/emulab.pem $ETCDIR/client.pem etc/emulab")
423 424
	== 0 or goto bad;
    # All MFSs and images get the same ssh host keys.
425
    ExecQuiet("$CP -p $IMAGEKEYS_DIR/* etc/ssh")
426 427
	== 0 or goto bad;
    # Copy boss timezone into the MFS.
428
    ExecQuiet("$CP -p $ZONEINFO/$OURTIMEZONE etc/localtime")
429 430 431
	== 0 or goto bad;

    # And the root/toor passwords.
432 433 434 435 436
    my $pfile = "etc/shadow";
    if (! -e "$pfile") {
	$pfile = "etc/passwd";
    }

437 438
    ExecQuiet("$SED -i .orig -e 's,^root:\([^:]*\),root:$passhash,' ".
	      "              -e 's,^toor:\([^:]*\),toor:$passhash,' ".
439
	      "     $pfile")
440 441 442 443 444 445
	== 0 or goto bad;

    #
    # Mark as "localized". This tells slicefix that it should copy all
    # the above stuff into the image.
    #
446 447 448 449
    # XXX argh, it appears that the cpio unpacking of the MFS at boot
    # time doesn't get /.localized and I don't want to figure out why.
    # So we stash the file in /root/.localized as well.
    #
450
    ExecQuiet("$CP /dev/null .localized")
451
	== 0 or goto bad;
452 453
    ExecQuiet("$CP /dev/null root/.localized")
	== 0 or goto bad;
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

    #
    # Compress it back.
    #
    if (defined($compression)) {
	ExecQuiet("find . | $CPIO -H newc -o | $compression -c9 ".
		  "  > ../${initfs}.${extension}.new")
	    == 0 or fatal("Could not compress ${initfs}.${extension}.new");
	ExecQuiet("$MV -f ../${initfs}.${extension} ../${initfs}.${extension}.old")
	    == 0 or fatal("Could not back up ${initfs}.${extension}");
	ExecQuiet("$MV -f ../${initfs}.${extension}.new ../${initfs}.${extension}")
	    == 0 or fatal("Could not rename new ${initfs}.${extension}");
    }
    else {
	ExecQuiet("find . | $CPIO -H newc -o > ../${initfs}.new") == 0
	    or fatal("Could not compress ${initfs}");
	ExecQuiet("$MV -f ../${initfs} ../${initfs}.old")
	    == 0 or fatal("Could not back up ${initfs}");
	ExecQuiet("$MV -f ../${initfs}.new ../${initfs}")
	    == 0 or fatal("Could not rename new ${initfs}");
    }
475 476 477

    chdir("..") or
	    fatal("Could not chdir out of $mpoint directory");
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 516 517 518 519 520 521 522 523 524 525 526 527 528
    system("$RM -rf $mpoint")
	if (!$debug);
    
  bad:
    # Noting to undo, but leave the extracted stuff around for debugging.
    exit(1);
}

#
# Run a command, being sure to capture all output. 
#
sub ExecQuiet($)
{
    #
    # Use a pipe read, so that we save away the output
    #
    my ($command) = @_;
    my $output    = "";

    if ($debug) {
	print STDERR "exec('$command')\n";
    }

    if (!open(PIPE,"$command 2>&1 |")) {
	print STDERR "Failed pipe('$command')\n";
	return -1;
    }
    while (<PIPE>) {
	$output .= $_;
    }
    close(PIPE);
    my $exit_value  = $? >> 8;

    if ($exit_value) {
	print STDERR "Failed: exec('$command'):\n";
    }
    if ($debug || $exit_value) {
	print STDERR "$output\n";
    }
    
    return $exit_value;
}

sub fatal($)
{
    my ($mesg) = @_;

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}