]> git.openstreetmap.org Git - dns.git/blob - bin/mkgeo
Add IPv6 address for kessie
[dns.git] / bin / mkgeo
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use IO::File;
7 use Math::Trig qw(deg2rad pip2 great_circle_distance);
8 use JSON::XS;
9 use LWP::UserAgent;
10 use YAML;
11
12 my $originfile = shift @ARGV;
13 my $clusterfile = shift @ARGV;
14 my $zone = shift @ARGV;
15 my $targetoriginfile = shift @ARGV;
16 my $origins = YAML::LoadFile($originfile);
17 my $clusters = YAML::LoadFile($clusterfile);
18 my @servers;
19
20 # Initialise cluster details
21 while (my($name,$cluster) = each %$clusters)
22 {
23     if ($cluster->{servers})
24     {
25         $cluster->{bandwidth} = 0;
26
27         foreach my $server (@{$cluster->{servers}})
28         {
29             $server->{cluster} = $cluster;
30             $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
31
32             push @servers, $server;
33         }
34     }
35     else
36     {
37         my $server = {
38             cluster => $cluster,
39             pingdom => $cluster->{pingdom},
40             bandwidth => $cluster->{bandwidth},
41             ipv4 => $cluster->{ipv4},
42             ipv6 => $cluster->{ipv6}
43         };
44
45         $cluster->{servers} = [ $server ];
46
47         push @servers, $server;
48     }
49
50     $cluster->{name} = $name;
51     $cluster->{status} = "down";
52 }
53
54 # Initialise server details
55 foreach my $server (@servers)
56 {
57     $server->{status} = "up";
58 }
59
60 # If pingdom support is enabled then check which servers are up
61 if ($ENV{PINGDOM_USERNAME} && $ENV{PINGDOM_PASSWORD})
62 {
63     my $ua = LWP::UserAgent->new;
64     my $cache;
65
66     $ua->timeout(5);
67     $ua->default_header("App-Key", "2cohi62u5haxvqmypk3ljqqrze1jufrh");
68     $ua->credentials("api.pingdom.com:443", "Pingdom API", $ENV{PINGDOM_USERNAME}, $ENV{PINGDOM_PASSWORD});
69
70     if (-f "pingdom.yml")
71     {
72         $cache = YAML::LoadFile("pingdom.yml"); 
73     }
74     else
75     {
76         $cache = {};
77     }
78
79     foreach my $server (@servers)
80     {
81         if (my $checkid = $server->{pingdom})
82         {
83             my $response = $ua->get("https://api.pingdom.com/api/2.0/checks/${checkid}");
84
85             if ($response->is_success)
86             {
87                 my $check = decode_json($response->content);
88
89                 $server->{status} = $check->{check}->{status};
90                 $cache->{$server->{pingdom}} = $check->{check}->{status};
91             }
92             else
93             {
94                 $server->{status} = $cache->{$server->{pingdom}} || "down";
95             }
96         }
97         else
98         {
99             $server->{status} = "down";
100         }
101     }
102
103     YAML::DumpFile("pingdom.yml", $cache);
104 }
105
106 # Mark a cluster as up if any servers are up
107 foreach my $server (@servers)
108 {
109     if ($server->{status} eq "up")
110     {
111         $server->{cluster}->{status} = "up";
112     }
113     else
114     {
115         $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
116     }
117 }
118
119 # Create target origins object
120 my $targetorigins = {};
121
122 # Initialise cluster details
123 while (my($name,$cluster) = each %$clusters)
124 {
125     $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
126     $cluster->{bandwidth_used} = 0;
127
128     $targetorigins->{$cluster->{name}} = {
129         code => $cluster->{name},
130         name => $cluster->{name},
131         lat => $cluster->{lat},
132         lon => $cluster->{lon},
133         bandwidth => 0
134     };
135 }
136
137 my @mappings = ();
138
139 # Scan origins and work out which clusters each can use
140 foreach my $origin (values %$origins)
141 {
142     foreach my $cluster (values %$clusters)
143     {
144         my $match = match_origin($cluster, $origin);
145
146         if ($cluster->{status} eq "up" && $match ne "denied")
147         {
148             my $priority = $match eq "preferred" ? 20 : 10;
149             my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
150
151             push @mappings, {
152                 origin => $origin, cluster => $cluster,
153                 priority => $priority, distance => $distance
154             };
155         }
156     }
157 }
158
159 # Allocate each country to a cluster
160 allocate_clusters(@mappings);
161
162 # If we failed to allocate every origin then loop, increasing
163 # the bandwidth for each cluster by a little and retrying until
164 # we manage to allocate everything
165 while (grep { !exists($_->{cluster}) } values %$origins)
166 {
167     # Clear any existing mappings of countries to clusters
168     foreach my $origin (values %$origins)
169     {
170         delete $origin->{cluster};
171     }
172
173     # Reset bandwidth usage for clusters and increase limits by 10%
174     foreach my $cluster (values %$clusters)
175     {
176         $cluster->{bandwidth_used} = 0;
177         $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
178     }
179
180     # Try the allocate again
181     allocate_clusters(@mappings);
182 }
183
184 # Create JSON collection object
185 my @json;
186
187 # Open output files
188 my $zonefile = IO::File->new("> data/${zone}") || die "$!";
189 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
190
191 # Output details for each country
192 foreach my $origin (values %$origins)
193 {
194     my $cluster = $origin->{cluster};
195     my $clon = $origin->{lon};
196     my $clat = $origin->{lat};
197     my $slon = $cluster->{lon};
198     my $slat = $cluster->{lat};
199
200     if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
201     {
202         $slon = $slon + 360;
203     }
204     elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
205     {
206         $clon = $clon + 360;
207     }
208
209     $zonefile->print("# $origin->{name}\n");
210     $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
211
212     push @json, {
213         type => "Feature",
214         geometry => {
215             type => "LineString",
216             coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
217         },
218         properties => {
219             origin => $origin->{name},
220             server => $cluster->{name},
221             colour => $cluster->{colour}
222         }
223     };
224
225     $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
226 }
227
228 # Header for default records
229 $zonefile->print("# Unknown origins\n");
230
231 # Output default records for IPs that can't be mapped to a country
232 while (my($name,$cluster) = each %$clusters)
233 {
234     if (my $default = $cluster->{default})
235     {
236         output_server($zonefile, "${default}.${zone}", $cluster);
237     }
238     elsif (exists($cluster->{default}))
239     {
240         output_server($zonefile, "${zone}", $cluster);
241     }
242 }
243
244 # Header for underlying servers
245 $zonefile->print("# Servers\n");
246
247 # Output A records for each cluster
248 while (my($name,$cluster) = each %$clusters)
249 {
250     output_server($zonefile, "${name}.${zone}", $cluster);
251 }
252
253 # Output the GeoJSON text
254 $jsonfile->print(encode_json(\@json));
255
256 # Close the output files
257 $jsonfile->close();
258 $zonefile->close();
259
260 # Output the target details in origin format if required
261 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
262
263 exit 0;
264
265 #
266 # Match an origin against a cluster
267 #
268 sub match_origin
269 {
270     my $cluster = shift;
271     my $origin = shift;
272     my $match;
273
274     if ($cluster->{preferred} &&
275         $cluster->{preferred}->{countries} &&
276         grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
277     {
278         $match = "preferred";
279     }
280     elsif ($cluster->{allowed} &&
281            $cluster->{allowed}->{countries} &&
282            grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
283     {
284         $match = "allowed";
285     }
286     elsif ($cluster->{denied} &&
287            $cluster->{denied}->{countries} &&
288            grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
289     {
290         $match = "denied";
291     }
292     elsif ($cluster->{preferred} &&
293            $cluster->{preferred}->{continents} &&
294            grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
295     {
296         $match = "preferred";
297     }
298     elsif ($cluster->{allowed} &&
299            $cluster->{allowed}->{continents} &&
300            grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
301     {
302         $match = "allowed";
303     }
304     elsif ($cluster->{denied} &&
305            $cluster->{denied}->{continents} &&
306            grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
307     {
308         $match = "denied";
309     }
310     elsif ($cluster->{allowed})
311     {
312         $match = "denied";
313     }
314     else
315     {
316         $match = "allowed";
317     }
318
319     return $match;
320 }
321
322 #
323 # Compute the great circle distance between two points
324 #
325 sub distance
326 {
327     my $lat1 = deg2rad(shift);
328     my $lon1 = deg2rad(shift);
329     my $lat2 = deg2rad(shift);
330     my $lon2 = deg2rad(shift);
331
332     return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
333 }
334
335 #
336 # Allocate each origin to a cluster
337 #
338 sub allocate_clusters
339 {
340     my @mappings = sort { compare_mappings($a, $b) } @_;
341
342     # Loop over the mappings, trying to assign each origin to the
343     # nearest cluster, but subject to the bandwidth limits
344     while (my $mapping = shift @mappings)
345     {
346         my @group;
347
348         push @group, $mapping;
349
350         while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
351         {
352             push @group, shift @mappings;
353         }
354
355         for my $mapping (sort compare_bandwidth @group)
356         {
357             my $origin = $mapping->{origin};
358             my $cluster = $mapping->{cluster};
359
360             if (!exists($origin->{cluster}) &&
361                 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
362             {
363                 $origin->{cluster} = $cluster;
364                 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
365             }
366         }
367     }
368
369     return;
370 }
371
372 #
373 # Compare two mappings to decide which to use
374 #
375 sub compare_mappings
376 {
377     my $a = shift;
378     my $b = shift;
379
380     return $b->{priority} <=> $a->{priority} ||
381            $a->{distance} <=> $b->{distance};
382 }
383
384 #
385 # Compare two mappings to decide which to try first
386 #
387 sub compare_bandwidth
388 {
389     my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
390     my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
391
392     return $a_used <=> $b_used;
393 }
394
395 #
396 # Output DNS records for a server
397 #
398 sub output_server
399 {
400     my $zonefile = shift;
401     my $name = shift;
402     my $cluster = shift;
403
404     foreach my $server (@{$cluster->{servers}})
405     {
406         if ($server->{status} eq "up")
407         {
408             $zonefile->print("+${name}:$server->{ipv4}:600\n");
409
410             if ($server->{ipv6})
411             {
412 #                $zonefile->print("3${name}:$server->{ipv6}:600\n");
413             }
414         }
415     }
416
417     return;
418 }