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 # Create target origins object
153 my $targetorigins = {};
155 # Initialise cluster details
156 while (my($name,$cluster) = each %$clusters)
158 $cluster->{requests_limit} = $cluster->{requests};
159 $cluster->{requests_used} = 0;
161 next if $cluster->{global};
163 $targetorigins->{$cluster->{name}} = {
164 code => $cluster->{name},
165 name => $cluster->{name},
166 lat => $cluster->{lat},
167 lon => $cluster->{lon},
174 # Scan origins and work out which clusters each can use
175 foreach my $origin (values %$origins)
177 foreach my $cluster (values %$clusters)
179 my $match = match_origin($cluster, $origin);
181 if ($cluster->{status} eq "up" && $match ne "denied")
183 my $priority = $match eq "preferred" ? 20 : 10;
186 if ($cluster->{global})
192 $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
196 origin => $origin, cluster => $cluster,
197 priority => $priority, distance => $distance
203 # Allocate each country to a cluster
204 allocate_clusters(@mappings);
206 # If we failed to allocate every origin then loop, increasing
207 # the requests for each cluster by a little and retrying until
208 # we manage to allocate everything
209 while (grep { !exists($_->{cluster}) } values %$origins)
211 # Clear any existing mappings of countries to clusters
212 foreach my $origin (values %$origins)
214 delete $origin->{cluster};
217 # Reset requests usage for clusters and increase limits by 10%
218 foreach my $cluster (values %$clusters)
220 $cluster->{requests_used} = 0;
221 $cluster->{requests_limit} = $cluster->{requests_limit} * 1.1;
224 # Try the allocate again
225 allocate_clusters(@mappings);
228 # Report on allocation results
229 foreach my $name (sort keys %$clusters)
231 my $cluster = $clusters->{$name};
232 my $used = int($cluster->{requests_used} + 0.5);
233 my $limit = $cluster->{requests_limit};
237 my $proportion = int($used / $limit * 100 + 0.5);
239 print "${name}: used ${used} of ${limit} (${proportion}%)\n";
243 print "${name}: used ${used} of ${limit}\n";
247 # Create JSON collection object
251 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
252 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
255 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
257 # Output details for each country
258 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
260 my $cluster = $origin->{cluster};
262 if (!defined($gdnsname))
264 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
267 if ($cluster->{lon} && $cluster->{lat})
269 my $clon = $origin->{lon};
270 my $clat = $origin->{lat};
271 my $slon = $cluster->{lon};
272 my $slat = $cluster->{lat};
274 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
278 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
286 type => "LineString",
287 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
290 origin => $origin->{name},
291 server => $cluster->{name},
292 colour => $cluster->{colour}
297 next if $cluster->{global};
299 $targetorigins->{$cluster->{name}}->{requests} += $origin->{requests};
302 # Skip default records if we don't need them
303 if (!defined($gdnsname))
305 # Output default records for IPs that can't be mapped to a country
306 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
308 my $name = $cluster->{name};
310 if (my $default = $cluster->{default})
312 output_server($zonefile, "${default}.${zone}", $cluster, 0);
314 elsif (exists($cluster->{default}))
316 output_server($zonefile, "${zone}", $cluster, 0);
321 # Output A records for each cluster
322 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
324 my $name = $cluster->{name};
326 if (@{$cluster->{servers}} > 1)
328 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
332 output_server($zonefile, "${name}.${zone}", $cluster, 1);
336 # Output the GeoJSON text
337 $jsonfile->print(encode_json(\@json));
340 $zonefile->print("];\n");
342 # Close the output files
346 # Output gdnsd configuration
347 if (defined($gdnsname))
349 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
350 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
351 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
354 $gdnsmapfile->print("${gdnsname} => {\n");
355 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
356 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
357 $gdnsmapfile->print(" map => {\n");
358 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
360 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
362 my $code = $origin->{code};
363 my $cluster = $origin->{cluster}->{name};
365 next if $code eq "XK";
367 if ($continent ne $origin->{continent})
369 $gdnsmapfile->print(" }\n") if $continent;
371 $continent = $origin->{continent};
373 $gdnsmapfile->print(" ${continent} => {\n");
376 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
379 $gdnsmapfile->print(" }\n") if $continent;
381 $gdnsmapfile->print(" }\n");
382 $gdnsmapfile->print("}\n");
384 $gdnsresourcefile->print("${gdnsname} => {\n");
385 $gdnsresourcefile->print(" map => ${gdnsname}\n");
386 $gdnsresourcefile->print(" dcmap => {\n");
388 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
390 my $name = $cluster->{name};
392 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
394 $gdnsweightedfile->print("${name} => {\n");
396 while (my($index,$server) = each @{$cluster->{servers}})
398 if ($server->{status} eq "up")
400 my $number = sprintf("%02d", $index + 1);
401 my $requests = $server->{requests};
403 if (my $cname = $server->{cname})
405 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${requests} ]\n");
409 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${requests} ]\n");
414 $gdnsweightedfile->print("}\n");
416 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
418 elsif (my $cname = $cluster->{cname})
420 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
424 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
428 $gdnsresourcefile->print(" }\n");
429 $gdnsresourcefile->print("}\n");
431 $gdnsweightedfile->close();
432 $gdnsresourcefile->close();
433 $gdnsmapfile->close();
436 # Output the target details in origin format if required
437 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
442 # Match an origin against a cluster
450 if ($cluster->{preferred} &&
451 $cluster->{preferred}->{origins} &&
452 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
454 $match = "preferred";
456 elsif ($cluster->{allowed} &&
457 $cluster->{allowed}->{origins} &&
458 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
462 elsif ($cluster->{preferred} &&
463 $cluster->{preferred}->{countries} &&
464 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
466 $match = "preferred";
468 elsif ($cluster->{allowed} &&
469 $cluster->{allowed}->{countries} &&
470 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
474 elsif ($cluster->{denied} &&
475 $cluster->{denied}->{countries} &&
476 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
480 elsif ($cluster->{preferred} &&
481 $cluster->{preferred}->{continents} &&
482 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
484 $match = "preferred";
486 elsif ($cluster->{allowed} &&
487 $cluster->{allowed}->{continents} &&
488 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
492 elsif ($cluster->{denied} &&
493 $cluster->{denied}->{continents} &&
494 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
498 elsif ($cluster->{allowed})
511 # Compute the great circle distance between two points
515 my $lat1 = deg2rad(shift);
516 my $lon1 = deg2rad(shift);
517 my $lat2 = deg2rad(shift);
518 my $lon2 = deg2rad(shift);
520 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
524 # Allocate each origin to a cluster
526 sub allocate_clusters
528 my @mappings = sort { compare_mappings($a, $b) } @_;
530 # Loop over the mappings, trying to assign each origin to the
531 # nearest cluster, but subject to the request limits
532 while (my $mapping = shift @mappings)
536 push @group, $mapping;
538 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
540 push @group, shift @mappings;
543 for my $mapping (sort compare_requests @group)
545 my $origin = $mapping->{origin};
546 my $cluster = $mapping->{cluster};
548 if (!exists($origin->{cluster}) &&
549 $cluster->{requests_used} + $origin->{requests} <= $cluster->{requests_limit})
551 $origin->{cluster} = $cluster;
552 $cluster->{requests_used} = $cluster->{requests_used} + $origin->{requests};
561 # Compare two mappings to decide which to use
568 return $b->{priority} <=> $a->{priority} ||
569 $a->{distance} <=> $b->{distance};
573 # Compare two mappings to decide which to try first
577 my $a_used = ( $a->{cluster}->{requests_used} * 100.0 ) / ( $a->{cluster}->{requests_limit} * 1.0 );
578 my $b_used = ( $b->{cluster}->{requests_used} * 100.0 ) / ( $b->{cluster}->{requests_limit} * 1.0 );
580 return $a_used <=> $b_used;
584 # Output DNS records for a server
588 my $zonefile = shift;
593 while (my($index,$server) = each @{$cluster->{servers}})
595 if ($all || $server->{status} eq "up")
599 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
604 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);