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 $zonefile->print("# $origin->{name}\n");
234 $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
236 $jszonefile->print(" CNAME(\"\L$origin->{code}\E.${jszone}\", \"$cluster->{name}.${zone}.\", TTL(\"10m\")),\n");
241 type => "LineString",
242 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
245 origin => $origin->{name},
246 server => $cluster->{name},
247 colour => $cluster->{colour}
251 $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
254 # Header for default records
255 $zonefile->print("# Unknown origins\n");
257 # Output default records for IPs that can't be mapped to a country
258 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
260 my $name = $cluster->{name};
262 if (my $default = $cluster->{default})
264 output_server($zonefile, $jszonefile, "${default}.${zone}", "${default}.${jszone}", $cluster);
266 elsif (exists($cluster->{default}))
268 output_server($zonefile, $jszonefile, "${zone}", "${jszone}", $cluster);
272 # Header for underlying servers
273 $zonefile->print("# Servers\n");
275 # Output A records for each cluster
276 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
278 my $name = $cluster->{name};
280 output_server($zonefile, $jszonefile, "${name}.${zone}", "${name}.${jszone}", $cluster);
282 if (@{$cluster->{servers}} > 1)
284 output_server($zonefile, $jszonefile, "${name}-%02d.${zone}", "${name}-%02d.${jszone}", $cluster);
288 # Output the GeoJSON text
289 $jsonfile->print(encode_json(\@json));
292 $jszonefile->print("];\n");
294 # Close the output files
296 $jszonefile->close();
299 # Output gdnsd configuration
300 if (defined($gdnsname))
302 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
303 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
304 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
307 $gdnsmapfile->print("${gdnsname} => {\n");
308 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
309 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
310 $gdnsmapfile->print(" map => {\n");
311 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
313 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
315 my $code = $origin->{code};
316 my $cluster = $origin->{cluster}->{name};
318 next if $code eq "XK";
320 if ($continent ne $origin->{continent})
322 $gdnsmapfile->print(" }\n") if $continent;
324 $continent = $origin->{continent};
326 $gdnsmapfile->print(" ${continent} => {\n");
329 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
332 $gdnsmapfile->print(" }\n") if $continent;
334 $gdnsmapfile->print(" }\n");
335 $gdnsmapfile->print("}\n");
337 $gdnsresourcefile->print("${gdnsname} => {\n");
338 $gdnsresourcefile->print(" map => ${gdnsname}\n");
339 $gdnsresourcefile->print(" dcmap => {\n");
341 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
343 my $name = $cluster->{name};
345 if (@{$cluster->{servers}} > 1)
347 $gdnsweightedfile->print("${name} => {\n");
349 while (my($index,$server) = each @{$cluster->{servers}})
351 if ($server->{status} eq "up")
353 my $number = sprintf("%02d", $index + 1);
354 my $bandwidth = $server->{bandwidth};
356 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}., ${bandwidth} ]\n");
360 $gdnsweightedfile->print("}\n");
362 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
366 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.\n");
370 $gdnsresourcefile->print(" }\n");
371 $gdnsresourcefile->print("}\n");
373 $gdnsweightedfile->close();
374 $gdnsresourcefile->close();
375 $gdnsmapfile->close();
378 # Output the target details in origin format if required
379 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
384 # Match an origin against a cluster
392 if ($cluster->{preferred} &&
393 $cluster->{preferred}->{origins} &&
394 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
396 $match = "preferred";
398 elsif ($cluster->{allowed} &&
399 $cluster->{allowed}->{origins} &&
400 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
404 elsif ($cluster->{preferred} &&
405 $cluster->{preferred}->{countries} &&
406 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
408 $match = "preferred";
410 elsif ($cluster->{allowed} &&
411 $cluster->{allowed}->{countries} &&
412 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
416 elsif ($cluster->{denied} &&
417 $cluster->{denied}->{countries} &&
418 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
422 elsif ($cluster->{preferred} &&
423 $cluster->{preferred}->{continents} &&
424 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
426 $match = "preferred";
428 elsif ($cluster->{allowed} &&
429 $cluster->{allowed}->{continents} &&
430 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
434 elsif ($cluster->{denied} &&
435 $cluster->{denied}->{continents} &&
436 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
440 elsif ($cluster->{allowed})
453 # Compute the great circle distance between two points
457 my $lat1 = deg2rad(shift);
458 my $lon1 = deg2rad(shift);
459 my $lat2 = deg2rad(shift);
460 my $lon2 = deg2rad(shift);
462 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
466 # Allocate each origin to a cluster
468 sub allocate_clusters
470 my @mappings = sort { compare_mappings($a, $b) } @_;
472 # Loop over the mappings, trying to assign each origin to the
473 # nearest cluster, but subject to the bandwidth limits
474 while (my $mapping = shift @mappings)
478 push @group, $mapping;
480 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
482 push @group, shift @mappings;
485 for my $mapping (sort compare_bandwidth @group)
487 my $origin = $mapping->{origin};
488 my $cluster = $mapping->{cluster};
490 if (!exists($origin->{cluster}) &&
491 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
493 $origin->{cluster} = $cluster;
494 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
503 # Compare two mappings to decide which to use
510 return $b->{priority} <=> $a->{priority} ||
511 $a->{distance} <=> $b->{distance};
515 # Compare two mappings to decide which to try first
517 sub compare_bandwidth
519 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
520 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
522 return $a_used <=> $b_used;
526 # Output DNS records for a server
530 my $zonefile = shift;
531 my $jszonefile = shift;
536 while (my($index,$server) = each @{$cluster->{servers}})
538 if ($server->{status} eq "up")
540 $zonefile->printf("+${name}:$server->{ipv4}:600\n", $index + 1);
541 $jszonefile->printf(" A(\"${jsname}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
545 my $ipv6 = $server->{ipv6};
547 $ipv6 =~ s/([0-9a-f]{4})(?=.)/$1:/ig;
549 $zonefile->printf("3${name}:$server->{ipv6}:600\n", $index + 1);
550 $jszonefile->printf(" AAAA(\"${jsname}\", \"${ipv6}\", TTL(\"10m\")),\n", $index + 1);