dhcpd_makeconf.in 15.3 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh Stoller's avatar
Leigh Stoller committed
2 3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2012 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh Stoller committed
5 6
# All rights reserved.
#
7
use English;
8
use Getopt::Std;
9
use Fcntl ':flock';
10

11 12 13 14
#
# dhcpd_makeconf - helper script to create dhcpd.conf files from the database.
# The template file should look like an ordinary dhcpd.conf file, but have
# the string %%nodetype=<type> where you want entries for a set of nodes
15
# filled out. See the template file in the dhcp directory for an example.
16
#
17 18 19 20 21
sub usage {
    print "Usage: $0 [-h] [-v] [-i] [-t <templatefile>]\n";
    print "-h	Show this message\n";
    print "-v	Use virtual names, when possible, for hostnames\n";
    print "-i 	Install new config file to standard location.\n";
22
    print "-r 	Restart DHCPD after config file regeneration (with -i only)\n";
23 24 25 26
    print "Without -i, spits out a dhcpd config file on stdout, as in:\n";
    print "  $0 > dhcpd.conf\n";
    exit(1);
}
27
my $optlist = "ihvt:r";
28 29
my $install = 0;
my $vnames  = 0;
30
my $restart = 0;
31

32
#
33
# Configure variables
34
#
35
my $TBOPS       = "@TBOPSEMAIL@";
36
my $ELABINELAB  = @ELABINELAB@;
37 38 39 40 41 42 43 44

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/sbin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

45
use lib "@prefix@/lib";
46 47
use libdb;
use libtestbed;
48
use Node;
49

50 51 52 53 54 55 56 57
#
# PXE boot constants
#
my $PXEBOOTDIR	    = "/tftpboot";
my $PXELINUXPREFIX  = "$PXEBOOTDIR/pxelinux";
my $PXELINUXBOOT    = "pxelinux.0";
my $PXELINUXCONFIG  = "pxelinux.cfg";

58 59 60 61
# XXX hack for now to support gpxelinux as well
my $GPXELINUXPREFIX = "$PXEBOOTDIR/gpxelinux";
my $GPXELINUXBOOT   = "gpxelinux.0";

62
my $CRTLTAG	    = TBDB_IFACEROLE_CONTROL();
63
my $MNGMNTTAG	    = TBDB_IFACEROLE_MANAGEMENT();
64 65
my $DHCPD_CONF	    = "/usr/local/etc/dhcpd.conf";
my $DHCPD_TEMPLATE  = "/usr/local/etc/dhcpd.conf.template";
66
my $DHCPD_TAIL      = "/usr/local/etc/dhcpd.conf.tail";
67
my %servernodes	    = ();
68 69 70
my %dhcp_subbosses  = ();
my %tftp_subbosses  = ();
my %bootinfo_subbosses  = ();
71
my %singlectlnet    = ();
72 73
my $template        = $DHCPD_TEMPLATE;
my $outfile	    = "/tmp/dhcpd_makeconf.$$";
74
my $OUT		    = *STDOUT;
75 76 77
my %subboss_dhcp_servers;

sub RestartSubbossDhcp($$);
78 79
sub SetupPXEBoot($$$$);
sub ClearPXEBoot($$);
80

81
#
82 83
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
84
#
85 86 87 88 89 90
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"i"})) {
    $install = 1;
91

92 93 94 95 96
    # We don't want to run this script unless its the real version.
    if ($EUID != 0) {
	die("*** $0:\n".
	    "    Must be root! Maybe its a development version?\n");
    }
97 98 99
    if (defined($options{"r"})) {
	$restart = 1;
    }
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
}
if (defined($options{"h"})) {
    usage();
}
if (defined($options{"v"})) {
    $vnames = 1;
}
if (defined($options{"t"})) {
    $template = $options{"t"};

    #
    # Untaint argument; Allow slash.
    #
    if ($template =~ /^([-\w\.\/]+)$/) {
	$template = $1;
    }
    else {
	die("Tainted template name: $template\n");
    }
}
120

121
#
122
# If we are going to actually install this file, must serialize to
123
# avoid a trashed config file.
124
#
125
if ($install) {
126 127 128 129
    if ((my $locked = TBScriptLock("dhcpd.conf", 1)) != TBSCRIPTLOCK_OKAY()) {
	exit(0)
	    if ($locked == TBSCRIPTLOCK_IGNORE);
	fatal("Could not get the lock after a long time!\n");
130
    }
131

132 133
    #
    # Open temporary output file.
134
    #
135 136 137 138
    open(OF, ">$outfile") or
	fatal("Could not open $outfile\n");
    $OUT = *OF;
}
139

140 141 142 143 144 145 146 147 148 149 150 151 152
#
# Locate all the "alternate server" nodes (inner elab boss nodes or
# inner plab PLC nodes).  We do this now rather than in the per-nodetype
# query below because the server may not be of the same type as the nodes
# they serve!
#
my $query_result =
    DBQueryWarn("select r.node_id,i.IP,r.pid,r.eid ".
		"from reserved as r ".
                "left join interfaces as i on ".
                "     r.node_id=i.node_id ".
                "where (r.inner_elab_role='boss' or ".
		"       r.inner_elab_role='boss+router' or ".
153
		"       r.inner_elab_role='boss+fs+router' or ".
154 155 156 157 158 159 160
		"       r.plab_role='plc') and ".
		"      i.role='$CRTLTAG' ");
if (! $query_result) {
    fatal("Could not dhcpd data from DB!");
}
while (my %row = $query_result->fetchhash()) {
    if (defined($row{"pid"}) && defined($row{"eid"})) {
161 162 163
	my $pid = $row{"pid"};
	my $eid = $row{"eid"};
	my $tag = "${pid}:${eid}";
164

165
	$servernodes{$tag} = $row{"IP"};
166 167 168 169 170 171 172 173 174 175 176 177 178

	#
	# Need to know if this is a single or dual control network model.
	#
	my $exp_result =
	    DBQueryFatal("select elabinelab_singlenet from experiments ".
			 "where pid='$pid' and eid='$eid'");
	if ($exp_result->num_rows) {
	    $singlectlnet{$tag} = ($exp_result->fetchrow_array())[0];
	}
	else {
	    $singlectlnet{$tag} = 0;
	}
179 180 181
    }
}

182 183 184 185 186 187
# Slurp in all of the subboss data to know A) if we should serve the DHCP
# lease to a given node, or if the next-server field should be something
# other than the IP for boss.
$query_result =
    DBQueryWarn("select s.node_id, s.service, s.subboss_id, i.IP ".
		"from subbosses as s left join interfaces as i on ".
188
		"s.subboss_id=i.node_id where i.role='$CRTLTAG' and s.disabled=0");
189 190 191 192 193 194
if (! $query_result) {
    fatal("Could not dhcpd data from DB!");
}
while (my %row = $query_result->fetchhash()) {
    my $node_id = $row{"node_id"};

195 196 197 198 199 200 201
    # We need to try restarting dhcpd on *all* subbosses, just in case
    # we've moved all dhcp nodes from one subboss to another.
    # Otherwise the old server wouldn't get restarted and both the old
    # and new servers would attempt to respond to dhcp requests.

    $subboss_dhcp_servers{$row{"subboss_id"}} = 1;

202 203 204 205 206 207 208 209 210
    if ($row{"service"} eq 'tftp') {
	    $tftp_subbosses{$node_id} = $row{"IP"};
    } elsif ($row{"service"} eq 'dhcp') {
	    $dhcp_subbosses{$node_id} = $row{"IP"};
    } elsif ($row{"service"} eq 'bootinfo') {
	    $bootinfo_subbosses{$node_id} = $row{"IP"};
    }
}

211 212
open(IF,"<$template") or
    fatal("Unable to open $template for reading");
213
while (<IF>) {
214 215 216 217 218
	if (/^(\s*)range\s*;/) {
		# Comment out a null DHCPD_DYNRANGE line.
		my $spaces = $1;
		print $OUT "${spaces}#range ... ...;\n";
	} elsif (/^(\s*)\%\%nodetype=(\w+)/) {
219 220
		my $spaces = $1;
		my $nodetype = $2;
221 222

		$query_result =
223 224
		    DBQueryWarn("select n.node_id,n.type, ".
				"       n.pxe_boot_path,n.next_pxe_boot_path,".
225 226
				"       i.IP,i.MAC,r.pid,r.eid,r.vname, ".
				"       r.inner_elab_role,r.inner_elab_boot, ".
227
				"       r.plab_role,r.plab_boot,i.role ".
228 229 230 231 232 233 234 235
				"from nodes as n ".
				"left join interfaces as i on ".
				"     n.node_id=i.node_id ".
				"left join node_types as t on n.type=t.type ".
				"left join reserved as r on ".
				"     n.node_id=r.node_id ".
				"where (n.type='$nodetype' or ".
				"       t.class='$nodetype') and ".
236 237 238
				"      (i.role='$CRTLTAG' or ".
				"       (i.role='$MNGMNTTAG' and ".
				"        t.isremotenode=0)) ".
239 240 241
				"order BY n.priority");
		if (! $query_result) {
		    fatal("Could not dhcpd data from DB!");
242
		}
243 244 245 246

		while (my %row = $query_result->fetchhash()) {
		    my $ip  = $row{"IP"};
		    my $mac = $row{"MAC"};
247
		    my $role = $row{"role"};
248 249
		    my $node_id;
		    my $next_server = "";
250
		    my $bootinfo_server = "";
251
		    my $hostname = "";
252
		    my $dns = "";
253
		    my $booting = "";
254
		    my $filename = "";
255 256 257 258 259 260 261

		    if ($vnames && defined($row{"vname"})) {
			$node_id = $row{"vname"};
		    }
		    else {
			$node_id = $row{"node_id"};
		    }
262 263 264 265 266 267 268
		    
		    # Management ports, nothing special to do.
		    if ($role eq TBDB_IFACEROLE_MANAGEMENT()) {
			$hostname =
			    "${spaces}\toption host-name \"${node_id}-mng\";\n";
			goto spit;
		    }
269

270 271 272 273 274 275
		    my $tag;
		    if (defined($row{"pid"})) {
			$tag = $row{"pid"} . ":" . $row{"eid"};
		    }

		    if (defined($tag) && defined($servernodes{$tag}) &&
276 277 278 279 280 281
			(($row{"inner_elab_boot"} == 1 &&
			  defined($row{"inner_elab_role"}) &&
			  $row{"inner_elab_role"} eq "node") ||
			 ($row{"plab_boot"} == 1 &&
			  defined($row{"plab_role"}) &&
			  $row{"plab_role"} eq "node"))) {
282

Mike Hibler's avatar
Mike Hibler committed
283 284 285 286 287 288 289 290 291 292
			#
			# XXX it is not yet completely clear what all we
			# need to do, or not do, for plab nodes.
			#
			if ($row{"plab_boot"} == 1) {
			    $hostname =
				"${spaces}\toption host-name \"$node_id\";\n";
			    $next_server = "${spaces}\tnext-server " .
				$servernodes{$tag} . ";\n";
			} else {
293 294 295 296 297 298 299 300 301 302 303
			    if ($singlectlnet{$tag}) {
				$hostname = "${spaces}\toption host-name ".
				    "\"$node_id\";\n";
				$booting  = "${spaces}\tignore booting;\n";
			    }
			    else {
				$next_server = "${spaces}\tnext-server " .
				    $servernodes{$tag} . ";\n";
				$dns = "${spaces}\toption ".
				    "domain-name-servers 1.1.1.1;\n";
			    }
304
			}
305
		    }
306 307 308 309 310
		    elsif (defined $dhcp_subbosses{$node_id}) {
			$hostname =
			    "${spaces}\toption host-name \"$node_id\";\n";
	                $booting = "${spaces}\tignore booting;\n";
		    }
311 312 313
		    else {
			$hostname =
			    "${spaces}\toption host-name \"$node_id\";\n";
314

315 316 317 318
		        if (defined $tftp_subbosses{$node_id}) {
			    $next_server = "${spaces}\tnext-server " .
			        $tftp_subbosses{$node_id} . ";\n";
		        }
319

320 321 322 323
		        if (defined $bootinfo_subbosses{$node_id}) {
			    $bootinfo_server = "${spaces}\toption PXE.emulab-bootinfo " .
			        $bootinfo_subbosses{$node_id} . ";\n";
		        }
324

325
		    }
326

327 328
		    #
		    # Handle alternate boot program filename if it exists.
329 330 331 332 333 334 335
		    # Order is:
		    #
		    # 1. nodes.next_pxe_boot_path for node
		    # 2. nodes.pxe_boot_path for node
		    # 3. "pxe_boot_path" node_attribute for node
		    # 4. "pxe_boot_path" node_type_attribute for node type
		    # 5. don't set (i.e., use the dhcpd.conf global default).
336
		    #
337 338 339 340 341
		    my $pxeboot = $row{"next_pxe_boot_path"};
		    if (!$pxeboot) {
			$pxeboot = $row{"pxe_boot_path"};
		    }
		    $filename = SetupPXEBoot($node_id, $mac, 1, $pxeboot);
342
		    if (!$filename) {
343 344 345 346
			# Get the node or node type default
			my $nobj = Node->Lookup($node_id);
			if (!$nobj) {
			    fatal("Could not find Node info for $node_id");
347
			}
348 349
			my $path = $nobj->default_pxeboot();
			$filename = SetupPXEBoot($node_id, $mac, 0, $path);
350 351 352
		    }
		    if ($filename) {
			$filename = "${spaces}\tfilename \"$filename\";\n";
353
		    }
354
		  spit:
355 356 357 358
		    # Need to make MAC look right..
		    $mac =~ s/(..)\B/$1:/g;

		    print $OUT "${spaces}host $ip {\n";
359 360
		    print $OUT $filename
			if (defined($filename));
361
		    print $OUT $next_server;
362
		    print $OUT $bootinfo_server;
363
		    print $OUT $dns;
364
		    print $OUT $booting;
365 366 367 368
		    print $OUT "${spaces}\thardware ethernet $mac;\n";
		    print $OUT $hostname;
		    print $OUT "${spaces}\tfixed-address $ip;\n";
		    print $OUT "${spaces}}\n\n";
369 370
		}
	} else {
371 372
	    # It's a regular line
	    print $OUT $_;
373 374
	}
}
375
close(IF);
376 377 378 379 380

if ($install) {
    close(OF) or
	fatal("Could not close $outfile");

381 382 383 384 385
    if (-e $DHCPD_TAIL) {
	system("cat $DHCPD_TAIL >> $outfile") == 0 or
	    fatal("Could not add tail to $outfile");
    }

386 387 388 389 390 391
    if (-e $DHCPD_CONF) {
	system("cp -fp $DHCPD_CONF ${DHCPD_CONF}.old") == 0 or
	    fatal("Could not backup copy of ${DHCPD_CONF}");
    }
    system("mv -f $outfile $DHCPD_CONF") == 0 or
	    fatal("Could not install new ${DHCPD_CONF}");
392 393 394 395 396 397 398 399 400 401 402 403 404 405

    if ($restart) {
	$dpid = `cat /var/run/dhcpd.pid`;
	chomp($dpid);
        # untaint
	if ($dpid =~ /^([\d]+)$/) {
	    $dpid = $1;
	}
	else {
	    fatal("Bad pid for DHCPD: $dpid");
	}
	if (kill('TERM', $dpid) == 0) {
	    fatal("Could not kill(TERM) process $dpid (dhcpd): $!");
	}
406

407 408
        my $old_uid = $UID;
        $UID = $EUID;
409 410 411
        for my $subboss (keys %subboss_dhcp_servers) {
            RestartSubbossDhcp($subboss, $restart);
        }
412
        $UID = $old_uid;
413 414
    }

415
    TBScriptUnlock();
416
}
417
exit(0);
418

419 420
#
# Special handling of pxe_boot_path argument.
421
#
422
# Any specified pxeboot path must start with PXEBOOTDIR (/tftpboot).
423 424 425 426 427 428
# If path starts with $PXELINUXPREFIX (/tftpboot/pxelinux/) or
# $GPXELINUXPREFIX (/tftpboot/gpxelinux), then the remainder of the
# path identifies the pxelinux configuration file from $PXELINUXCONFIG
# (/tftpboot/pxelinux.cfg) to use. This config file for the node
# (MAC address) will be symlinked to this config file. The PXE boot
# program will be set to either $PXELINUXBOOT or $GPXELINUXBOOT.
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
#
# Returns the string to be used for the "filename" option in dhcpd.conf.
#
sub SetupPXEBoot($$$$)
{
    my ($node, $mac, $clear, $str) = @_;

    # get rid of any old pxelinux magic
    if ($clear) {
	ClearPXEBoot($node, $mac);
    }

    return undef
	if (!defined($str));

    # don't allow if outside TFTP directory
    if ($str !~ /^$PXEBOOTDIR\// || $str =~ /\.\./) {
	print STDERR "$node: ignoring bogus pxe_boot_path '$str'\n";
	return undef;
    }

    # if it starts with the magic pxelinux prefix, setup a config file
451 452 453
    if ($str =~ /^($PXELINUXPREFIX|$GPXELINUXPREFIX)\/(.*)$/) {
	my $path = $1;
	my $cfile = $2;
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 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
	my $cpath = "$PXEBOOTDIR/$PXELINUXCONFIG";

	if (! -r "$cpath/$cfile") {
	    print STDERR "$node: ignoring invalid pxelinux config '$cfile'\n";
	    return undef;
	}

	#
	# XXX ugh. In an inner elab with an inner control network,
	# pxelinux will use the MAC address of the real control net interface
	# to construct its config file name. So we need to look that up.
	#
	if ($ELABINELAB) {
	    my $qr = DBQueryWarn("select MAC from interfaces where ".
				 " node_id='$node' and role='outer_ctrl'");
	    if ($qr && $qr->numrows) {
		my %row = $qr->fetchhash();
		if (defined($row{"MAC"})) {
		    $mac = $row{"MAC"};
		}
	    }
	}

	if ($mac =~ /^(..)(..)(..)(..)(..)(..)$/) {
	    $macname = "01-$1-$2-$3-$4-$5-$6";
	} else {
	    print STDERR "$node: ignoring unparsable MAC address '$mac'\n";
	    return undef;
	}

	if ($install) {
	    if (-e "$cpath/$macname") {
		if (!unlink("$cpath/$macname")) {
		    print STDERR "$node: could not remove old pxelinux config\n";
		    return undef;
		}
	    }
	    if (!symlink($cfile, "$cpath/$macname")) {
		print STDERR "$node: could not symlink to pxelinux config '$cfile'\n";
		return undef;
	    }
	} else {
	    print STDERR "WARNING: not changing pxelinux config for $node\n";
	}

	# return the pxelinux binary
500 501 502 503 504
	if ($path eq $PXELINUXPREFIX) {
	    $str = "$PXEBOOTDIR/$PXELINUXBOOT";
	} else {
	    $str = "$PXEBOOTDIR/$GPXELINUXBOOT";
	}
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 543 544 545
    }

    return $str;
}

#
# Make sure there is no pxelinux config for the given node
#
sub ClearPXEBoot($$)
{
    my ($node, $mac) = @_;
    my $cpath = "$PXEBOOTDIR/$PXELINUXCONFIG";

    #
    # XXX ugh. In an inner elab with an inner control network,
    # pxelinux will use the MAC address of the real control net interface
    # to construct its config file name. So we need to look that up.
    #
    if ($ELABINELAB) {
	my $qr = DBQueryWarn("select MAC from interfaces where ".
			     " node_id='$node' and role='outer_ctrl'");
	if ($qr && $qr->numrows) {
	    my %row = $qr->fetchhash();
	    if (defined($row{"MAC"})) {
		$mac = $row{"MAC"};
	    }
	}
    }

    if ($mac =~ /^(..)(..)(..)(..)(..)(..)$/) {
	$macname = "01-$1-$2-$3-$4-$5-$6";
	if ($install) {
	    if (-e "$cpath/$macname" && !unlink("$cpath/$macname")) {
		print STDERR "$node: could not remove old pxelinux config\n";
	    }
	} else {
	    print STDERR "WARNING: not changing pxelinux config for $node\n";
	}
    }
}

546 547 548 549 550
#
# Die.
#
sub fatal {
    my $msg = $_[0];
551

552 553
    TBScriptUnlock()
	if ($install);
554

555 556
    die("*** $0:\n".
	"    $msg\n");
557
}
558

559 560 561
sub RestartSubbossDhcp($$)
{
        my ($subboss, $restart) = @_;
562
        
563
        my $cmd = "ssh $subboss @prefix@/sbin/subboss_dhcpd_makeconf";
564 565 566 567 568 569 570 571

        $cmd .= " -r" if ($restart);

        print "Restarting dhcpd on subboss $subboss\n";
        if (system($cmd)) {
	    print STDERR "Failed to restart dhcpd on $subboss\n";
	}
}