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 $jszone = shift @ARGV;
18 my $targetoriginfile = shift @ARGV;
19 my $origins = YAML::LoadFile($originfile);
20 my $clusters = YAML::LoadFile($clusterfile);
21 my $gdnsname = shift @ARGV;
24 # Initialise cluster details
25 while (my($name,$cluster) = each %$clusters)
27 if ($cluster->{servers})
29 $cluster->{bandwidth} = 0;
31 foreach my $server (@{$cluster->{servers}})
33 $server->{cluster} = $cluster;
34 $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
36 push @servers, $server;
43 statuscake => $cluster->{statuscake},
44 bandwidth => $cluster->{bandwidth},
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_USERNAME} && $ENV{STATUSCAKE_APIKEY})
67 my $ua = LWP::UserAgent->new;
70 $ua->agent("mkgeo/1.0");
71 $ua->default_header("Username", $ENV{STATUSCAKE_USERNAME});
72 $ua->default_header("API", $ENV{STATUSCAKE_APIKEY});
74 if (-f "statuscake.yml")
76 $cache = YAML::LoadFile("statuscake.yml");
83 my $response = $ua->get("https://app.statuscake.com/API/Tests/");
85 if ($response->is_success)
87 my $tests = decode_json($response->content);
89 foreach my $test (@$tests)
91 my $testid = $test->{TestID};
93 if ($test->{Status} eq "Up" && !$test->{Paused})
95 $cache->{$testid} = "up";
99 $cache->{$testid} = "down";
104 foreach my $server (@servers)
106 if (my $testids = $server->{statuscake})
108 $server->{status} = "up";
110 for my $testid (@$testids)
112 my $testresult = $cache->{$testid} || "down";
114 $server->{status} = "down" if $testresult eq "down";
119 $server->{status} = "down";
123 YAML::DumpFile("statuscake.yml", $cache);
126 # Mark a cluster as up if any servers are up
127 foreach my $server (@servers)
129 if ($server->{status} eq "up")
131 $server->{cluster}->{status} = "up";
135 $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
139 # Create target origins object
140 my $targetorigins = {};
142 # Initialise cluster details
143 while (my($name,$cluster) = each %$clusters)
145 $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
146 $cluster->{bandwidth_used} = 0;
148 $targetorigins->{$cluster->{name}} = {
149 code => $cluster->{name},
150 name => $cluster->{name},
151 lat => $cluster->{lat},
152 lon => $cluster->{lon},
159 # Scan origins and work out which clusters each can use
160 foreach my $origin (values %$origins)
162 foreach my $cluster (values %$clusters)
164 my $match = match_origin($cluster, $origin);
166 if ($cluster->{status} eq "up" && $match ne "denied")
168 my $priority = $match eq "preferred" ? 20 : 10;
169 my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
172 origin => $origin, cluster => $cluster,
173 priority => $priority, distance => $distance
179 # Allocate each country to a cluster
180 allocate_clusters(@mappings);
182 # If we failed to allocate every origin then loop, increasing
183 # the bandwidth for each cluster by a little and retrying until
184 # we manage to allocate everything
185 while (grep { !exists($_->{cluster}) } values %$origins)
187 # Clear any existing mappings of countries to clusters
188 foreach my $origin (values %$origins)
190 delete $origin->{cluster};
193 # Reset bandwidth usage for clusters and increase limits by 10%
194 foreach my $cluster (values %$clusters)
196 $cluster->{bandwidth_used} = 0;
197 $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
200 # Try the allocate again
201 allocate_clusters(@mappings);
204 # Create JSON collection object
208 my $zonefile = IO::File->new("> data/${zone}") || die "$!";
209 my $jszonefile = IO::File->new("> include/${jszone}.js") || die "$!";
210 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
213 $jszonefile->print("var \U${jszone}\E_RECORDS = [\n");
215 # Output details for each country
216 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
218 my $cluster = $origin->{cluster};
219 my $clon = $origin->{lon};
220 my $clat = $origin->{lat};
221 my $slon = $cluster->{lon};
222 my $slat = $cluster->{lat};
224 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
228 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
233 if (!defined($gdnsname))
235 $zonefile->print("# $origin->{name}\n");
236 $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
238 $jszonefile->print(" CNAME(\"\L$origin->{code}\E.${jszone}\", \"$cluster->{name}.${zone}.\", TTL(\"10m\")),\n");
244 type => "LineString",
245 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
248 origin => $origin->{name},
249 server => $cluster->{name},
250 colour => $cluster->{colour}
254 $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
257 # Skip default records if we don't need them
258 if (!defined($gdnsname))
260 # Header for default records
261 $zonefile->print("# Unknown origins\n");
263 # Output default records for IPs that can't be mapped to a country
264 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
266 my $name = $cluster->{name};
268 if (my $default = $cluster->{default})
270 output_server($zonefile, $jszonefile, "${default}.${zone}", "${default}.${jszone}", $cluster);
272 elsif (exists($cluster->{default}))
274 output_server($zonefile, $jszonefile, "${zone}", "${jszone}", $cluster);
279 # Header for underlying servers
280 $zonefile->print("# Servers\n");
282 # Output A records for each cluster
283 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
285 my $name = $cluster->{name};
287 output_server($zonefile, $jszonefile, "${name}.${zone}", "${name}.${jszone}", $cluster);
289 if (@{$cluster->{servers}} > 1)
291 output_server($zonefile, $jszonefile, "${name}-%02d.${zone}", "${name}-%02d.${jszone}", $cluster);
295 # Output the GeoJSON text
296 $jsonfile->print(encode_json(\@json));
299 $jszonefile->print("];\n");
301 # Close the output files
303 $jszonefile->close();
306 # Output gdnsd configuration
307 if (defined($gdnsname))
309 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
310 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
311 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
314 $gdnsmapfile->print("${gdnsname} => {\n");
315 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
316 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
317 $gdnsmapfile->print(" map => {\n");
318 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
320 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
322 my $code = $origin->{code};
323 my $cluster = $origin->{cluster}->{name};
325 next if $code eq "XK";
327 if ($continent ne $origin->{continent})
329 $gdnsmapfile->print(" }\n") if $continent;
331 $continent = $origin->{continent};
333 $gdnsmapfile->print(" ${continent} => {\n");
336 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
339 $gdnsmapfile->print(" }\n") if $continent;
341 $gdnsmapfile->print(" }\n");
342 $gdnsmapfile->print("}\n");
344 $gdnsresourcefile->print("${gdnsname} => {\n");
345 $gdnsresourcefile->print(" map => ${gdnsname}\n");
346 $gdnsresourcefile->print(" dcmap => {\n");
348 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
350 my $name = $cluster->{name};
352 if (@{$cluster->{servers}} > 1)
354 $gdnsweightedfile->print("${name} => {\n");
356 while (my($index,$server) = each @{$cluster->{servers}})
358 if ($server->{status} eq "up")
360 my $number = sprintf("%02d", $index + 1);
361 my $bandwidth = $server->{bandwidth};
363 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}., ${bandwidth} ]\n");
367 $gdnsweightedfile->print("}\n");
369 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
373 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.\n");
377 $gdnsresourcefile->print(" }\n");
378 $gdnsresourcefile->print("}\n");
380 $gdnsweightedfile->close();
381 $gdnsresourcefile->close();
382 $gdnsmapfile->close();
385 # Output the target details in origin format if required
386 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
391 # Match an origin against a cluster
399 if ($cluster->{preferred} &&
400 $cluster->{preferred}->{origins} &&
401 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
403 $match = "preferred";
405 elsif ($cluster->{allowed} &&
406 $cluster->{allowed}->{origins} &&
407 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
411 elsif ($cluster->{preferred} &&
412 $cluster->{preferred}->{countries} &&
413 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
415 $match = "preferred";
417 elsif ($cluster->{allowed} &&
418 $cluster->{allowed}->{countries} &&
419 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
423 elsif ($cluster->{denied} &&
424 $cluster->{denied}->{countries} &&
425 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
429 elsif ($cluster->{preferred} &&
430 $cluster->{preferred}->{continents} &&
431 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
433 $match = "preferred";
435 elsif ($cluster->{allowed} &&
436 $cluster->{allowed}->{continents} &&
437 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
441 elsif ($cluster->{denied} &&
442 $cluster->{denied}->{continents} &&
443 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
447 elsif ($cluster->{allowed})
460 # Compute the great circle distance between two points
464 my $lat1 = deg2rad(shift);
465 my $lon1 = deg2rad(shift);
466 my $lat2 = deg2rad(shift);
467 my $lon2 = deg2rad(shift);
469 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
473 # Allocate each origin to a cluster
475 sub allocate_clusters
477 my @mappings = sort { compare_mappings($a, $b) } @_;
479 # Loop over the mappings, trying to assign each origin to the
480 # nearest cluster, but subject to the bandwidth limits
481 while (my $mapping = shift @mappings)
485 push @group, $mapping;
487 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
489 push @group, shift @mappings;
492 for my $mapping (sort compare_bandwidth @group)
494 my $origin = $mapping->{origin};
495 my $cluster = $mapping->{cluster};
497 if (!exists($origin->{cluster}) &&
498 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
500 $origin->{cluster} = $cluster;
501 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
510 # Compare two mappings to decide which to use
517 return $b->{priority} <=> $a->{priority} ||
518 $a->{distance} <=> $b->{distance};
522 # Compare two mappings to decide which to try first
524 sub compare_bandwidth
526 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
527 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
529 return $a_used <=> $b_used;
533 # Output DNS records for a server
537 my $zonefile = shift;
538 my $jszonefile = shift;
543 while (my($index,$server) = each @{$cluster->{servers}})
545 if ($server->{status} eq "up")
547 $zonefile->printf("+${name}:$server->{ipv4}:600\n", $index + 1);
548 $jszonefile->printf(" A(\"${jsname}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
552 my $ipv6 = $server->{ipv6};
554 $ipv6 =~ s/([0-9a-f]{4})(?=.)/$1:/ig;
556 $zonefile->printf("3${name}:$server->{ipv6}:600\n", $index + 1);
557 $jszonefile->printf(" AAAA(\"${jsname}\", \"${ipv6}\", TTL(\"10m\")),\n", $index + 1);