9 use Math::Trig qw(deg2rad pip2 great_circle_distance);
12 use YAML::XS qw(LoadFile DumpFile);
14 my $originfile = shift @ARGV;
15 my $clusterfile = shift @ARGV;
16 my $zone = shift @ARGV;
17 my $targetoriginfile = shift @ARGV;
18 my $origins = LoadFile($originfile);
19 my $clusters = LoadFile($clusterfile);
20 my $gdnsname = shift @ARGV;
23 # Initialise cluster details
24 while (my($name,$cluster) = each %$clusters)
26 if ($cluster->{servers})
28 $cluster->{bandwidth} = 0;
30 foreach my $server (@{$cluster->{servers}})
32 $server->{cluster} = $cluster;
33 $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
35 push @servers, $server;
42 statuscake => $cluster->{statuscake},
43 bandwidth => $cluster->{bandwidth},
44 cname => $cluster->{cname},
45 ipv4 => $cluster->{ipv4},
46 ipv6 => $cluster->{ipv6}
49 $cluster->{servers} = [ $server ];
51 push @servers, $server;
54 $cluster->{name} = $name;
55 $cluster->{status} = "down";
58 # Initialise server details
59 foreach my $server (@servers)
61 $server->{status} = "up";
64 # If statuscake support is enabled then check which servers are up
65 if ($ENV{STATUSCAKE_USERNAME} && $ENV{STATUSCAKE_APIKEY})
67 my $ua = LWP::UserAgent->new;
70 $ua->agent("mkgeo/1.0");
71 $ua->default_header("Username", $ENV{STATUSCAKE_USERNAME});
72 $ua->default_header("API", $ENV{STATUSCAKE_APIKEY});
74 if (-f "statuscake.yml")
76 $cache = LoadFile("statuscake.yml");
83 my $response = $ua->get("https://app.statuscake.com/API/Tests/");
85 if ($response->is_success)
87 my $tests = decode_json($response->content);
89 foreach my $test (@$tests)
91 my $testid = $test->{TestID};
93 if ($test->{Status} eq "Up" && !$test->{Paused})
95 $cache->{$testid} = "up";
99 $cache->{$testid} = "down";
104 foreach my $server (@servers)
106 if (my $testids = $server->{statuscake})
108 $server->{status} = "up";
110 for my $testid (@$testids)
112 my $testresult = $cache->{$testid} || "down";
114 $server->{status} = "down" if $testresult eq "down";
119 $server->{status} = "down";
123 DumpFile("statuscake-$$.yml", $cache);
124 rename("statuscake-$$.yml", "statuscake.yml");
127 # Mark a cluster as up if any servers are up
128 foreach my $server (@servers)
130 if ($server->{status} eq "up")
132 $server->{cluster}->{status} = "up";
136 $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
140 # Create target origins object
141 my $targetorigins = {};
143 # Initialise cluster details
144 while (my($name,$cluster) = each %$clusters)
146 $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
147 $cluster->{bandwidth_used} = 0;
149 $targetorigins->{$cluster->{name}} = {
150 code => $cluster->{name},
151 name => $cluster->{name},
152 lat => $cluster->{lat},
153 lon => $cluster->{lon},
160 # Scan origins and work out which clusters each can use
161 foreach my $origin (values %$origins)
163 foreach my $cluster (values %$clusters)
165 my $match = match_origin($cluster, $origin);
167 if ($cluster->{status} eq "up" && $match ne "denied")
169 my $priority = $match eq "preferred" ? 20 : 10;
172 if ($cluster->{global})
178 $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
182 origin => $origin, cluster => $cluster,
183 priority => $priority, distance => $distance
189 # Allocate each country to a cluster
190 allocate_clusters(@mappings);
192 # If we failed to allocate every origin then loop, increasing
193 # the bandwidth for each cluster by a little and retrying until
194 # we manage to allocate everything
195 while (grep { !exists($_->{cluster}) } values %$origins)
197 # Clear any existing mappings of countries to clusters
198 foreach my $origin (values %$origins)
200 delete $origin->{cluster};
203 # Reset bandwidth usage for clusters and increase limits by 10%
204 foreach my $cluster (values %$clusters)
206 $cluster->{bandwidth_used} = 0;
207 $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
210 # Try the allocate again
211 allocate_clusters(@mappings);
214 # Create JSON collection object
218 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
219 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
222 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
224 # Output details for each country
225 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
227 my $cluster = $origin->{cluster};
229 if (!defined($gdnsname))
231 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
234 if ($cluster->{lon} && $cluster->{lat})
236 my $clon = $origin->{lon};
237 my $clat = $origin->{lat};
238 my $slon = $cluster->{lon};
239 my $slat = $cluster->{lat};
241 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
245 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
253 type => "LineString",
254 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
257 origin => $origin->{name},
258 server => $cluster->{name},
259 colour => $cluster->{colour}
264 $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
267 # Skip default records if we don't need them
268 if (!defined($gdnsname))
270 # Output default records for IPs that can't be mapped to a country
271 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
273 my $name = $cluster->{name};
275 if (my $default = $cluster->{default})
277 output_server($zonefile, "${default}.${zone}", $cluster, 0);
279 elsif (exists($cluster->{default}))
281 output_server($zonefile, "${zone}", $cluster, 0);
286 # Output A records for each cluster
287 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
289 my $name = $cluster->{name};
291 if (@{$cluster->{servers}} > 1)
293 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
297 output_server($zonefile, "${name}.${zone}", $cluster, 1);
301 # Output the GeoJSON text
302 $jsonfile->print(encode_json(\@json));
305 $zonefile->print("];\n");
307 # Close the output files
311 # Output gdnsd configuration
312 if (defined($gdnsname))
314 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
315 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
316 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
319 $gdnsmapfile->print("${gdnsname} => {\n");
320 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
321 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
322 $gdnsmapfile->print(" map => {\n");
323 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
325 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
327 my $code = $origin->{code};
328 my $cluster = $origin->{cluster}->{name};
330 next if $code eq "XK";
332 if ($continent ne $origin->{continent})
334 $gdnsmapfile->print(" }\n") if $continent;
336 $continent = $origin->{continent};
338 $gdnsmapfile->print(" ${continent} => {\n");
341 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
344 $gdnsmapfile->print(" }\n") if $continent;
346 $gdnsmapfile->print(" }\n");
347 $gdnsmapfile->print("}\n");
349 $gdnsresourcefile->print("${gdnsname} => {\n");
350 $gdnsresourcefile->print(" map => ${gdnsname}\n");
351 $gdnsresourcefile->print(" dcmap => {\n");
353 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
355 my $name = $cluster->{name};
357 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
359 $gdnsweightedfile->print("${name} => {\n");
361 while (my($index,$server) = each @{$cluster->{servers}})
363 if ($server->{status} eq "up")
365 my $number = sprintf("%02d", $index + 1);
366 my $bandwidth = $server->{bandwidth};
368 if (my $cname = $server->{cname})
370 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${bandwidth} ]\n");
374 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${bandwidth} ]\n");
379 $gdnsweightedfile->print("}\n");
381 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
383 elsif (my $cname = $cluster->{cname})
385 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
389 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
393 $gdnsresourcefile->print(" }\n");
394 $gdnsresourcefile->print("}\n");
396 $gdnsweightedfile->close();
397 $gdnsresourcefile->close();
398 $gdnsmapfile->close();
401 # Output the target details in origin format if required
402 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
407 # Match an origin against a cluster
415 if ($cluster->{preferred} &&
416 $cluster->{preferred}->{origins} &&
417 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
419 $match = "preferred";
421 elsif ($cluster->{allowed} &&
422 $cluster->{allowed}->{origins} &&
423 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
427 elsif ($cluster->{preferred} &&
428 $cluster->{preferred}->{countries} &&
429 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
431 $match = "preferred";
433 elsif ($cluster->{allowed} &&
434 $cluster->{allowed}->{countries} &&
435 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
439 elsif ($cluster->{denied} &&
440 $cluster->{denied}->{countries} &&
441 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
445 elsif ($cluster->{preferred} &&
446 $cluster->{preferred}->{continents} &&
447 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
449 $match = "preferred";
451 elsif ($cluster->{allowed} &&
452 $cluster->{allowed}->{continents} &&
453 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
457 elsif ($cluster->{denied} &&
458 $cluster->{denied}->{continents} &&
459 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
463 elsif ($cluster->{allowed})
476 # Compute the great circle distance between two points
480 my $lat1 = deg2rad(shift);
481 my $lon1 = deg2rad(shift);
482 my $lat2 = deg2rad(shift);
483 my $lon2 = deg2rad(shift);
485 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
489 # Allocate each origin to a cluster
491 sub allocate_clusters
493 my @mappings = sort { compare_mappings($a, $b) } @_;
495 # Loop over the mappings, trying to assign each origin to the
496 # nearest cluster, but subject to the bandwidth limits
497 while (my $mapping = shift @mappings)
501 push @group, $mapping;
503 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
505 push @group, shift @mappings;
508 for my $mapping (sort compare_bandwidth @group)
510 my $origin = $mapping->{origin};
511 my $cluster = $mapping->{cluster};
513 if (!exists($origin->{cluster}) &&
514 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
516 $origin->{cluster} = $cluster;
517 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
526 # Compare two mappings to decide which to use
533 return $b->{priority} <=> $a->{priority} ||
534 $a->{distance} <=> $b->{distance};
538 # Compare two mappings to decide which to try first
540 sub compare_bandwidth
542 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
543 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
545 return $a_used <=> $b_used;
549 # Output DNS records for a server
553 my $zonefile = shift;
558 while (my($index,$server) = each @{$cluster->{servers}})
560 if ($all || $server->{status} eq "up")
564 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
569 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);