]> git.openstreetmap.org Git - dns.git/blob - bin/mkgeo
Add support for publishing DNS to Cloudflare
[dns.git] / bin / mkgeo
1 #!/usr/bin/perl
2
3 use v5.12;
4
5 use strict;
6 use warnings;
7
8 use IO::File;
9 use Math::Trig qw(deg2rad pip2 great_circle_distance);
10 use JSON::XS;
11 use LWP::UserAgent;
12 use YAML;
13
14 my $originfile = shift @ARGV;
15 my $clusterfile = shift @ARGV;
16 my $zone = shift @ARGV;
17 my $jszone = shift @ARGV;
18 my $targetoriginfile = shift @ARGV;
19 my $origins = YAML::LoadFile($originfile);
20 my $clusters = YAML::LoadFile($clusterfile);
21 my $gdnsname = shift @ARGV;
22 my @servers;
23
24 # Initialise cluster details
25 while (my($name,$cluster) = each %$clusters)
26 {
27     if ($cluster->{servers})
28     {
29         $cluster->{bandwidth} = 0;
30
31         foreach my $server (@{$cluster->{servers}})
32         {
33             $server->{cluster} = $cluster;
34             $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
35
36             push @servers, $server;
37         }
38     }
39     else
40     {
41         my $server = {
42             cluster => $cluster,
43             statuscake => $cluster->{statuscake},
44             bandwidth => $cluster->{bandwidth},
45             ipv4 => $cluster->{ipv4},
46             ipv6 => $cluster->{ipv6}
47         };
48
49         $cluster->{servers} = [ $server ];
50
51         push @servers, $server;
52     }
53
54     $cluster->{name} = $name;
55     $cluster->{status} = "down";
56 }
57
58 # Initialise server details
59 foreach my $server (@servers)
60 {
61     $server->{status} = "up";
62 }
63
64 # If statuscake support is enabled then check which servers are up
65 if ($ENV{STATUSCAKE_USERNAME} && $ENV{STATUSCAKE_APIKEY})
66 {
67     my $ua = LWP::UserAgent->new;
68     my $cache;
69
70     $ua->agent("mkgeo/1.0");
71     $ua->default_header("Username", $ENV{STATUSCAKE_USERNAME});
72     $ua->default_header("API", $ENV{STATUSCAKE_APIKEY});
73
74     if (-f "statuscake.yml")
75     {
76         $cache = YAML::LoadFile("statuscake.yml");
77     }
78     else
79     {
80         $cache = {};
81     }
82
83     my $response = $ua->get("https://app.statuscake.com/API/Tests/");
84
85     if ($response->is_success)
86     {
87         my $tests = decode_json($response->content);
88
89         foreach my $test (@$tests)
90         {
91             my $testid = $test->{TestID};
92
93             if ($test->{Status} eq "Up" && !$test->{Paused})
94             {
95                 $cache->{$testid} = "up";
96             }
97             else
98             {
99                 $cache->{$testid} = "down";
100             }
101         }
102     }
103
104     foreach my $server (@servers)
105     {
106         if (my $testids = $server->{statuscake})
107         {
108             $server->{status} = "up";
109
110             for my $testid (@$testids)
111             {
112                 my $testresult = $cache->{$testid} || "down";
113
114                 $server->{status} = "down" if $testresult eq "down";
115             }
116         }
117         else
118         {
119             $server->{status} = "down";
120         }
121     }
122
123     YAML::DumpFile("statuscake.yml", $cache);
124 }
125
126 # Mark a cluster as up if any servers are up
127 foreach my $server (@servers)
128 {
129     if ($server->{status} eq "up")
130     {
131         $server->{cluster}->{status} = "up";
132     }
133     else
134     {
135         $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
136     }
137 }
138
139 # Create target origins object
140 my $targetorigins = {};
141
142 # Initialise cluster details
143 while (my($name,$cluster) = each %$clusters)
144 {
145     $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
146     $cluster->{bandwidth_used} = 0;
147
148     $targetorigins->{$cluster->{name}} = {
149         code => $cluster->{name},
150         name => $cluster->{name},
151         lat => $cluster->{lat},
152         lon => $cluster->{lon},
153         bandwidth => 0
154     };
155 }
156
157 my @mappings = ();
158
159 # Scan origins and work out which clusters each can use
160 foreach my $origin (values %$origins)
161 {
162     foreach my $cluster (values %$clusters)
163     {
164         my $match = match_origin($cluster, $origin);
165
166         if ($cluster->{status} eq "up" && $match ne "denied")
167         {
168             my $priority = $match eq "preferred" ? 20 : 10;
169             my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
170
171             push @mappings, {
172                 origin => $origin, cluster => $cluster,
173                 priority => $priority, distance => $distance
174             };
175         }
176     }
177 }
178
179 # Allocate each country to a cluster
180 allocate_clusters(@mappings);
181
182 # If we failed to allocate every origin then loop, increasing
183 # the bandwidth for each cluster by a little and retrying until
184 # we manage to allocate everything
185 while (grep { !exists($_->{cluster}) } values %$origins)
186 {
187     # Clear any existing mappings of countries to clusters
188     foreach my $origin (values %$origins)
189     {
190         delete $origin->{cluster};
191     }
192
193     # Reset bandwidth usage for clusters and increase limits by 10%
194     foreach my $cluster (values %$clusters)
195     {
196         $cluster->{bandwidth_used} = 0;
197         $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
198     }
199
200     # Try the allocate again
201     allocate_clusters(@mappings);
202 }
203
204 # Create JSON collection object
205 my @json;
206
207 # Open output files
208 my $zonefile = IO::File->new("> data/${zone}") || die "$!";
209 my $jszonefile = IO::File->new("> include/${jszone}.js") || die "$!";
210 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
211
212 # Output headers
213 $jszonefile->print("var \U${jszone}\E_RECORDS = [\n");
214
215 # Output details for each country
216 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
217 {
218     my $cluster = $origin->{cluster};
219     my $clon = $origin->{lon};
220     my $clat = $origin->{lat};
221     my $slon = $cluster->{lon};
222     my $slat = $cluster->{lat};
223
224     if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
225     {
226         $slon = $slon + 360;
227     }
228     elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
229     {
230         $clon = $clon + 360;
231     }
232
233     $zonefile->print("# $origin->{name}\n");
234     $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
235
236     $jszonefile->print("  CNAME(\"\L$origin->{code}\E.${jszone}\", \"$cluster->{name}.${zone}.\", TTL(\"10m\")),\n");
237
238     push @json, {
239         type => "Feature",
240         geometry => {
241             type => "LineString",
242             coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
243         },
244         properties => {
245             origin => $origin->{name},
246             server => $cluster->{name},
247             colour => $cluster->{colour}
248         }
249     };
250
251     $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
252 }
253
254 # Header for default records
255 $zonefile->print("# Unknown origins\n");
256
257 # Output default records for IPs that can't be mapped to a country
258 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
259 {
260     my $name = $cluster->{name};
261
262     if (my $default = $cluster->{default})
263     {
264         output_server($zonefile, $jszonefile, "${default}.${zone}", "${default}.${jszone}", $cluster);
265     }
266     elsif (exists($cluster->{default}))
267     {
268         output_server($zonefile, $jszonefile, "${zone}", "${jszone}", $cluster);
269     }
270 }
271
272 # Header for underlying servers
273 $zonefile->print("# Servers\n");
274
275 # Output A records for each cluster
276 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
277 {
278     my $name = $cluster->{name};
279
280     output_server($zonefile, $jszonefile, "${name}.${zone}", "${name}.${jszone}", $cluster);
281
282     if (@{$cluster->{servers}} > 1)
283     {
284         output_server($zonefile, $jszonefile, "${name}-%02d.${zone}", "${name}-%02d.${jszone}", $cluster);
285     }
286 }
287
288 # Output the GeoJSON text
289 $jsonfile->print(encode_json(\@json));
290
291 # Output footers
292 $jszonefile->print("];\n");
293
294 # Close the output files
295 $jsonfile->close();
296 $jszonefile->close();
297 $zonefile->close();
298
299 # Output gdnsd configuration
300 if (defined($gdnsname))
301 {
302     my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
303     my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
304     my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
305     my $continent = "";
306
307     $gdnsmapfile->print("${gdnsname} => {\n");
308     $gdnsmapfile->print("  geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
309     $gdnsmapfile->print("  datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
310     $gdnsmapfile->print("  map => {\n");
311     $gdnsmapfile->print("    default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
312
313     foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
314     {
315         my $code = $origin->{code};
316         my $cluster = $origin->{cluster}->{name};
317
318         next if $code eq "XK";
319
320         if ($continent ne $origin->{continent})
321         {
322             $gdnsmapfile->print("    }\n") if $continent;
323
324             $continent = $origin->{continent};
325
326             $gdnsmapfile->print("    ${continent} => {\n");
327         }
328
329         $gdnsmapfile->print("      ${code} => [${cluster}]\n");
330     }
331
332     $gdnsmapfile->print("    }\n") if $continent;
333
334     $gdnsmapfile->print("  }\n");
335     $gdnsmapfile->print("}\n");
336
337     $gdnsresourcefile->print("${gdnsname} => {\n");
338     $gdnsresourcefile->print("  map => ${gdnsname}\n");
339     $gdnsresourcefile->print("  dcmap => {\n");
340
341     foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
342     {
343         my $name = $cluster->{name};
344
345         if (@{$cluster->{servers}} > 1)
346         {
347             $gdnsweightedfile->print("${name} => {\n");
348
349             while (my($index,$server) = each @{$cluster->{servers}})
350             {
351                 if ($server->{status} eq "up")
352                 {
353                     my $number = sprintf("%02d", $index + 1);
354                     my $bandwidth = $server->{bandwidth};
355
356                     $gdnsweightedfile->print("  ${name}-${number} = [ ${name}-${number}.${zone}., ${bandwidth} ]\n");
357                 }
358             }
359
360             $gdnsweightedfile->print("}\n");
361
362             $gdnsresourcefile->print("    ${name} => %weighted!${name}\n");
363         }
364         else
365         {
366             $gdnsresourcefile->print("    ${name} => ${name}.${zone}.\n");
367         }
368     }
369
370     $gdnsresourcefile->print("  }\n");
371     $gdnsresourcefile->print("}\n");
372
373     $gdnsweightedfile->close();
374     $gdnsresourcefile->close();
375     $gdnsmapfile->close();
376 }
377
378 # Output the target details in origin format if required
379 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
380
381 exit 0;
382
383 #
384 # Match an origin against a cluster
385 #
386 sub match_origin
387 {
388     my $cluster = shift;
389     my $origin = shift;
390     my $match;
391
392     if ($cluster->{preferred} &&
393         $cluster->{preferred}->{origins} &&
394         grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
395     {
396         $match = "preferred";
397     }
398     elsif ($cluster->{allowed} &&
399            $cluster->{allowed}->{origins} &&
400            grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
401     {
402         $match = "allowed";
403     }
404     elsif ($cluster->{preferred} &&
405            $cluster->{preferred}->{countries} &&
406            grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
407     {
408         $match = "preferred";
409     }
410     elsif ($cluster->{allowed} &&
411            $cluster->{allowed}->{countries} &&
412            grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
413     {
414         $match = "allowed";
415     }
416     elsif ($cluster->{denied} &&
417            $cluster->{denied}->{countries} &&
418            grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
419     {
420         $match = "denied";
421     }
422     elsif ($cluster->{preferred} &&
423            $cluster->{preferred}->{continents} &&
424            grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
425     {
426         $match = "preferred";
427     }
428     elsif ($cluster->{allowed} &&
429            $cluster->{allowed}->{continents} &&
430            grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
431     {
432         $match = "allowed";
433     }
434     elsif ($cluster->{denied} &&
435            $cluster->{denied}->{continents} &&
436            grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
437     {
438         $match = "denied";
439     }
440     elsif ($cluster->{allowed})
441     {
442         $match = "denied";
443     }
444     else
445     {
446         $match = "allowed";
447     }
448
449     return $match;
450 }
451
452 #
453 # Compute the great circle distance between two points
454 #
455 sub distance
456 {
457     my $lat1 = deg2rad(shift);
458     my $lon1 = deg2rad(shift);
459     my $lat2 = deg2rad(shift);
460     my $lon2 = deg2rad(shift);
461
462     return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
463 }
464
465 #
466 # Allocate each origin to a cluster
467 #
468 sub allocate_clusters
469 {
470     my @mappings = sort { compare_mappings($a, $b) } @_;
471
472     # Loop over the mappings, trying to assign each origin to the
473     # nearest cluster, but subject to the bandwidth limits
474     while (my $mapping = shift @mappings)
475     {
476         my @group;
477
478         push @group, $mapping;
479
480         while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
481         {
482             push @group, shift @mappings;
483         }
484
485         for my $mapping (sort compare_bandwidth @group)
486         {
487             my $origin = $mapping->{origin};
488             my $cluster = $mapping->{cluster};
489
490             if (!exists($origin->{cluster}) &&
491                 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
492             {
493                 $origin->{cluster} = $cluster;
494                 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
495             }
496         }
497     }
498
499     return;
500 }
501
502 #
503 # Compare two mappings to decide which to use
504 #
505 sub compare_mappings
506 {
507     my $a = shift;
508     my $b = shift;
509
510     return $b->{priority} <=> $a->{priority} ||
511            $a->{distance} <=> $b->{distance};
512 }
513
514 #
515 # Compare two mappings to decide which to try first
516 #
517 sub compare_bandwidth
518 {
519     my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
520     my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
521
522     return $a_used <=> $b_used;
523 }
524
525 #
526 # Output DNS records for a server
527 #
528 sub output_server
529 {
530     my $zonefile = shift;
531     my $jszonefile = shift;
532     my $name = shift;
533     my $jsname = shift;
534     my $cluster = shift;
535
536     while (my($index,$server) = each @{$cluster->{servers}})
537     {
538         if ($server->{status} eq "up")
539         {
540             $zonefile->printf("+${name}:$server->{ipv4}:600\n", $index + 1);
541             $jszonefile->printf("  A(\"${jsname}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
542
543             if ($server->{ipv6})
544             {
545                 my $ipv6 = $server->{ipv6};
546
547                 $ipv6 =~ s/([0-9a-f]{4})(?=.)/\1:/ig;
548
549                 $zonefile->printf("3${name}:$server->{ipv6}:600\n", $index + 1);
550                 $jszonefile->printf("  AAAA(\"${jsname}\", \"${ipv6}\", TTL(\"10m\")),\n", $index + 1);
551             }
552         }
553     }
554
555     return;
556 }