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