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 # Create JSON collection object
228 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
229 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
232 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
234 # Output details for each country
235 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
237 my $cluster = $origin->{cluster};
239 if (!defined($gdnsname))
241 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
244 if ($cluster->{lon} && $cluster->{lat})
246 my $clon = $origin->{lon};
247 my $clat = $origin->{lat};
248 my $slon = $cluster->{lon};
249 my $slat = $cluster->{lat};
251 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
255 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
263 type => "LineString",
264 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
267 origin => $origin->{name},
268 server => $cluster->{name},
269 colour => $cluster->{colour}
274 next if $cluster->{global};
276 $targetorigins->{$cluster->{name}}->{requests} += $origin->{requests};
279 # Skip default records if we don't need them
280 if (!defined($gdnsname))
282 # Output default records for IPs that can't be mapped to a country
283 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
285 my $name = $cluster->{name};
287 if (my $default = $cluster->{default})
289 output_server($zonefile, "${default}.${zone}", $cluster, 0);
291 elsif (exists($cluster->{default}))
293 output_server($zonefile, "${zone}", $cluster, 0);
298 # Output A records for each cluster
299 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
301 my $name = $cluster->{name};
303 if (@{$cluster->{servers}} > 1)
305 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
309 output_server($zonefile, "${name}.${zone}", $cluster, 1);
313 # Output the GeoJSON text
314 $jsonfile->print(encode_json(\@json));
317 $zonefile->print("];\n");
319 # Close the output files
323 # Output gdnsd configuration
324 if (defined($gdnsname))
326 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
327 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
328 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
331 $gdnsmapfile->print("${gdnsname} => {\n");
332 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
333 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
334 $gdnsmapfile->print(" map => {\n");
335 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
337 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
339 my $code = $origin->{code};
340 my $cluster = $origin->{cluster}->{name};
342 next if $code eq "XK";
344 if ($continent ne $origin->{continent})
346 $gdnsmapfile->print(" }\n") if $continent;
348 $continent = $origin->{continent};
350 $gdnsmapfile->print(" ${continent} => {\n");
353 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
356 $gdnsmapfile->print(" }\n") if $continent;
358 $gdnsmapfile->print(" }\n");
359 $gdnsmapfile->print("}\n");
361 $gdnsresourcefile->print("${gdnsname} => {\n");
362 $gdnsresourcefile->print(" map => ${gdnsname}\n");
363 $gdnsresourcefile->print(" dcmap => {\n");
365 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
367 my $name = $cluster->{name};
369 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
371 $gdnsweightedfile->print("${name} => {\n");
373 while (my($index,$server) = each @{$cluster->{servers}})
375 if ($server->{status} eq "up")
377 my $number = sprintf("%02d", $index + 1);
378 my $requests = $server->{requests};
380 if (my $cname = $server->{cname})
382 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${requests} ]\n");
386 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${requests} ]\n");
391 $gdnsweightedfile->print("}\n");
393 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
395 elsif (my $cname = $cluster->{cname})
397 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
401 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
405 $gdnsresourcefile->print(" }\n");
406 $gdnsresourcefile->print("}\n");
408 $gdnsweightedfile->close();
409 $gdnsresourcefile->close();
410 $gdnsmapfile->close();
413 # Output the target details in origin format if required
414 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
419 # Match an origin against a cluster
427 if ($cluster->{preferred} &&
428 $cluster->{preferred}->{origins} &&
429 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
431 $match = "preferred";
433 elsif ($cluster->{allowed} &&
434 $cluster->{allowed}->{origins} &&
435 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
439 elsif ($cluster->{preferred} &&
440 $cluster->{preferred}->{countries} &&
441 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
443 $match = "preferred";
445 elsif ($cluster->{allowed} &&
446 $cluster->{allowed}->{countries} &&
447 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
451 elsif ($cluster->{denied} &&
452 $cluster->{denied}->{countries} &&
453 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
457 elsif ($cluster->{preferred} &&
458 $cluster->{preferred}->{continents} &&
459 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
461 $match = "preferred";
463 elsif ($cluster->{allowed} &&
464 $cluster->{allowed}->{continents} &&
465 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
469 elsif ($cluster->{denied} &&
470 $cluster->{denied}->{continents} &&
471 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
475 elsif ($cluster->{allowed})
488 # Compute the great circle distance between two points
492 my $lat1 = deg2rad(shift);
493 my $lon1 = deg2rad(shift);
494 my $lat2 = deg2rad(shift);
495 my $lon2 = deg2rad(shift);
497 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
501 # Allocate each origin to a cluster
503 sub allocate_clusters
505 my @mappings = sort { compare_mappings($a, $b) } @_;
507 # Loop over the mappings, trying to assign each origin to the
508 # nearest cluster, but subject to the request limits
509 while (my $mapping = shift @mappings)
513 push @group, $mapping;
515 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
517 push @group, shift @mappings;
520 for my $mapping (sort compare_requests @group)
522 my $origin = $mapping->{origin};
523 my $cluster = $mapping->{cluster};
525 if (!exists($origin->{cluster}) &&
526 $cluster->{requests_used} + $origin->{requests} <= $cluster->{requests_limit})
528 $origin->{cluster} = $cluster;
529 $cluster->{requests_used} = $cluster->{requests_used} + $origin->{requests};
538 # Compare two mappings to decide which to use
545 return $b->{priority} <=> $a->{priority} ||
546 $a->{distance} <=> $b->{distance};
550 # Compare two mappings to decide which to try first
554 my $a_used = ( $a->{cluster}->{requests_used} * 100.0 ) / ( $a->{cluster}->{requests_limit} * 1.0 );
555 my $b_used = ( $b->{cluster}->{requests_used} * 100.0 ) / ( $b->{cluster}->{requests_limit} * 1.0 );
557 return $a_used <=> $b_used;
561 # Output DNS records for a server
565 my $zonefile = shift;
570 while (my($index,$server) = each @{$cluster->{servers}})
572 if ($all || $server->{status} eq "up")
576 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
581 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);