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;
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;
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_APIKEY})
67 my $ua = LWP::UserAgent->new;
70 $ua->agent("mkgeo/1.0");
71 $ua->default_header("Authorization", "Bearer $ENV{STATUSCAKE_APIKEY}");
73 if (-f "statuscake.yml")
75 $cache = LoadFile("statuscake.yml");
85 while ($page <= $pages)
87 my $response = $ua->get("https://api.statuscake.com/v1/uptime?nouptime=true&limit=100&page=${page}");
89 if ($response->is_success)
91 my $uptime = decode_json($response->content);
93 foreach my $test (@{$uptime->{data}})
95 my $testid = $test->{id};
97 if ($test->{status} eq "up" && !$test->{paused})
99 $cache->{$testid} = "up";
103 $cache->{$testid} = "down";
108 $pages = $uptime->{metadata}->{page_count};
112 foreach my $server (@servers)
114 if (my $testids = $server->{statuscake})
116 $server->{status} = "up";
118 for my $testid (@$testids)
120 my $testresult = $cache->{$testid} || "down";
122 $server->{status} = "down" if $testresult eq "down";
127 $server->{status} = "down";
131 DumpFile("statuscake-$$.yml", $cache);
132 rename("statuscake-$$.yml", "statuscake.yml");
135 # Mark a cluster as up if any servers are up
136 foreach my $server (@servers)
138 if ($server->{status} eq "up")
140 $server->{cluster}->{status} = "up";
144 $server->{cluster}->{requests} = $server->{cluster}->{requests} - $server->{requests};
148 # Create target origins object
149 my $targetorigins = {};
151 # Initialise cluster details
152 while (my($name,$cluster) = each %$clusters)
154 $cluster->{requests_limit} = $cluster->{requests};
155 $cluster->{requests_used} = 0;
157 next if $cluster->{global};
159 $targetorigins->{$cluster->{name}} = {
160 code => $cluster->{name},
161 name => $cluster->{name},
162 lat => $cluster->{lat},
163 lon => $cluster->{lon},
170 # Scan origins and work out which clusters each can use
171 foreach my $origin (values %$origins)
173 foreach my $cluster (values %$clusters)
175 my $match = match_origin($cluster, $origin);
177 if ($cluster->{status} eq "up" && $match ne "denied")
179 my $priority = $match eq "preferred" ? 20 : 10;
182 if ($cluster->{global})
188 $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
192 origin => $origin, cluster => $cluster,
193 priority => $priority, distance => $distance
199 # Allocate each country to a cluster
200 allocate_clusters(@mappings);
202 # If we failed to allocate every origin then loop, increasing
203 # the requests for each cluster by a little and retrying until
204 # we manage to allocate everything
205 while (grep { !exists($_->{cluster}) } values %$origins)
207 # Clear any existing mappings of countries to clusters
208 foreach my $origin (values %$origins)
210 delete $origin->{cluster};
213 # Reset requests usage for clusters and increase limits by 10%
214 foreach my $cluster (values %$clusters)
216 $cluster->{requests_used} = 0;
217 $cluster->{requests_limit} = $cluster->{requests_limit} * 1.1;
220 # Try the allocate again
221 allocate_clusters(@mappings);
224 # Report on allocation results
225 foreach my $name (sort keys %$clusters)
227 my $cluster = $clusters->{$name};
228 my $used = int($cluster->{requests_used} + 0.5);
229 my $limit = $cluster->{requests_limit};
233 my $proportion = int($used / $limit * 100 + 0.5);
235 print "${name}: used ${used} of ${limit} (${proportion}%)\n";
239 print "${name}: used ${used} of ${limit}\n";
243 # Create JSON collection object
247 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
248 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
251 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
253 # Output details for each country
254 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
256 my $cluster = $origin->{cluster};
258 if (!defined($gdnsname))
260 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
263 if ($cluster->{lon} && $cluster->{lat})
265 my $clon = $origin->{lon};
266 my $clat = $origin->{lat};
267 my $slon = $cluster->{lon};
268 my $slat = $cluster->{lat};
270 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
274 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
282 type => "LineString",
283 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
286 origin => $origin->{name},
287 server => $cluster->{name},
288 colour => $cluster->{colour}
293 next if $cluster->{global};
295 $targetorigins->{$cluster->{name}}->{requests} += $origin->{requests};
298 # Skip default records if we don't need them
299 if (!defined($gdnsname))
301 # Output default records for IPs that can't be mapped to a country
302 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
304 my $name = $cluster->{name};
306 if (my $default = $cluster->{default})
308 output_server($zonefile, "${default}.${zone}", $cluster, 0);
310 elsif (exists($cluster->{default}))
312 output_server($zonefile, "${zone}", $cluster, 0);
317 # Output A records for each cluster
318 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
320 my $name = $cluster->{name};
322 if (@{$cluster->{servers}} > 1)
324 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
328 output_server($zonefile, "${name}.${zone}", $cluster, 1);
332 # Output the GeoJSON text
333 $jsonfile->print(encode_json(\@json));
336 $zonefile->print("];\n");
338 # Close the output files
342 # Output gdnsd configuration
343 if (defined($gdnsname))
345 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
346 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
347 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
350 $gdnsmapfile->print("${gdnsname} => {\n");
351 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
352 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
353 $gdnsmapfile->print(" map => {\n");
354 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
356 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
358 my $code = $origin->{code};
359 my $cluster = $origin->{cluster}->{name};
361 next if $code eq "XK";
363 if ($continent ne $origin->{continent})
365 $gdnsmapfile->print(" }\n") if $continent;
367 $continent = $origin->{continent};
369 $gdnsmapfile->print(" ${continent} => {\n");
372 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
375 $gdnsmapfile->print(" }\n") if $continent;
377 $gdnsmapfile->print(" }\n");
378 $gdnsmapfile->print("}\n");
380 $gdnsresourcefile->print("${gdnsname} => {\n");
381 $gdnsresourcefile->print(" map => ${gdnsname}\n");
382 $gdnsresourcefile->print(" dcmap => {\n");
384 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
386 my $name = $cluster->{name};
388 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
390 $gdnsweightedfile->print("${name} => {\n");
392 while (my($index,$server) = each @{$cluster->{servers}})
394 if ($server->{status} eq "up")
396 my $number = sprintf("%02d", $index + 1);
397 my $requests = $server->{requests};
399 if (my $cname = $server->{cname})
401 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${requests} ]\n");
405 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${requests} ]\n");
410 $gdnsweightedfile->print("}\n");
412 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
414 elsif (my $cname = $cluster->{cname})
416 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
420 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
424 $gdnsresourcefile->print(" }\n");
425 $gdnsresourcefile->print("}\n");
427 $gdnsweightedfile->close();
428 $gdnsresourcefile->close();
429 $gdnsmapfile->close();
432 # Output the target details in origin format if required
433 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
438 # Match an origin against a cluster
446 if ($cluster->{preferred} &&
447 $cluster->{preferred}->{origins} &&
448 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
450 $match = "preferred";
452 elsif ($cluster->{allowed} &&
453 $cluster->{allowed}->{origins} &&
454 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
458 elsif ($cluster->{preferred} &&
459 $cluster->{preferred}->{countries} &&
460 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
462 $match = "preferred";
464 elsif ($cluster->{allowed} &&
465 $cluster->{allowed}->{countries} &&
466 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
470 elsif ($cluster->{denied} &&
471 $cluster->{denied}->{countries} &&
472 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
476 elsif ($cluster->{preferred} &&
477 $cluster->{preferred}->{continents} &&
478 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
480 $match = "preferred";
482 elsif ($cluster->{allowed} &&
483 $cluster->{allowed}->{continents} &&
484 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
488 elsif ($cluster->{denied} &&
489 $cluster->{denied}->{continents} &&
490 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
494 elsif ($cluster->{allowed})
507 # Compute the great circle distance between two points
511 my $lat1 = deg2rad(shift);
512 my $lon1 = deg2rad(shift);
513 my $lat2 = deg2rad(shift);
514 my $lon2 = deg2rad(shift);
516 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
520 # Allocate each origin to a cluster
522 sub allocate_clusters
524 my @mappings = sort { compare_mappings($a, $b) } @_;
526 # Loop over the mappings, trying to assign each origin to the
527 # nearest cluster, but subject to the request limits
528 while (my $mapping = shift @mappings)
532 push @group, $mapping;
534 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
536 push @group, shift @mappings;
539 for my $mapping (sort compare_requests @group)
541 my $origin = $mapping->{origin};
542 my $cluster = $mapping->{cluster};
544 if (!exists($origin->{cluster}) &&
545 $cluster->{requests_used} + $origin->{requests} <= $cluster->{requests_limit})
547 $origin->{cluster} = $cluster;
548 $cluster->{requests_used} = $cluster->{requests_used} + $origin->{requests};
557 # Compare two mappings to decide which to use
564 return $b->{priority} <=> $a->{priority} ||
565 $a->{distance} <=> $b->{distance};
569 # Compare two mappings to decide which to try first
573 my $a_used = ( $a->{cluster}->{requests_used} * 100.0 ) / ( $a->{cluster}->{requests_limit} * 1.0 );
574 my $b_used = ( $b->{cluster}->{requests_used} * 100.0 ) / ( $b->{cluster}->{requests_limit} * 1.0 );
576 return $a_used <=> $b_used;
580 # Output DNS records for a server
584 my $zonefile = shift;
589 while (my($index,$server) = each @{$cluster->{servers}})
591 if ($all || $server->{status} eq "up")
595 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
600 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);