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->{requests} = 0;
30 foreach my $server (@{$cluster->{servers}})
32 $server->{cluster} = $cluster;
33 $cluster->{requests} = $cluster->{requests} + $server->{requests};
35 push @servers, $server;
38 elsif ($cluster->{requests} > 0)
42 statuscake => $cluster->{statuscake},
43 requests => $cluster->{requests},
44 cname => $cluster->{cname},
45 ipv4 => $cluster->{ipv4},
46 ipv6 => $cluster->{ipv6}
49 $cluster->{servers} = [ $server ];
51 push @servers, $server;
55 $cluster->{servers} = [];
58 $cluster->{name} = $name;
59 $cluster->{status} = "down";
62 # Initialise server details
63 foreach my $server (@servers)
65 $server->{status} = "up";
68 # If statuscake support is enabled then check which servers are up
69 if ($ENV{STATUSCAKE_APIKEY})
71 my $ua = LWP::UserAgent->new;
74 $ua->agent("mkgeo/1.0");
75 $ua->default_header("Authorization", "Bearer $ENV{STATUSCAKE_APIKEY}");
77 if (-f "statuscake.yml")
79 $cache = LoadFile("statuscake.yml");
89 while ($page <= $pages)
91 my $response = $ua->get("https://api.statuscake.com/v1/uptime?nouptime=true&limit=100&page=${page}");
93 if ($response->is_success)
95 my $uptime = decode_json($response->content);
97 foreach my $test (@{$uptime->{data}})
99 my $testid = $test->{id};
101 if ($test->{status} eq "up" && !$test->{paused})
103 $cache->{$testid} = "up";
107 $cache->{$testid} = "down";
112 $pages = $uptime->{metadata}->{page_count};
116 foreach my $server (@servers)
118 if (my $testids = $server->{statuscake})
120 $server->{status} = "up";
122 for my $testid (@$testids)
124 my $testresult = $cache->{$testid} || "down";
126 $server->{status} = "down" if $testresult eq "down";
131 $server->{status} = "down";
135 DumpFile("statuscake-$$.yml", $cache);
136 rename("statuscake-$$.yml", "statuscake.yml");
139 # Mark a cluster as up if any servers are up
140 foreach my $server (@servers)
142 if ($server->{status} eq "up")
144 $server->{cluster}->{status} = "up";
148 $server->{cluster}->{requests} = $server->{cluster}->{requests} - $server->{requests};
152 # Abort if no servers at all are up
153 exit 0 unless grep { $_->{status} eq "up" } values(%$clusters);
155 # Create target origins object
156 my $targetorigins = {};
158 # Initialise cluster details
159 while (my($name,$cluster) = each %$clusters)
161 $cluster->{requests_limit} = $cluster->{requests};
162 $cluster->{requests_used} = 0;
164 next if $cluster->{global};
166 $targetorigins->{$cluster->{name}} = {
167 code => $cluster->{name},
168 name => $cluster->{name},
169 lat => $cluster->{lat},
170 lon => $cluster->{lon},
177 # Scan origins and work out which clusters each can use
178 foreach my $origin (values %$origins)
180 foreach my $cluster (values %$clusters)
182 my $match = match_origin($cluster, $origin);
184 if ($cluster->{status} eq "up" && $match ne "denied")
186 my $priority = $match eq "preferred" ? 20 : 10;
189 if ($cluster->{global})
195 $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
199 origin => $origin, cluster => $cluster,
200 priority => $priority, distance => $distance
206 # Allocate each country to a cluster
207 allocate_clusters(@mappings);
209 # If we failed to allocate every origin then loop, increasing
210 # the requests for each cluster by a little and retrying until
211 # we manage to allocate everything
212 while (grep { !exists($_->{cluster}) } values %$origins)
214 # Clear any existing mappings of countries to clusters
215 foreach my $origin (values %$origins)
217 delete $origin->{cluster};
220 # Reset requests usage for clusters and increase limits by 10%
221 foreach my $cluster (values %$clusters)
223 $cluster->{requests_used} = 0;
224 $cluster->{requests_limit} = $cluster->{requests_limit} * 1.1;
227 # Try the allocate again
228 allocate_clusters(@mappings);
231 # Report on allocation results
232 foreach my $name (sort keys %$clusters)
234 my $cluster = $clusters->{$name};
235 my $used = int($cluster->{requests_used} + 0.5);
236 my $limit = $cluster->{requests_limit};
240 my $proportion = int($used / $limit * 100 + 0.5);
242 print "${name}: used ${used} of ${limit} (${proportion}%)\n";
246 print "${name}: used ${used} of ${limit}\n";
250 # Create JSON collection object
254 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
255 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
258 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
260 # Output details for each country
261 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
263 my $cluster = $origin->{cluster};
265 if (!defined($gdnsname))
267 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
270 if ($cluster->{lon} && $cluster->{lat})
272 my $clon = $origin->{lon};
273 my $clat = $origin->{lat};
274 my $slon = $cluster->{lon};
275 my $slat = $cluster->{lat};
277 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
281 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
289 type => "LineString",
290 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
293 origin => $origin->{name},
294 server => $cluster->{name},
295 colour => $cluster->{colour}
300 next if $cluster->{global};
302 $targetorigins->{$cluster->{name}}->{requests} += $origin->{requests};
305 # Skip default records if we don't need them
306 if (!defined($gdnsname))
308 # Output default records for IPs that can't be mapped to a country
309 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
311 my $name = $cluster->{name};
313 if (my $default = $cluster->{default})
315 output_server($zonefile, "${default}.${zone}", $cluster, 0);
317 elsif (exists($cluster->{default}))
319 output_server($zonefile, "${zone}", $cluster, 0);
324 # Output A records for each cluster
325 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
327 my $name = $cluster->{name};
329 if (@{$cluster->{servers}} > 1)
331 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
335 output_server($zonefile, "${name}.${zone}", $cluster, 1);
339 # Output the GeoJSON text
340 $jsonfile->print(encode_json(\@json));
343 $zonefile->print("];\n");
345 # Close the output files
349 # Output gdnsd configuration
350 if (defined($gdnsname))
352 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
353 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
354 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
357 $gdnsmapfile->print("${gdnsname} => {\n");
358 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
359 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
360 $gdnsmapfile->print(" map => {\n");
361 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
363 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
365 my $code = $origin->{code};
366 my $cluster = $origin->{cluster}->{name};
368 next if $code eq "XK";
370 if ($continent ne $origin->{continent})
372 $gdnsmapfile->print(" }\n") if $continent;
374 $continent = $origin->{continent};
376 $gdnsmapfile->print(" ${continent} => {\n");
379 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
382 $gdnsmapfile->print(" }\n") if $continent;
384 $gdnsmapfile->print(" }\n");
385 $gdnsmapfile->print("}\n");
387 $gdnsresourcefile->print("${gdnsname} => {\n");
388 $gdnsresourcefile->print(" map => ${gdnsname}\n");
389 $gdnsresourcefile->print(" dcmap => {\n");
391 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
393 my $name = $cluster->{name};
395 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
397 $gdnsweightedfile->print("${name} => {\n");
399 while (my($index,$server) = each @{$cluster->{servers}})
401 if ($server->{status} eq "up")
403 my $number = sprintf("%02d", $index + 1);
404 my $requests = $server->{requests};
406 if (my $cname = $server->{cname})
408 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${requests} ]\n");
412 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${requests} ]\n");
417 $gdnsweightedfile->print("}\n");
419 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
421 elsif (my $cname = $cluster->{cname})
423 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
427 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
431 $gdnsresourcefile->print(" }\n");
432 $gdnsresourcefile->print("}\n");
434 $gdnsweightedfile->close();
435 $gdnsresourcefile->close();
436 $gdnsmapfile->close();
439 # Output the target details in origin format if required
440 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
445 # Match an origin against a cluster
453 if ($cluster->{preferred} &&
454 $cluster->{preferred}->{origins} &&
455 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
457 $match = "preferred";
459 elsif ($cluster->{allowed} &&
460 $cluster->{allowed}->{origins} &&
461 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
465 elsif ($cluster->{preferred} &&
466 $cluster->{preferred}->{countries} &&
467 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
469 $match = "preferred";
471 elsif ($cluster->{allowed} &&
472 $cluster->{allowed}->{countries} &&
473 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
477 elsif ($cluster->{denied} &&
478 $cluster->{denied}->{countries} &&
479 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
483 elsif ($cluster->{preferred} &&
484 $cluster->{preferred}->{continents} &&
485 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
487 $match = "preferred";
489 elsif ($cluster->{allowed} &&
490 $cluster->{allowed}->{continents} &&
491 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
495 elsif ($cluster->{denied} &&
496 $cluster->{denied}->{continents} &&
497 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
501 elsif ($cluster->{allowed})
514 # Compute the great circle distance between two points
518 my $lat1 = deg2rad(shift);
519 my $lon1 = deg2rad(shift);
520 my $lat2 = deg2rad(shift);
521 my $lon2 = deg2rad(shift);
523 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
527 # Allocate each origin to a cluster
529 sub allocate_clusters
531 my @mappings = sort { compare_mappings($a, $b) } @_;
533 # Loop over the mappings, trying to assign each origin to the
534 # nearest cluster, but subject to the request limits
535 while (my $mapping = shift @mappings)
539 push @group, $mapping;
541 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
543 push @group, shift @mappings;
546 for my $mapping (sort compare_requests @group)
548 my $origin = $mapping->{origin};
549 my $cluster = $mapping->{cluster};
551 if (!exists($origin->{cluster}) &&
552 $cluster->{requests_used} + $origin->{requests} <= $cluster->{requests_limit})
554 $origin->{cluster} = $cluster;
555 $cluster->{requests_used} = $cluster->{requests_used} + $origin->{requests};
564 # Compare two mappings to decide which to use
571 return $b->{priority} <=> $a->{priority} ||
572 $a->{distance} <=> $b->{distance};
576 # Compare two mappings to decide which to try first
580 my $a_used = ( $a->{cluster}->{requests_used} * 100.0 ) / ( $a->{cluster}->{requests_limit} * 1.0 );
581 my $b_used = ( $b->{cluster}->{requests_used} * 100.0 ) / ( $b->{cluster}->{requests_limit} * 1.0 );
583 return $a_used <=> $b_used;
587 # Output DNS records for a server
591 my $zonefile = shift;
596 while (my($index,$server) = each @{$cluster->{servers}})
598 if ($all || $server->{status} eq "up")
602 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
607 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);