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 $targetoriginfile = shift @ARGV;
 
  18 my $origins = YAML::LoadFile($originfile);
 
  19 my $clusters = YAML::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 = YAML::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     YAML::DumpFile("statuscake.yml", $cache);
 
 125 # Mark a cluster as up if any servers are up
 
 126 foreach my $server (@servers)
 
 128     if ($server->{status} eq "up")
 
 130         $server->{cluster}->{status} = "up";
 
 134         $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
 
 138 # Create target origins object
 
 139 my $targetorigins = {};
 
 141 # Initialise cluster details
 
 142 while (my($name,$cluster) = each %$clusters)
 
 144     $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
 
 145     $cluster->{bandwidth_used} = 0;
 
 147     $targetorigins->{$cluster->{name}} = {
 
 148         code => $cluster->{name},
 
 149         name => $cluster->{name},
 
 150         lat => $cluster->{lat},
 
 151         lon => $cluster->{lon},
 
 158 # Scan origins and work out which clusters each can use
 
 159 foreach my $origin (values %$origins)
 
 161     foreach my $cluster (values %$clusters)
 
 163         my $match = match_origin($cluster, $origin);
 
 165         if ($cluster->{status} eq "up" && $match ne "denied")
 
 167             my $priority = $match eq "preferred" ? 20 : 10;
 
 168             my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
 
 171                 origin => $origin, cluster => $cluster,
 
 172                 priority => $priority, distance => $distance
 
 178 # Allocate each country to a cluster
 
 179 allocate_clusters(@mappings);
 
 181 # If we failed to allocate every origin then loop, increasing
 
 182 # the bandwidth for each cluster by a little and retrying until
 
 183 # we manage to allocate everything
 
 184 while (grep { !exists($_->{cluster}) } values %$origins)
 
 186     # Clear any existing mappings of countries to clusters
 
 187     foreach my $origin (values %$origins)
 
 189         delete $origin->{cluster};
 
 192     # Reset bandwidth usage for clusters and increase limits by 10%
 
 193     foreach my $cluster (values %$clusters)
 
 195         $cluster->{bandwidth_used} = 0;
 
 196         $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
 
 199     # Try the allocate again
 
 200     allocate_clusters(@mappings);
 
 203 # Create JSON collection object
 
 207 my $zonefile = IO::File->new("> data/${zone}") || die "$!";
 
 208 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
 
 210 # Output details for each country
 
 211 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
 
 213     my $cluster = $origin->{cluster};
 
 214     my $clon = $origin->{lon};
 
 215     my $clat = $origin->{lat};
 
 216     my $slon = $cluster->{lon};
 
 217     my $slat = $cluster->{lat};
 
 219     if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
 
 223     elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
 
 228     $zonefile->print("# $origin->{name}\n");
 
 229     $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
 
 234             type => "LineString",
 
 235             coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
 
 238             origin => $origin->{name},
 
 239             server => $cluster->{name},
 
 240             colour => $cluster->{colour}
 
 244     $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
 
 247 # Header for default records
 
 248 $zonefile->print("# Unknown origins\n");
 
 250 # Output default records for IPs that can't be mapped to a country
 
 251 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 253     my $name = $cluster->{name};
 
 255     if (my $default = $cluster->{default})
 
 257         output_server($zonefile, "${default}.${zone}", $cluster);
 
 259     elsif (exists($cluster->{default}))
 
 261         output_server($zonefile, "${zone}", $cluster);
 
 265 # Header for underlying servers
 
 266 $zonefile->print("# Servers\n");
 
 268 # Output A records for each cluster
 
 269 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 271     my $name = $cluster->{name};
 
 273     output_server($zonefile, "${name}.${zone}", $cluster);
 
 275     if (@{$cluster->{servers}} > 1)
 
 277         output_server($zonefile, "${name}-%02d.${zone}", $cluster);
 
 281 # Output the GeoJSON text
 
 282 $jsonfile->print(encode_json(\@json));
 
 284 # Close the output files
 
 288 # Output gdnsd configuration
 
 289 if (defined($gdnsname))
 
 291     my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
 
 292     my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
 
 293     my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
 
 296     $gdnsmapfile->print("${gdnsname} => {\n");
 
 297     $gdnsmapfile->print("  geoip2_db => /var/lib/GeoIP/GeoLite2-Country.mmdb\n");
 
 298     $gdnsmapfile->print("  datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
 
 299     $gdnsmapfile->print("  map => {\n");
 
 300     $gdnsmapfile->print("    default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
 
 302     foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
 
 304         my $code = $origin->{code};
 
 305         my $cluster = $origin->{cluster}->{name};
 
 307         next if $code eq "XK";
 
 309         if ($continent ne $origin->{continent})
 
 311             $gdnsmapfile->print("    }\n") if $continent;
 
 313             $continent = $origin->{continent};
 
 315             $gdnsmapfile->print("    ${continent} => {\n");
 
 318         $gdnsmapfile->print("      ${code} => [${cluster}]\n");
 
 321     $gdnsmapfile->print("    }\n") if $continent;
 
 323     $gdnsmapfile->print("  }\n");
 
 324     $gdnsmapfile->print("}\n");
 
 326     $gdnsresourcefile->print("${gdnsname} => {\n");
 
 327     $gdnsresourcefile->print("  map => ${gdnsname}\n");
 
 328     $gdnsresourcefile->print("  dcmap => {\n");
 
 330     foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 332         my $name = $cluster->{name};
 
 334         if (@{$cluster->{servers}} > 1)
 
 336             $gdnsweightedfile->print("${name} => {\n");
 
 338             while (my($index,$server) = each @{$cluster->{servers}})
 
 340                 if ($server->{status} eq "up")
 
 342                     my $number = sprintf("%02d", $index + 1);
 
 343                     my $bandwidth = $server->{bandwidth};
 
 345                     $gdnsweightedfile->print("  ${name}-${number} = [ ${name}-${number}.${zone}., ${bandwidth} ]\n");
 
 349             $gdnsweightedfile->print("}\n");
 
 351             $gdnsresourcefile->print("    ${name} => %weighted!${name}\n");
 
 355             $gdnsresourcefile->print("    ${name} => ${name}.${zone}.\n");
 
 359     $gdnsresourcefile->print("  }\n");
 
 360     $gdnsresourcefile->print("}\n");
 
 362     $gdnsweightedfile->close();
 
 363     $gdnsresourcefile->close();
 
 364     $gdnsmapfile->close();
 
 367 # Output the target details in origin format if required
 
 368 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
 
 373 # Match an origin against a cluster
 
 381     if ($cluster->{preferred} &&
 
 382         $cluster->{preferred}->{origins} &&
 
 383         grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
 
 385         $match = "preferred";
 
 387     elsif ($cluster->{allowed} &&
 
 388            $cluster->{allowed}->{origins} &&
 
 389            grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
 
 393     elsif ($cluster->{preferred} &&
 
 394            $cluster->{preferred}->{countries} &&
 
 395            grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
 
 397         $match = "preferred";
 
 399     elsif ($cluster->{allowed} &&
 
 400            $cluster->{allowed}->{countries} &&
 
 401            grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
 
 405     elsif ($cluster->{denied} &&
 
 406            $cluster->{denied}->{countries} &&
 
 407            grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
 
 411     elsif ($cluster->{preferred} &&
 
 412            $cluster->{preferred}->{continents} &&
 
 413            grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
 
 415         $match = "preferred";
 
 417     elsif ($cluster->{allowed} &&
 
 418            $cluster->{allowed}->{continents} &&
 
 419            grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
 
 423     elsif ($cluster->{denied} &&
 
 424            $cluster->{denied}->{continents} &&
 
 425            grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
 
 429     elsif ($cluster->{allowed})
 
 442 # Compute the great circle distance between two points
 
 446     my $lat1 = deg2rad(shift);
 
 447     my $lon1 = deg2rad(shift);
 
 448     my $lat2 = deg2rad(shift);
 
 449     my $lon2 = deg2rad(shift);
 
 451     return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
 
 455 # Allocate each origin to a cluster
 
 457 sub allocate_clusters
 
 459     my @mappings = sort { compare_mappings($a, $b) } @_;
 
 461     # Loop over the mappings, trying to assign each origin to the
 
 462     # nearest cluster, but subject to the bandwidth limits
 
 463     while (my $mapping = shift @mappings)
 
 467         push @group, $mapping;
 
 469         while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
 
 471             push @group, shift @mappings;
 
 474         for my $mapping (sort compare_bandwidth @group)
 
 476             my $origin = $mapping->{origin};
 
 477             my $cluster = $mapping->{cluster};
 
 479             if (!exists($origin->{cluster}) &&
 
 480                 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
 
 482                 $origin->{cluster} = $cluster;
 
 483                 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
 
 492 # Compare two mappings to decide which to use
 
 499     return $b->{priority} <=> $a->{priority} ||
 
 500            $a->{distance} <=> $b->{distance};
 
 504 # Compare two mappings to decide which to try first
 
 506 sub compare_bandwidth
 
 508     my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
 
 509     my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
 
 511     return $a_used <=> $b_used;
 
 515 # Output DNS records for a server
 
 519     my $zonefile = shift;
 
 523     while (my($index,$server) = each @{$cluster->{servers}})
 
 525         if ($server->{status} eq "up")
 
 527             $zonefile->printf("+${name}:$server->{ipv4}:600\n", $index + 1);
 
 531 #                $zonefile->printf("3${name}:$server->{ipv6}:600\n", $index + 1);