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};
230 my $proportion = int($used / $limit * 100 + 0.5);
232 print "${name}: used ${used} of ${limit} (${proportion}%)\n";
235 # Create JSON collection object
239 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
240 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
243 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
245 # Output details for each country
246 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
248 my $cluster = $origin->{cluster};
250 if (!defined($gdnsname))
252 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
255 if ($cluster->{lon} && $cluster->{lat})
257 my $clon = $origin->{lon};
258 my $clat = $origin->{lat};
259 my $slon = $cluster->{lon};
260 my $slat = $cluster->{lat};
262 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
266 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
274 type => "LineString",
275 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
278 origin => $origin->{name},
279 server => $cluster->{name},
280 colour => $cluster->{colour}
285 next if $cluster->{global};
287 $targetorigins->{$cluster->{name}}->{requests} += $origin->{requests};
290 # Skip default records if we don't need them
291 if (!defined($gdnsname))
293 # Output default records for IPs that can't be mapped to a country
294 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
296 my $name = $cluster->{name};
298 if (my $default = $cluster->{default})
300 output_server($zonefile, "${default}.${zone}", $cluster, 0);
302 elsif (exists($cluster->{default}))
304 output_server($zonefile, "${zone}", $cluster, 0);
309 # Output A records for each cluster
310 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
312 my $name = $cluster->{name};
314 if (@{$cluster->{servers}} > 1)
316 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
320 output_server($zonefile, "${name}.${zone}", $cluster, 1);
324 # Output the GeoJSON text
325 $jsonfile->print(encode_json(\@json));
328 $zonefile->print("];\n");
330 # Close the output files
334 # Output gdnsd configuration
335 if (defined($gdnsname))
337 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
338 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
339 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
342 $gdnsmapfile->print("${gdnsname} => {\n");
343 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
344 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
345 $gdnsmapfile->print(" map => {\n");
346 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
348 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
350 my $code = $origin->{code};
351 my $cluster = $origin->{cluster}->{name};
353 next if $code eq "XK";
355 if ($continent ne $origin->{continent})
357 $gdnsmapfile->print(" }\n") if $continent;
359 $continent = $origin->{continent};
361 $gdnsmapfile->print(" ${continent} => {\n");
364 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
367 $gdnsmapfile->print(" }\n") if $continent;
369 $gdnsmapfile->print(" }\n");
370 $gdnsmapfile->print("}\n");
372 $gdnsresourcefile->print("${gdnsname} => {\n");
373 $gdnsresourcefile->print(" map => ${gdnsname}\n");
374 $gdnsresourcefile->print(" dcmap => {\n");
376 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
378 my $name = $cluster->{name};
380 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
382 $gdnsweightedfile->print("${name} => {\n");
384 while (my($index,$server) = each @{$cluster->{servers}})
386 if ($server->{status} eq "up")
388 my $number = sprintf("%02d", $index + 1);
389 my $requests = $server->{requests};
391 if (my $cname = $server->{cname})
393 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${requests} ]\n");
397 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${requests} ]\n");
402 $gdnsweightedfile->print("}\n");
404 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
406 elsif (my $cname = $cluster->{cname})
408 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
412 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
416 $gdnsresourcefile->print(" }\n");
417 $gdnsresourcefile->print("}\n");
419 $gdnsweightedfile->close();
420 $gdnsresourcefile->close();
421 $gdnsmapfile->close();
424 # Output the target details in origin format if required
425 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
430 # Match an origin against a cluster
438 if ($cluster->{preferred} &&
439 $cluster->{preferred}->{origins} &&
440 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
442 $match = "preferred";
444 elsif ($cluster->{allowed} &&
445 $cluster->{allowed}->{origins} &&
446 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
450 elsif ($cluster->{preferred} &&
451 $cluster->{preferred}->{countries} &&
452 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
454 $match = "preferred";
456 elsif ($cluster->{allowed} &&
457 $cluster->{allowed}->{countries} &&
458 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
462 elsif ($cluster->{denied} &&
463 $cluster->{denied}->{countries} &&
464 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
468 elsif ($cluster->{preferred} &&
469 $cluster->{preferred}->{continents} &&
470 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
472 $match = "preferred";
474 elsif ($cluster->{allowed} &&
475 $cluster->{allowed}->{continents} &&
476 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
480 elsif ($cluster->{denied} &&
481 $cluster->{denied}->{continents} &&
482 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
486 elsif ($cluster->{allowed})
499 # Compute the great circle distance between two points
503 my $lat1 = deg2rad(shift);
504 my $lon1 = deg2rad(shift);
505 my $lat2 = deg2rad(shift);
506 my $lon2 = deg2rad(shift);
508 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
512 # Allocate each origin to a cluster
514 sub allocate_clusters
516 my @mappings = sort { compare_mappings($a, $b) } @_;
518 # Loop over the mappings, trying to assign each origin to the
519 # nearest cluster, but subject to the request limits
520 while (my $mapping = shift @mappings)
524 push @group, $mapping;
526 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
528 push @group, shift @mappings;
531 for my $mapping (sort compare_requests @group)
533 my $origin = $mapping->{origin};
534 my $cluster = $mapping->{cluster};
536 if (!exists($origin->{cluster}) &&
537 $cluster->{requests_used} + $origin->{requests} <= $cluster->{requests_limit})
539 $origin->{cluster} = $cluster;
540 $cluster->{requests_used} = $cluster->{requests_used} + $origin->{requests};
549 # Compare two mappings to decide which to use
556 return $b->{priority} <=> $a->{priority} ||
557 $a->{distance} <=> $b->{distance};
561 # Compare two mappings to decide which to try first
565 my $a_used = ( $a->{cluster}->{requests_used} * 100.0 ) / ( $a->{cluster}->{requests_limit} * 1.0 );
566 my $b_used = ( $b->{cluster}->{requests_used} * 100.0 ) / ( $b->{cluster}->{requests_limit} * 1.0 );
568 return $a_used <=> $b_used;
572 # Output DNS records for a server
576 my $zonefile = shift;
581 while (my($index,$server) = each @{$cluster->{servers}})
583 if ($all || $server->{status} eq "up")
587 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
592 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);