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 # Skip outputting server map if gdnsd is doing that
216 if (!defined($gdnsname))
218 # Output details for each country
219 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
221 my $cluster = $origin->{cluster};
222 my $clon = $origin->{lon};
223 my $clat = $origin->{lat};
224 my $slon = $cluster->{lon};
225 my $slat = $cluster->{lat};
227 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
231 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
236 $zonefile->print("# $origin->{name}\n");
237 $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
239 $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 # Header for default records
258 $zonefile->print("# Unknown origins\n");
260 # Output default records for IPs that can't be mapped to a country
261 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
263 my $name = $cluster->{name};
265 if (my $default = $cluster->{default})
267 output_server($zonefile, $jszonefile, "${default}.${zone}", "${default}.${jszone}", $cluster);
269 elsif (exists($cluster->{default}))
271 output_server($zonefile, $jszonefile, "${zone}", "${jszone}", $cluster);
276 # Header for underlying servers
277 $zonefile->print("# Servers\n");
279 # Output A records for each cluster
280 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
282 my $name = $cluster->{name};
284 output_server($zonefile, $jszonefile, "${name}.${zone}", "${name}.${jszone}", $cluster);
286 if (@{$cluster->{servers}} > 1)
288 output_server($zonefile, $jszonefile, "${name}-%02d.${zone}", "${name}-%02d.${jszone}", $cluster);
292 # Output the GeoJSON text
293 $jsonfile->print(encode_json(\@json));
296 $jszonefile->print("];\n");
298 # Close the output files
300 $jszonefile->close();
303 # Output gdnsd configuration
304 if (defined($gdnsname))
306 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
307 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
308 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
311 $gdnsmapfile->print("${gdnsname} => {\n");
312 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
313 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
314 $gdnsmapfile->print(" map => {\n");
315 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
317 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
319 my $code = $origin->{code};
320 my $cluster = $origin->{cluster}->{name};
322 next if $code eq "XK";
324 if ($continent ne $origin->{continent})
326 $gdnsmapfile->print(" }\n") if $continent;
328 $continent = $origin->{continent};
330 $gdnsmapfile->print(" ${continent} => {\n");
333 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
336 $gdnsmapfile->print(" }\n") if $continent;
338 $gdnsmapfile->print(" }\n");
339 $gdnsmapfile->print("}\n");
341 $gdnsresourcefile->print("${gdnsname} => {\n");
342 $gdnsresourcefile->print(" map => ${gdnsname}\n");
343 $gdnsresourcefile->print(" dcmap => {\n");
345 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
347 my $name = $cluster->{name};
349 if (@{$cluster->{servers}} > 1)
351 $gdnsweightedfile->print("${name} => {\n");
353 while (my($index,$server) = each @{$cluster->{servers}})
355 if ($server->{status} eq "up")
357 my $number = sprintf("%02d", $index + 1);
358 my $bandwidth = $server->{bandwidth};
360 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}., ${bandwidth} ]\n");
364 $gdnsweightedfile->print("}\n");
366 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
370 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.\n");
374 $gdnsresourcefile->print(" }\n");
375 $gdnsresourcefile->print("}\n");
377 $gdnsweightedfile->close();
378 $gdnsresourcefile->close();
379 $gdnsmapfile->close();
382 # Output the target details in origin format if required
383 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
388 # Match an origin against a cluster
396 if ($cluster->{preferred} &&
397 $cluster->{preferred}->{origins} &&
398 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
400 $match = "preferred";
402 elsif ($cluster->{allowed} &&
403 $cluster->{allowed}->{origins} &&
404 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
408 elsif ($cluster->{preferred} &&
409 $cluster->{preferred}->{countries} &&
410 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
412 $match = "preferred";
414 elsif ($cluster->{allowed} &&
415 $cluster->{allowed}->{countries} &&
416 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
420 elsif ($cluster->{denied} &&
421 $cluster->{denied}->{countries} &&
422 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
426 elsif ($cluster->{preferred} &&
427 $cluster->{preferred}->{continents} &&
428 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
430 $match = "preferred";
432 elsif ($cluster->{allowed} &&
433 $cluster->{allowed}->{continents} &&
434 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
438 elsif ($cluster->{denied} &&
439 $cluster->{denied}->{continents} &&
440 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
444 elsif ($cluster->{allowed})
457 # Compute the great circle distance between two points
461 my $lat1 = deg2rad(shift);
462 my $lon1 = deg2rad(shift);
463 my $lat2 = deg2rad(shift);
464 my $lon2 = deg2rad(shift);
466 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
470 # Allocate each origin to a cluster
472 sub allocate_clusters
474 my @mappings = sort { compare_mappings($a, $b) } @_;
476 # Loop over the mappings, trying to assign each origin to the
477 # nearest cluster, but subject to the bandwidth limits
478 while (my $mapping = shift @mappings)
482 push @group, $mapping;
484 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
486 push @group, shift @mappings;
489 for my $mapping (sort compare_bandwidth @group)
491 my $origin = $mapping->{origin};
492 my $cluster = $mapping->{cluster};
494 if (!exists($origin->{cluster}) &&
495 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
497 $origin->{cluster} = $cluster;
498 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
507 # Compare two mappings to decide which to use
514 return $b->{priority} <=> $a->{priority} ||
515 $a->{distance} <=> $b->{distance};
519 # Compare two mappings to decide which to try first
521 sub compare_bandwidth
523 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
524 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
526 return $a_used <=> $b_used;
530 # Output DNS records for a server
534 my $zonefile = shift;
535 my $jszonefile = shift;
540 while (my($index,$server) = each @{$cluster->{servers}})
542 if ($server->{status} eq "up")
544 $zonefile->printf("+${name}:$server->{ipv4}:600\n", $index + 1);
545 $jszonefile->printf(" A(\"${jsname}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
549 my $ipv6 = $server->{ipv6};
551 $ipv6 =~ s/([0-9a-f]{4})(?=.)/$1:/ig;
553 $zonefile->printf("3${name}:$server->{ipv6}:600\n", $index + 1);
554 $jszonefile->printf(" AAAA(\"${jsname}\", \"${ipv6}\", TTL(\"10m\")),\n", $index + 1);