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 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 = 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 DumpFile("statuscake-$$.yml", $cache);
123 link("statuscake-$$.yml", "statuscake.yml");
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("> include/${zone}.js") || die "$!";
209 my $jsonfile = IO::File->new("> json/${zone}.openstreetmap.org.json") || die "$!";
212 $zonefile->print("var \U${zone}\E_RECORDS = [\n");
214 # Output details for each country
215 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
217 my $cluster = $origin->{cluster};
218 my $clon = $origin->{lon};
219 my $clat = $origin->{lat};
220 my $slon = $cluster->{lon};
221 my $slat = $cluster->{lat};
223 if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
227 elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
232 if (!defined($gdnsname))
234 $zonefile->print(" CNAME(\"\L$origin->{code}\E.${zone}\", \"$cluster->{name}.${zone}.openstreetmap.org.\", TTL(\"10m\")),\n");
240 type => "LineString",
241 coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
244 origin => $origin->{name},
245 server => $cluster->{name},
246 colour => $cluster->{colour}
250 $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
253 # Skip default records if we don't need them
254 if (!defined($gdnsname))
256 # Output default records for IPs that can't be mapped to a country
257 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
259 my $name = $cluster->{name};
261 if (my $default = $cluster->{default})
263 output_server($zonefile, "${default}.${zone}", $cluster, 0);
265 elsif (exists($cluster->{default}))
267 output_server($zonefile, "${zone}", $cluster, 0);
272 # Output A records for each cluster
273 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
275 my $name = $cluster->{name};
277 if (@{$cluster->{servers}} > 1)
279 output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
283 output_server($zonefile, "${name}.${zone}", $cluster, 1);
287 # Output the GeoJSON text
288 $jsonfile->print(encode_json(\@json));
291 $zonefile->print("];\n");
293 # Close the output files
297 # Output gdnsd configuration
298 if (defined($gdnsname))
300 my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
301 my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
302 my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
305 $gdnsmapfile->print("${gdnsname} => {\n");
306 $gdnsmapfile->print(" geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
307 $gdnsmapfile->print(" datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
308 $gdnsmapfile->print(" map => {\n");
309 $gdnsmapfile->print(" default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
311 foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
313 my $code = $origin->{code};
314 my $cluster = $origin->{cluster}->{name};
316 next if $code eq "XK";
318 if ($continent ne $origin->{continent})
320 $gdnsmapfile->print(" }\n") if $continent;
322 $continent = $origin->{continent};
324 $gdnsmapfile->print(" ${continent} => {\n");
327 $gdnsmapfile->print(" ${code} => [${cluster}]\n");
330 $gdnsmapfile->print(" }\n") if $continent;
332 $gdnsmapfile->print(" }\n");
333 $gdnsmapfile->print("}\n");
335 $gdnsresourcefile->print("${gdnsname} => {\n");
336 $gdnsresourcefile->print(" map => ${gdnsname}\n");
337 $gdnsresourcefile->print(" dcmap => {\n");
339 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
341 my $name = $cluster->{name};
343 if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
345 $gdnsweightedfile->print("${name} => {\n");
347 while (my($index,$server) = each @{$cluster->{servers}})
349 if ($server->{status} eq "up")
351 my $number = sprintf("%02d", $index + 1);
352 my $bandwidth = $server->{bandwidth};
354 $gdnsweightedfile->print(" ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${bandwidth} ]\n");
358 $gdnsweightedfile->print("}\n");
360 $gdnsresourcefile->print(" ${name} => %weighted!${name}\n");
364 $gdnsresourcefile->print(" ${name} => ${name}.${zone}.openstreetmap.org.\n");
368 $gdnsresourcefile->print(" }\n");
369 $gdnsresourcefile->print("}\n");
371 $gdnsweightedfile->close();
372 $gdnsresourcefile->close();
373 $gdnsmapfile->close();
376 # Output the target details in origin format if required
377 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
382 # Match an origin against a cluster
390 if ($cluster->{preferred} &&
391 $cluster->{preferred}->{origins} &&
392 grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
394 $match = "preferred";
396 elsif ($cluster->{allowed} &&
397 $cluster->{allowed}->{origins} &&
398 grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
402 elsif ($cluster->{preferred} &&
403 $cluster->{preferred}->{countries} &&
404 grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
406 $match = "preferred";
408 elsif ($cluster->{allowed} &&
409 $cluster->{allowed}->{countries} &&
410 grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
414 elsif ($cluster->{denied} &&
415 $cluster->{denied}->{countries} &&
416 grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
420 elsif ($cluster->{preferred} &&
421 $cluster->{preferred}->{continents} &&
422 grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
424 $match = "preferred";
426 elsif ($cluster->{allowed} &&
427 $cluster->{allowed}->{continents} &&
428 grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
432 elsif ($cluster->{denied} &&
433 $cluster->{denied}->{continents} &&
434 grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
438 elsif ($cluster->{allowed})
451 # Compute the great circle distance between two points
455 my $lat1 = deg2rad(shift);
456 my $lon1 = deg2rad(shift);
457 my $lat2 = deg2rad(shift);
458 my $lon2 = deg2rad(shift);
460 return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
464 # Allocate each origin to a cluster
466 sub allocate_clusters
468 my @mappings = sort { compare_mappings($a, $b) } @_;
470 # Loop over the mappings, trying to assign each origin to the
471 # nearest cluster, but subject to the bandwidth limits
472 while (my $mapping = shift @mappings)
476 push @group, $mapping;
478 while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
480 push @group, shift @mappings;
483 for my $mapping (sort compare_bandwidth @group)
485 my $origin = $mapping->{origin};
486 my $cluster = $mapping->{cluster};
488 if (!exists($origin->{cluster}) &&
489 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
491 $origin->{cluster} = $cluster;
492 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
501 # Compare two mappings to decide which to use
508 return $b->{priority} <=> $a->{priority} ||
509 $a->{distance} <=> $b->{distance};
513 # Compare two mappings to decide which to try first
515 sub compare_bandwidth
517 my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
518 my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
520 return $a_used <=> $b_used;
524 # Output DNS records for a server
528 my $zonefile = shift;
533 while (my($index,$server) = each @{$cluster->{servers}})
535 if ($all || $server->{status} eq "up")
537 $zonefile->printf(" A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
541 $zonefile->printf(" AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);