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->{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 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_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 = 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 DumpFile("statuscake-$$.yml", $cache);
124 rename("statuscake-$$.yml", "statuscake.yml");
127 # Mark a cluster as up if any servers are up
128 foreach my $server (@servers)
130 if ($server->{status} eq "up")
132 $server->{cluster}->{status} = "up";
136 $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
140 # Create target origins object
141 my $targetorigins = {};
143 # Initialise cluster details
144 while (my($name,$cluster) = each %$clusters)
146 $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
147 $cluster->{bandwidth_used} = 0;
149 next if $cluster->{global};
151 $targetorigins->{$cluster->{name}} = {
152 code => $cluster->{name},
153 name => $cluster->{name},
154 lat => $cluster->{lat},
155 lon => $cluster->{lon},
162 # Scan origins and work out which clusters each can use
163 foreach my $origin (values %$origins)
165 foreach my $cluster (values %$clusters)
167 my $match = match_origin($cluster, $origin);
169 if ($cluster->{status} eq "up" && $match ne "denied")
171 my $priority = $match eq "preferred" ? 20 : 10;
174 if ($cluster->{global})
180 $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
184 origin => $origin, cluster => $cluster,
185 priority => $priority, distance => $distance
191 # Allocate each country to a cluster
192 allocate_clusters(@mappings);
194 # If we failed to allocate every origin then loop, increasing
195 # the bandwidth for each cluster by a little and retrying until
196 # we manage to allocate everything
197 while (grep { !exists($_->{cluster}) } values %$origins)
199 # Clear any existing mappings of countries to clusters
200 foreach my $origin (values %$origins)
202 delete $origin->{cluster};
205 # Reset bandwidth usage for clusters and increase limits by 10%
206 foreach my $cluster (values %$clusters)
208 $cluster->{bandwidth_used} = 0;
209 $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
212 # Try the allocate again
213 allocate_clusters(@mappings);
216 # Create JSON collection object
220 my $zonefile = IO::File->new("> include/${zone}.js") || die "$!";
221 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
224 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
226 # Output details for each country
227 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
229 my $cluster = $origin->{cluster};
231 if (!defined($gdnsname))
233 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
236 if ($cluster->{lon} && $cluster->{lat})
238 my $clon = $origin->{lon};
239 my $clat = $origin->{lat};
240 my $slon = $cluster->{lon};
241 my $slat = $cluster->{lat};
243 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
247 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
255 type => "LineString",
256 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
259 origin => $origin->{name},
260 server => $cluster->{name},
261 colour => $cluster->{colour}
266 $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
269 # Skip default records if we don't need them
270 if (!defined($gdnsname))
272 # Output default records for IPs that can't be mapped to a country
273 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
275 my $name = $cluster->{name};
277 if (my $default = $cluster->{default})
279 output_server($zonefile, "${default}.${zone}", $cluster, 0);
281 elsif (exists($cluster->{default}))
283 output_server($zonefile, "${zone}", $cluster, 0);
288 # Output A records for each cluster
289 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
291 my $name = $cluster->{name};
293 if (@{$cluster->{servers}} > 1)
295 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
299 output_server($zonefile, "${name}.${zone}", $cluster, 1);
303 # Output the GeoJSON text
304 $jsonfile->print(encode_json(\@json));
307 $zonefile->print("];\n");
309 # Close the output files
313 # Output gdnsd configuration
314 if (defined($gdnsname))
316 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
317 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
318 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
321 $gdnsmapfile->print("${gdnsname} => {\n");
322 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
323 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
324 $gdnsmapfile->print(" map => {\n");
325 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
327 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
329 my $code = $origin->{code};
330 my $cluster = $origin->{cluster}->{name};
332 next if $code eq "XK";
334 if ($continent ne $origin->{continent})
336 $gdnsmapfile->print(" }\n") if $continent;
338 $continent = $origin->{continent};
340 $gdnsmapfile->print(" ${continent} => {\n");
343 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
346 $gdnsmapfile->print(" }\n") if $continent;
348 $gdnsmapfile->print(" }\n");
349 $gdnsmapfile->print("}\n");
351 $gdnsresourcefile->print("${gdnsname} => {\n");
352 $gdnsresourcefile->print(" map => ${gdnsname}\n");
353 $gdnsresourcefile->print(" dcmap => {\n");
355 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
357 my $name = $cluster->{name};
359 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
361 $gdnsweightedfile->print("${name} => {\n");
363 while (my($index,$server) = each @{$cluster->{servers}})
365 if ($server->{status} eq "up")
367 my $number = sprintf("%02d", $index + 1);
368 my $bandwidth = $server->{bandwidth};
370 if (my $cname = $server->{cname})
372 $gdnsweightedfile->print(" ${name}-${number} = [ ${cname}., ${bandwidth} ]\n");
376 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${bandwidth} ]\n");
381 $gdnsweightedfile->print("}\n");
383 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
385 elsif (my $cname = $cluster->{cname})
387 $gdnsresourcefile->print(" ${name} => ${cname}.\n");
391 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
395 $gdnsresourcefile->print(" }\n");
396 $gdnsresourcefile->print("}\n");
398 $gdnsweightedfile->close();
399 $gdnsresourcefile->close();
400 $gdnsmapfile->close();
403 # Output the target details in origin format if required
404 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
409 # Match an origin against a cluster
417 if ($cluster->{preferred} &&
418 $cluster->{preferred}->{origins} &&
419 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
421 $match = "preferred";
423 elsif ($cluster->{allowed} &&
424 $cluster->{allowed}->{origins} &&
425 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
429 elsif ($cluster->{preferred} &&
430 $cluster->{preferred}->{countries} &&
431 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
433 $match = "preferred";
435 elsif ($cluster->{allowed} &&
436 $cluster->{allowed}->{countries} &&
437 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
441 elsif ($cluster->{denied} &&
442 $cluster->{denied}->{countries} &&
443 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
447 elsif ($cluster->{preferred} &&
448 $cluster->{preferred}->{continents} &&
449 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
451 $match = "preferred";
453 elsif ($cluster->{allowed} &&
454 $cluster->{allowed}->{continents} &&
455 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
459 elsif ($cluster->{denied} &&
460 $cluster->{denied}->{continents} &&
461 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
465 elsif ($cluster->{allowed})
478 # Compute the great circle distance between two points
482 my $lat1 = deg2rad(shift);
483 my $lon1 = deg2rad(shift);
484 my $lat2 = deg2rad(shift);
485 my $lon2 = deg2rad(shift);
487 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
491 # Allocate each origin to a cluster
493 sub allocate_clusters
495 my @mappings = sort { compare_mappings($a, $b) } @_;
497 # Loop over the mappings, trying to assign each origin to the
498 # nearest cluster, but subject to the bandwidth limits
499 while (my $mapping = shift @mappings)
503 push @group, $mapping;
505 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
507 push @group, shift @mappings;
510 for my $mapping (sort compare_bandwidth @group)
512 my $origin = $mapping->{origin};
513 my $cluster = $mapping->{cluster};
515 if (!exists($origin->{cluster}) &&
516 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
518 $origin->{cluster} = $cluster;
519 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
528 # Compare two mappings to decide which to use
535 return $b->{priority} <=> $a->{priority} ||
536 $a->{distance} <=> $b->{distance};
540 # Compare two mappings to decide which to try first
542 sub compare_bandwidth
544 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
545 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
547 return $a_used <=> $b_used;
551 # Output DNS records for a server
555 my $zonefile = shift;
560 while (my($index,$server) = each @{$cluster->{servers}})
562 if ($all || $server->{status} eq "up")
566 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
571 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);