9 use Math::Trig qw(deg2rad pip2 great_circle_distance);
14 my $originfile = shift @ARGV;
15 my $clusterfile = shift @ARGV;
16 my $zone = shift @ARGV;
17 my $targetoriginfile = shift @ARGV;
18 my $origins = YAML::LoadFile($originfile);
19 my $clusters = YAML::LoadFile($clusterfile);
20 my $gdnsname = shift @ARGV;
23 # Initialise cluster details
24 while (my($name,$cluster) = each %$clusters)
26 if ($cluster->{servers})
28 $cluster->{bandwidth} = 0;
30 foreach my $server (@{$cluster->{servers}})
32 $server->{cluster} = $cluster;
33 $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
35 push @servers, $server;
42 statuscake => $cluster->{statuscake},
43 bandwidth => $cluster->{bandwidth},
44 ipv4 => $cluster->{ipv4},
45 ipv6 => $cluster->{ipv6}
48 $cluster->{servers} = [ $server ];
50 push @servers, $server;
53 $cluster->{name} = $name;
54 $cluster->{status} = "down";
57 # Initialise server details
58 foreach my $server (@servers)
60 $server->{status} = "up";
63 # If statuscake support is enabled then check which servers are up
64 if ($ENV{STATUSCAKE_USERNAME} && $ENV{STATUSCAKE_APIKEY})
66 my $ua = LWP::UserAgent->new;
69 $ua->agent("mkgeo/1.0");
70 $ua->default_header("Username", $ENV{STATUSCAKE_USERNAME});
71 $ua->default_header("API", $ENV{STATUSCAKE_APIKEY});
73 if (-f "statuscake.yml")
75 $cache = YAML::LoadFile("statuscake.yml");
82 my $response = $ua->get("https://app.statuscake.com/API/Tests/");
84 if ($response->is_success)
86 my $tests = decode_json($response->content);
88 foreach my $test (@$tests)
90 my $testid = $test->{TestID};
92 if ($test->{Status} eq "Up" && !$test->{Paused})
94 $cache->{$testid} = "up";
98 $cache->{$testid} = "down";
103 foreach my $server (@servers)
105 if (my $testids = $server->{statuscake})
107 $server->{status} = "up";
109 for my $testid (@$testids)
111 my $testresult = $cache->{$testid} || "down";
113 $server->{status} = "down" if $testresult eq "down";
118 $server->{status} = "down";
122 YAML::DumpFile("statuscake.yml", $cache);
125 # Mark a cluster as up if any servers are up
126 foreach my $server (@servers)
128 if ($server->{status} eq "up")
130 $server->{cluster}->{status} = "up";
134 $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
138 # Create target origins object
139 my $targetorigins = {};
141 # Initialise cluster details
142 while (my($name,$cluster) = each %$clusters)
144 $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
145 $cluster->{bandwidth_used} = 0;
147 $targetorigins->{$cluster->{name}} = {
148 code => $cluster->{name},
149 name => $cluster->{name},
150 lat => $cluster->{lat},
151 lon => $cluster->{lon},
158 # Scan origins and work out which clusters each can use
159 foreach my $origin (values %$origins)
161 foreach my $cluster (values %$clusters)
163 my $match = match_origin($cluster, $origin);
165 if ($cluster->{status} eq "up" && $match ne "denied")
167 my $priority = $match eq "preferred" ? 20 : 10;
168 my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
171 origin => $origin, cluster => $cluster,
172 priority => $priority, distance => $distance
178 # Allocate each country to a cluster
179 allocate_clusters(@mappings);
181 # If we failed to allocate every origin then loop, increasing
182 # the bandwidth for each cluster by a little and retrying until
183 # we manage to allocate everything
184 while (grep { !exists($_->{cluster}) } values %$origins)
186 # Clear any existing mappings of countries to clusters
187 foreach my $origin (values %$origins)
189 delete $origin->{cluster};
192 # Reset bandwidth usage for clusters and increase limits by 10%
193 foreach my $cluster (values %$clusters)
195 $cluster->{bandwidth_used} = 0;
196 $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
199 # Try the allocate again
200 allocate_clusters(@mappings);
203 # Create JSON collection object
207 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
208 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
211 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
213 # Output details for each country
214 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
216 my $cluster = $origin->{cluster};
217 my $clon = $origin->{lon};
218 my $clat = $origin->{lat};
219 my $slon = $cluster->{lon};
220 my $slat = $cluster->{lat};
222 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
226 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
231 if (!defined($gdnsname))
233 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
239 type => "LineString",
240 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
243 origin => $origin->{name},
244 server => $cluster->{name},
245 colour => $cluster->{colour}
249 $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
252 # Skip default records if we don't need them
253 if (!defined($gdnsname))
255 # Output default records for IPs that can't be mapped to a country
256 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
258 my $name = $cluster->{name};
260 if (my $default = $cluster->{default})
262 output_server($zonefile, "${default}.${zone}", $cluster);
264 elsif (exists($cluster->{default}))
266 output_server($zonefile, "${zone}", $cluster);
271 # Output A records for each cluster
272 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
274 my $name = $cluster->{name};
276 output_server($zonefile, "${name}.${zone}", $cluster);
278 if (@{$cluster->{servers}} > 1)
280 output_server($zonefile, "${name}-%02d.${zone}", $cluster);
284 # Output the GeoJSON text
285 $jsonfile->print(encode_json(\@json));
288 $zonefile->print("];\n");
290 # Close the output files
294 # Output gdnsd configuration
295 if (defined($gdnsname))
297 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
298 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
299 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
302 $gdnsmapfile->print("${gdnsname} => {\n");
303 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
304 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
305 $gdnsmapfile->print(" map => {\n");
306 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
308 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
310 my $code = $origin->{code};
311 my $cluster = $origin->{cluster}->{name};
313 next if $code eq "XK";
315 if ($continent ne $origin->{continent})
317 $gdnsmapfile->print(" }\n") if $continent;
319 $continent = $origin->{continent};
321 $gdnsmapfile->print(" ${continent} => {\n");
324 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
327 $gdnsmapfile->print(" }\n") if $continent;
329 $gdnsmapfile->print(" }\n");
330 $gdnsmapfile->print("}\n");
332 $gdnsresourcefile->print("${gdnsname} => {\n");
333 $gdnsresourcefile->print(" map => ${gdnsname}\n");
334 $gdnsresourcefile->print(" dcmap => {\n");
336 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
338 my $name = $cluster->{name};
340 if (@{$cluster->{servers}} > 1)
342 $gdnsweightedfile->print("${name} => {\n");
344 while (my($index,$server) = each @{$cluster->{servers}})
346 if ($server->{status} eq "up")
348 my $number = sprintf("%02d", $index + 1);
349 my $bandwidth = $server->{bandwidth};
351 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}., ${bandwidth} ]\n");
355 $gdnsweightedfile->print("}\n");
357 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
361 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.\n");
365 $gdnsresourcefile->print(" }\n");
366 $gdnsresourcefile->print("}\n");
368 $gdnsweightedfile->close();
369 $gdnsresourcefile->close();
370 $gdnsmapfile->close();
373 # Output the target details in origin format if required
374 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
379 # Match an origin against a cluster
387 if ($cluster->{preferred} &&
388 $cluster->{preferred}->{origins} &&
389 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
391 $match = "preferred";
393 elsif ($cluster->{allowed} &&
394 $cluster->{allowed}->{origins} &&
395 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
399 elsif ($cluster->{preferred} &&
400 $cluster->{preferred}->{countries} &&
401 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
403 $match = "preferred";
405 elsif ($cluster->{allowed} &&
406 $cluster->{allowed}->{countries} &&
407 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
411 elsif ($cluster->{denied} &&
412 $cluster->{denied}->{countries} &&
413 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
417 elsif ($cluster->{preferred} &&
418 $cluster->{preferred}->{continents} &&
419 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
421 $match = "preferred";
423 elsif ($cluster->{allowed} &&
424 $cluster->{allowed}->{continents} &&
425 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
429 elsif ($cluster->{denied} &&
430 $cluster->{denied}->{continents} &&
431 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
435 elsif ($cluster->{allowed})
448 # Compute the great circle distance between two points
452 my $lat1 = deg2rad(shift);
453 my $lon1 = deg2rad(shift);
454 my $lat2 = deg2rad(shift);
455 my $lon2 = deg2rad(shift);
457 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
461 # Allocate each origin to a cluster
463 sub allocate_clusters
465 my @mappings = sort { compare_mappings($a, $b) } @_;
467 # Loop over the mappings, trying to assign each origin to the
468 # nearest cluster, but subject to the bandwidth limits
469 while (my $mapping = shift @mappings)
473 push @group, $mapping;
475 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
477 push @group, shift @mappings;
480 for my $mapping (sort compare_bandwidth @group)
482 my $origin = $mapping->{origin};
483 my $cluster = $mapping->{cluster};
485 if (!exists($origin->{cluster}) &&
486 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
488 $origin->{cluster} = $cluster;
489 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
498 # Compare two mappings to decide which to use
505 return $b->{priority} <=> $a->{priority} ||
506 $a->{distance} <=> $b->{distance};
510 # Compare two mappings to decide which to try first
512 sub compare_bandwidth
514 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
515 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
517 return $a_used <=> $b_used;
521 # Output DNS records for a server
525 my $zonefile = shift;
529 while (my($index,$server) = each @{$cluster->{servers}})
531 if ($server->{status} eq "up")
533 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
537 my $ipv6 = $server->{ipv6};
539 $ipv6 =~ s/([0-9a-f]{4})(?=.)/$1:/ig;
541 $zonefile->printf(" AAAA(\"${name}\", \"${ipv6}\", TTL(\"10m\")),\n", $index + 1);