named_setup.in 11 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh Stoller's avatar
Leigh Stoller committed
2 3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2008 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh Stoller committed
5 6
# All rights reserved.
#
7
use English;
8
use Socket;
9
use strict;
10 11 12 13

#
# Suck out virtual names and create CNAME map entries.
#
14 15
# This script always does the right thing, so it does not matter who calls it. 
#
16
# usage: named_setup [-norestart]
17 18
#

19 20 21 22 23 24 25
#
# Function phototypes
#

sub assemble_zonefile($);
sub make_forward_zonefile($$$);
sub isroutable($);
26
sub process_nodes($);
27

28 29 30 31
#
# Configure variables
#
my $TB		= "@prefix@";
32
my $TBOPS       = "@TBOPSEMAIL@";
33
my $USERS	= "@USERNODE@";
34
my $DISABLED    = "@DISABLE_NAMED_SETUP@";
35
my $OURDOMAIN   = "@OURDOMAIN@";
36

Leigh Stoller's avatar
Leigh Stoller committed
37
my $mapdir			= "/etc/namedb";
38 39 40 41
my $mapfile			= "$mapdir/${OURDOMAIN}.db";
my $mapfiletail			= "$mapfile.tail";
my $mapfile_internal		= "$mapdir/${OURDOMAIN}.internal.db";
my $mapfile_internal_head	= "$mapfile_internal.head";
42
my $mapfile_internal_tail	= "$mapfile_internal.tail";
43 44 45
my $vnodesfile			= "$mapdir/vnodes.${OURDOMAIN}.db";
my $vnodesback 			= "$mapdir/vnodes.${OURDOMAIN}.db.backup";
my $reversedir			= "$mapdir/reverse";
46
my $restart_named		= 1;
47
my $sortem			= 0; # set to 1 to generated IP-sorted file
48
my $dbg	= 0;
49 50
my @row;

51 52
use strict;

53
# If we are disabled, just quietly exit
54 55 56 57
if ($DISABLED) {
    exit 0;
}

58
# We do not want to run this script unless its the real version.
59
if ($EUID != 0) {
60 61
    die("*** $0:\n".
	"    Must be root! Maybe its a development version?\n");
62 63
}
# XXX Hacky!
64
if (0 && $TB ne "/usr/testbed") {
65 66
    die("*** $0:\n".
	"    Wrong version. Maybe its a development version?\n");
67 68
}

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

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

76
# Testbed Support libraries
77 78 79
use lib "@prefix@/lib";
use libtestbed;
use libdb;
80

81 82 83 84 85 86 87
#
# Check for norestart option.
#
if (@ARGV && $ARGV[0] eq "-norestart") {
    $restart_named = 0;
}

88
#
89
# We need to serialize this script to avoid a trashed map file.
90
#
91 92 93 94
if ((my $locked = TBScriptLock("named", 1)) != TBSCRIPTLOCK_OKAY()) {
    exit(0)
        if ($locked == TBSCRIPTLOCK_IGNORE);
    fatal("Could not get the lock after a long time!\n");
95 96 97
}

#
98
# Grab the list of all nodes, including virtual and widearea nodes
99
#
100
my $db_result =
101 102 103 104
    DBQueryFatal("select n.node_id, n.role, n.jailip, i.IP, i.role, ".
                 "    r.inner_elab_role ".
		 "  from nodes as n join interfaces as i ".
		 "left join reserved as r on r.node_id=n.node_id ".
105 106
		 "where (n.node_id=i.node_id and n.role='testnode' or ".
		 "       n.phys_nodeid=i.node_id and n.role='virtnode') ".
107
		 "    and (i.IP is not null or n.jailip is not null) ".
108
		 "    and (i.card is null or ".
109
		 "         i.role='" . TBDB_IFACEROLE_CONTROL() . "')");
110

111
my %routable;
112 113
my %unroutable;
my %reverse;
114

115
process_nodes($db_result);
116

117 118 119 120
#
# For IXPs we also need their gateway addresses as well
#
$db_result =
121 122
    DBQueryFatal("select n.node_id, n.role, n.jailip, i.IP, i.role, null ".
		 "  from nodes as n ".
123 124 125 126 127 128 129
		 "left join interfaces as i ".
		 "on n.phys_nodeid=i.node_id and n.node_id!=i.node_id ". 
		 "where n.role='testnode' ".
		 "    and (i.IP is not null or n.jailip is not null) ".
		 "    and (i.card is null or ".
		 "         i.role='" . TBDB_IFACEROLE_GW() . "') ");
process_nodes($db_result);
130 131

#
132
# Get the list of currently-reserved nodes so that we can make CNAMEs for them
133
#
134
$db_result =
135
    DBQueryFatal("select node_id,pid,eid,vname from reserved");
136

137 138
my %cnames;
while (my ($node_id,$pid,$eid,$vname) = $db_result->fetchrow_array()) {
139

140 141 142 143 144 145
    #
    # Handle some rare cases where a node can get reserved without a vname -
    # such as calling nalloc directly
    #
    if (!defined($vname)) {
	$vname = $node_id;
146
    }
147 148

    push @{$cnames{$node_id}}, "$vname.$eid.$pid";
149 150 151 152
}


#
153
# Make the zone file for routable IP addresses
154
#
155 156
make_forward_zonefile($mapfiletail,\%routable,\%cnames);
assemble_zonefile($mapfile);
157

158
#
159 160
# Make the zone file that includes both routable and unroutable IP addresses,
# if the site has a .head file for it
161 162
#
if (-e $mapfile_internal_head) {
163 164 165
    make_forward_zonefile($mapfile_internal_tail,
	{%routable, %unroutable},\%cnames);
    assemble_zonefile($mapfile_internal);
166
}
167

168

169 170 171 172 173
#
# Look for reverse zone files that we may need to make
#
opendir(DIR,$reversedir) or fatal("Unable to open directory $reversedir\n");
while (my $dirent = readdir(DIR)) {
174
    if ($dirent !~ /((\d+\.\d+\.\d+).*\.db)\.head/) {
175 176 177 178 179 180 181
	next;
    }
    my $subnet = $2;
    my $basename = $1;

    my $filename = "$reversedir/$basename.tail";
    open MAP, ">$filename" || fatal("Couldn't open $filename: $!\n");
182 183 184 185 186
    if ($reverse{$subnet}) {
	foreach my $aref (sort {$$a[0] <=> $$b[0]} @{$reverse{$subnet}}) {
	    my ($host, $name) = @$aref;
	    printf MAP "$host\tIN\tPTR\t$name.$OURDOMAIN.\n";
	}
187 188 189
    }
    close MAP;

190
    assemble_zonefile("$reversedir/$basename");
191 192 193 194
    
}
closedir DIR;

195
#
196
# Get the nameserver to reload the zone files.
197 198 199
# This is better than HUPing the nameserver directly. Notet that we look
# for a local port of named first.
#
200 201 202 203 204 205 206 207
if ($restart_named) {
    if (-x "/usr/local/sbin/rndc") {
	system("/usr/local/sbin/rndc reload > /dev/null") == 0 or
	    fatal("/usr/local/sbin/rndc reload failed!\n");
    } else {
	system("named.reload > /dev/null") == 0 or
	    fatal("named.reload failed!\n");
    }
208
}
209 210
TBScriptUnlock();
exit(0);
211

212 213 214 215 216 217 218 219 220 221 222
#
# Sort out the routable and unroutable addresses from a DB query,
# and make a map for reversing them
#
sub process_nodes($) {
    while (my @row = $db_result->fetchrow_array()) {
	my $node_id = $row[0];
	my $nrole   = $row[1];
	my $jailIP  = $row[2];
	my $IP      = $row[3];
	my $irole   = $row[4];
223
	my $inner_elab_role = $row[5];
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

	#
	# For most nodes, we get the IP address from the interfaces table;
	# but, for virtual nodes, we get it from the jailip column
	#
	if (defined($jailIP)) {
	    $IP = $jailIP;
	}
	if (!$IP) {
	    warn "named_setup: No IP for node $node_id!\n";
	    next;
	}

	#
	# Special treatment for gateway interfaces - we give act as if they
	# are a separate node
	#
	if ($irole && $irole eq TBDB_IFACEROLE_GW()) {
	    $node_id = "$node_id-gw";
	}

	#
	# Make a little structure so that we can make decisions later about
	# this node (ie. handling virt nodes differently)
	#
	my $node_rec = {
	    IP   => $IP,
251 252
	    role => $nrole,
	    inner_elab_role => $inner_elab_role
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	};

	#
	# Sort it into the right pile based on whether or not it's routable
	#
	if (isroutable($IP)) {
	    $routable{$node_id} = $node_rec;
	} else {
	    $unroutable{$node_id} = $node_rec;
	}

	#
	# Put it into a map so we can generate the reverse zone file later
	#
	$IP =~ /(\d+\.\d+\.\d+)\.(\d+)/;
	if ($1 && $2) {
	    my $subnet = $1;
	    my $host = $2;
	    push @{$reverse{$subnet}}, [$host, $node_id];
	} else {
	    warn "Poorly formed IP address $IP\n";
	}
    }
}

278 279 280
#
# Die and tell someone about it
#
281
sub fatal {
282
    my $msg = $_[0];
283

284
    TBScriptUnlock();
285
    SENDMAIL($TBOPS, "Named Setup Failed", $msg);
286 287
    die($msg);
}
288 289

#
290
# Put together a zone file from its consituent head and tail pieces
291
#
292 293
sub assemble_zonefile($) {
    my ($mapfile) = @_;
294 295

    my $mapfileback = "$mapfile.backup";
296 297
    my $mapfilehead = "$mapfile.head";
    my $mapfiletail = "$mapfile.tail";
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

    #
    # Concat the head and tail files to create the new map.
    #
    if (-e $mapfile) {
	system("mv -f $mapfile $mapfileback") == 0 or
	fatal("Could not back up $mapfile to $mapfileback\n");
    }

    #
    # Generate a warning so that no one tries to edit the file by hand
    #
    open(MAP, ">$mapfile") || fatal("Couldn't open $mapfile\n");
    print MAP
    ";\n".
    "; ******************************************************************\n".
    "; DO NOT EDIT THIS FILE. IT IS A CREATION, A FIGMENT, A CONTRIVANCE!\n".
    ";\n".
    "; Edit the \"head\" file, then run ${TB}bin/named_setup.\n".
    "; ******************************************************************\n".
    ";\n";

    #
    # Now copy in the head part of the map, looking for the serial
    # number so it can be bumped up.
    #
    open(MAPHEAD, "<$mapfilehead") || fatal("Couldn't open $mapfilehead\n");
    while (<MAPHEAD>) {
	if ( /;\s*Serial\s+/i ) {
	    my $serial = `date +%s`;
	    chop $serial;

	    print MAP "\t\t\t$serial\t; Serial Number -- DO NOT EDIT\n";
	}
	else {
	    print MAP "$_";
	}
    }
    close(MAPHEAD);
    close(MAP);

    #
    # Now the tail of the map.
    # 
    system("cat $mapfiletail >> $mapfile") == 0 or
    fatal("Failed to concat $mapfiletail to $mapfile\n");
}
345

346 347 348 349 350 351 352 353 354 355
my $laddrs;
sub byip {
    my @aa = split '\.', $$laddrs{$a}->{IP};
    my @bb = split '\.', $$laddrs{$b}->{IP};
    return $aa[0] <=> $bb[0] ||
	$aa[1] <=> $bb[1] ||
	    $aa[2] <=> $bb[2] ||
		$aa[3] <=> $bb[3];
}

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
#
# Make a forward zone file, from the given map of addresses and CNAMEs
#
sub make_forward_zonefile($$$) {
    my ($filename, $addresses, $cnames) = @_;
    open(MAP, ">$filename") || fatal("Couldn't open $filename\n");
    print MAP "\n";
    print MAP ";\n";
    print MAP "; DO NOT EDIT below this point. Auto generated map entries!\n";
    print MAP ";\n";
    print MAP "\n";

    #
    # Start out with the A records for the nodes
    #
    print MAP "\n";
    print MAP ";\n";
    print MAP "; Nodes\n";
    print MAP ";\n";
    print MAP "\n";
376 377 378 379 380 381 382
    my @list = keys(%$addresses);
    if ($sortem) {
	$laddrs = $addresses;
	@list = sort byip @list;
    }
    for my $node_id (@list) {
	my $node_rec = $$addresses{$node_id};
383 384 385 386 387 388 389 390 391 392

	#
	# Special treatment for virtual nodes - we only bother to print them
	# out if some has reserved them (ie. if they have a CNAME)
	#
	if (($node_rec->{role} eq "virtnode") && (!$cnames->{$node_id})) {
	    next;
	}

	print MAP "$node_id\tIN\tA\t$node_rec->{IP}\n";
393 394 395 396 397 398 399 400
	if (defined($node_rec->{inner_elab_role}) &&
	    ($node_rec->{inner_elab_role} eq "ops" ||
	     $node_rec->{inner_elab_role} eq "ops+fs")) {
	    print MAP "\tIN\tMX 10\t$node_id\n";
	}
	else {
	    print MAP "\tIN\tMX 10\t$USERS.\n";
	}
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    }

    #
    # Switch the TTL to 1 second for CNAMEs so that people will changes quickly
    # as experiments swap in and out
    #
    print MAP "\n";
    print MAP "\$TTL\t1\n\n";

    print MAP "\n";
    print MAP ";\n";
    print MAP "; CNAMEs for reserved nodes\n";
    print MAP ";\n";
    print MAP "\n";

    while (my ($pname, $vnames) = each %$cnames) {
	#
	# Only print out CNAMEs for nodes that are actually going into this map
	#
	next unless ($addresses->{$pname});

	#
	# Write out every CNAME for this pnode
	#
	foreach my $vname (@$vnames) {
	    my $formatted_vname = sprintf "%-50s", $vname;
	    print MAP "$formatted_vname\tIN\tCNAME\t$pname\n";
	}
    }

    print MAP "\n";
    close(MAP);
}

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
#
# Is an IP routable?
#
sub isroutable($)
{
    my ($IP)  = @_;
    my ($a,$b,$c,$d) = ($IP =~ /^(\d*)\.(\d*)\.(\d*)\.(\d*)/);

    #
    # These are unroutable:
    # 10.0.0.0        -   10.255.255.255  (10/8 prefix)
    # 172.16.0.0      -   172.31.255.255  (172.16/12 prefix)
    # 192.168.0.0     -   192.168.255.255 (192.168/16 prefix)
    #

    # Easy tests.
    return 0
	if (($a eq "10") ||
	    ($a eq "192" && $b eq "168"));

    # Lastly
    return 0
	if (inet_ntoa((inet_aton($IP) & inet_aton("255.240.0.0"))) eq
	    "172.16.0.0");

    return 1;
}