named_setup.in 12.3 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2
3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2011 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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
my $domx = 0;
50
51
my @row;

52
53
use strict;

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

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

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

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

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

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

89
#
90
# We need to serialize this script to avoid a trashed map file.
91
#
92
93
94
95
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");
96

97
98
99
}

#
100
# Grab the list of all nodes, including virtual and widearea nodes
101
#
102
my $db_result =
103
104
105
106
    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 ".
107
108
		 "where (n.node_id=i.node_id and n.role='testnode' or ".
		 "       n.phys_nodeid=i.node_id and n.role='virtnode') ".
109
		 "    and (i.IP is not null or n.jailip is not null) ".
110
		 "    and (i.card is null or ".
111
		 "         i.role='" . TBDB_IFACEROLE_CONTROL() . "')");
112

113
my %routable;
114
115
my %unroutable;
my %reverse;
116

117
process_nodes($db_result);
118

119
120
121
122
#
# For IXPs we also need their gateway addresses as well
#
$db_result =
123
124
    DBQueryFatal("select n.node_id, n.role, n.jailip, i.IP, i.role, null ".
		 "  from nodes as n ".
125
126
127
128
129
130
131
		 "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);
132

133
134
135
136
137
138
139
140
141
142
143
144
145
# Get the v2pmap table since that holds the additional name mappings.
my %p2vmap = ();
$db_result =
    DBQueryFatal("select v.vname,v.node_id from reserved as r ".
                 "left join v2pmap as v on v.node_id=r.node_id and ".
                 "     v.exptidx=r.exptidx and v.vname!=r.vname ".
                 "where v.vname is not null");
while (my ($vname,$node_id) = $db_result->fetchrow_array()) {
    $p2vmap{$node_id} = []
        if (!exists($p2vmap{$node_id}));
    push(@{ $p2vmap{$node_id} }, $vname);
}

146
#
147
# Get the list of currently-reserved nodes so that we can make CNAMEs for them
148
#
149
$db_result =
150
    DBQueryFatal("select node_id,pid,eid,vname,inner_elab_role from reserved");
151

152
my %cnames;
153
while (my ($node_id,$pid,$eid,$vname,$erole) = $db_result->fetchrow_array()) {
154

155
156
157
158
159
160
    #
    # Handle some rare cases where a node can get reserved without a vname -
    # such as calling nalloc directly
    #
    if (!defined($vname)) {
	$vname = $node_id;
161
    }
162
    push @{$cnames{$node_id}}, "$vname.$eid.$pid";
163
164
165
166

    #
    # Special case for inner elab boss; add CNAME for www.
    #
167
    if (defined($erole) && $erole =~ /boss/) {
168
169
        push @{$cnames{$node_id}}, "www.$eid.$pid";
    }
170
171
172
173
174
175
176
    #
    # Special case for inner elab ops; add CNAME for event-server.
    #
    if (defined($erole) &&
        ($erole eq "ops" || $erole eq "ops+fs")) {
        push @{$cnames{$node_id}}, "event-server.$eid.$pid";
    }
177

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    #
    # And add additional names in v2pmap, which can happen for delay and
    # bridge nodes.
    #
    if (exists($p2vmap{$node_id})) {
        my @extras = @{ $p2vmap{$node_id} };

	foreach my $extra (@extras) {
            next
		if ($extra eq $vname);

	    push @{$cnames{$node_id}}, "$extra.$eid.$pid";
	}
    }
}
193
194

#
195
# Make the zone file for routable IP addresses
196
#
197
198
make_forward_zonefile($mapfiletail,\%routable,\%cnames);
assemble_zonefile($mapfile);
199

200
#
201
202
# Make the zone file that includes both routable and unroutable IP addresses,
# if the site has a .head file for it
203
204
#
if (-e $mapfile_internal_head) {
205
206
207
    make_forward_zonefile($mapfile_internal_tail,
	{%routable, %unroutable},\%cnames);
    assemble_zonefile($mapfile_internal);
208
}
209

210

211
212
213
214
215
#
# 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)) {
216
    if ($dirent !~ /((\d+\.\d+\.\d+).*\.db)\.head/) {
217
218
219
220
221
222
223
	next;
    }
    my $subnet = $2;
    my $basename = $1;

    my $filename = "$reversedir/$basename.tail";
    open MAP, ">$filename" || fatal("Couldn't open $filename: $!\n");
224
225
226
227
228
    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";
	}
229
230
231
    }
    close MAP;

232
    assemble_zonefile("$reversedir/$basename");
233
234
235
236
    
}
closedir DIR;

237
#
238
# Get the nameserver to reload the zone files.
239
240
241
# This is better than HUPing the nameserver directly. Notet that we look
# for a local port of named first.
#
242
243
244
245
246
247
248
249
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");
    }
250
}
251
252
TBScriptUnlock();
exit(0);
253

254
255
256
257
258
259
260
261
262
263
264
#
# 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];
265
	my $inner_elab_role = $row[5];
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292

	#
	# 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,
293
294
	    role => $nrole,
	    inner_elab_role => $inner_elab_role
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
	};

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

320
321
322
#
# Die and tell someone about it
#
323
sub fatal {
324
    my $msg = $_[0];
325

326
    TBScriptUnlock();
327
    SENDMAIL($TBOPS, "Named Setup Failed", $msg);
328
329
    die($msg);
}
330
331

#
332
# Put together a zone file from its consituent head and tail pieces
333
#
334
335
sub assemble_zonefile($) {
    my ($mapfile) = @_;
336
337

    my $mapfileback = "$mapfile.backup";
338
339
    my $mapfilehead = "$mapfile.head";
    my $mapfiletail = "$mapfile.tail";
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357

    #
    # 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".
358
    "; Edit the \"head\" file, then run ${TB}/bin/named_setup.\n".
359
360
361
362
363
364
365
366
367
368
    "; ******************************************************************\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 ) {
369
370
371
	    my $serial = `date +%s`;
	    chomp($serial);
	    $serial = $serial | 0x70000000;
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387

	    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");
}
388

389
390
391
392
393
394
395
396
397
398
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];
}

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#
# 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";
419
420
421
422
423
424
425
    my @list = keys(%$addresses);
    if ($sortem) {
	$laddrs = $addresses;
	@list = sort byip @list;
    }
    for my $node_id (@list) {
	my $node_rec = $$addresses{$node_id};
426
427
428
429
430
431
432
433
434
435

	#
	# 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";
436
437
438
439
440
441
442
443
444
	if ($domx) {
	    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";
	    }
445
	}
446
447
448
449
450
451
452
453
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
    }

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

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