7 use Math::Trig qw(deg2rad pip2 great_circle_distance);
 
  12 my $originfile = shift @ARGV;
 
  13 my $clusterfile = shift @ARGV;
 
  14 my $zone = shift @ARGV;
 
  15 my $targetoriginfile = shift @ARGV;
 
  16 my $origins = YAML::LoadFile($originfile);
 
  17 my $clusters = YAML::LoadFile($clusterfile);
 
  18 my $gdnsname = shift @ARGV;
 
  21 # Initialise cluster details
 
  22 while (my($name,$cluster) = each %$clusters)
 
  24     if ($cluster->{servers})
 
  26         $cluster->{bandwidth} = 0;
 
  28         foreach my $server (@{$cluster->{servers}})
 
  30             $server->{cluster} = $cluster;
 
  31             $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
 
  33             push @servers, $server;
 
  40             statuscake => $cluster->{statuscake},
 
  41             bandwidth => $cluster->{bandwidth},
 
  42             ipv4 => $cluster->{ipv4},
 
  43             ipv6 => $cluster->{ipv6}
 
  46         $cluster->{servers} = [ $server ];
 
  48         push @servers, $server;
 
  51     $cluster->{name} = $name;
 
  52     $cluster->{status} = "down";
 
  55 # Initialise server details
 
  56 foreach my $server (@servers)
 
  58     $server->{status} = "up";
 
  61 # If statuscake support is enabled then check which servers are up
 
  62 if ($ENV{STATUSCAKE_USERNAME} && $ENV{STATUSCAKE_APIKEY})
 
  64     my $ua = LWP::UserAgent->new;
 
  67     $ua->agent("mkgeo/1.0");
 
  68     $ua->default_header("Username", $ENV{STATUSCAKE_USERNAME});
 
  69     $ua->default_header("API", $ENV{STATUSCAKE_APIKEY});
 
  71     if (-f "statuscake.yml")
 
  73         $cache = YAML::LoadFile("statuscake.yml");
 
  80     my $response = $ua->get("https://app.statuscake.com/API/Tests/");
 
  82     if ($response->is_success)
 
  84         my $tests = decode_json($response->content);
 
  86         foreach my $test (@$tests)
 
  88             my $testid = $test->{TestID};
 
  90             if ($test->{Status} eq "Up" && !$test->{Paused})
 
  92                 $cache->{$testid} = "up";
 
  96                 $cache->{$testid} = "down";
 
 101     foreach my $server (@servers)
 
 103         if (my $testids = $server->{statuscake})
 
 105             $server->{status} = "up";
 
 107             for my $testid (@$testids)
 
 109                 my $testresult = $cache->{$testid} || "down";
 
 111                 $server->{status} = "down" if $testresult eq "down";
 
 116             $server->{status} = "down";
 
 120     YAML::DumpFile("statuscake.yml", $cache);
 
 123 # Mark a cluster as up if any servers are up
 
 124 foreach my $server (@servers)
 
 126     if ($server->{status} eq "up")
 
 128         $server->{cluster}->{status} = "up";
 
 132         $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
 
 136 # Create target origins object
 
 137 my $targetorigins = {};
 
 139 # Initialise cluster details
 
 140 while (my($name,$cluster) = each %$clusters)
 
 142     $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
 
 143     $cluster->{bandwidth_used} = 0;
 
 145     $targetorigins->{$cluster->{name}} = {
 
 146         code => $cluster->{name},
 
 147         name => $cluster->{name},
 
 148         lat => $cluster->{lat},
 
 149         lon => $cluster->{lon},
 
 156 # Scan origins and work out which clusters each can use
 
 157 foreach my $origin (values %$origins)
 
 159     foreach my $cluster (values %$clusters)
 
 161         my $match = match_origin($cluster, $origin);
 
 163         if ($cluster->{status} eq "up" && $match ne "denied")
 
 165             my $priority = $match eq "preferred" ? 20 : 10;
 
 166             my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
 
 169                 origin => $origin, cluster => $cluster,
 
 170                 priority => $priority, distance => $distance
 
 176 # Allocate each country to a cluster
 
 177 allocate_clusters(@mappings);
 
 179 # If we failed to allocate every origin then loop, increasing
 
 180 # the bandwidth for each cluster by a little and retrying until
 
 181 # we manage to allocate everything
 
 182 while (grep { !exists($_->{cluster}) } values %$origins)
 
 184     # Clear any existing mappings of countries to clusters
 
 185     foreach my $origin (values %$origins)
 
 187         delete $origin->{cluster};
 
 190     # Reset bandwidth usage for clusters and increase limits by 10%
 
 191     foreach my $cluster (values %$clusters)
 
 193         $cluster->{bandwidth_used} = 0;
 
 194         $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
 
 197     # Try the allocate again
 
 198     allocate_clusters(@mappings);
 
 201 # Create JSON collection object
 
 205 my $zonefile = IO::File->new("> data/${zone}") || die "$!";
 
 206 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
 
 208 # Output details for each country
 
 209 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
 
 211     my $cluster = $origin->{cluster};
 
 212     my $clon = $origin->{lon};
 
 213     my $clat = $origin->{lat};
 
 214     my $slon = $cluster->{lon};
 
 215     my $slat = $cluster->{lat};
 
 217     if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
 
 221     elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
 
 226     $zonefile->print("# $origin->{name}\n");
 
 227     $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
 
 232             type => "LineString",
 
 233             coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
 
 236             origin => $origin->{name},
 
 237             server => $cluster->{name},
 
 238             colour => $cluster->{colour}
 
 242     $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
 
 245 # Header for default records
 
 246 $zonefile->print("# Unknown origins\n");
 
 248 # Output default records for IPs that can't be mapped to a country
 
 249 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 251     my $name = $cluster->{name};
 
 253     if (my $default = $cluster->{default})
 
 255         output_server($zonefile, "${default}.${zone}", $cluster);
 
 257     elsif (exists($cluster->{default}))
 
 259         output_server($zonefile, "${zone}", $cluster);
 
 263 # Header for underlying servers
 
 264 $zonefile->print("# Servers\n");
 
 266 # Output A records for each cluster
 
 267 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 269     my $name = $cluster->{name};
 
 271     output_server($zonefile, "${name}.${zone}", $cluster);
 
 274 # Output the GeoJSON text
 
 275 $jsonfile->print(encode_json(\@json));
 
 277 # Close the output files
 
 281 # Output gdnsd configuration
 
 282 if (defined($gdnsname))
 
 284     my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
 
 285     my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
 
 288     $gdnsmapfile->print("${gdnsname} => {\n");
 
 289     $gdnsmapfile->print("  geoip2_db => /var/lib/GeoIP/GeoLite2-Country.mmdb\n");
 
 290     $gdnsmapfile->print("  datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
 
 291     $gdnsmapfile->print("  map => {\n");
 
 292     $gdnsmapfile->print("    default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
 
 294     foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
 
 296         my $code = $origin->{code};
 
 297         my $cluster = $origin->{cluster}->{name};
 
 299         next if $code eq "XK";
 
 301         if ($continent ne $origin->{continent})
 
 303             $gdnsmapfile->print("    }\n") if $continent;
 
 305             $continent = $origin->{continent};
 
 307             $gdnsmapfile->print("    ${continent} => {\n");
 
 310         $gdnsmapfile->print("      ${code} => [${cluster}]\n");
 
 313     $gdnsmapfile->print("    }\n") if $continent;
 
 315     $gdnsmapfile->print("  }\n");
 
 316     $gdnsmapfile->print("}\n");
 
 318     $gdnsresourcefile->print("${gdnsname} => {\n");
 
 319     $gdnsresourcefile->print("  map => ${gdnsname}\n");
 
 320     $gdnsresourcefile->print("  dcmap => {\n");
 
 322     foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 324         my $name = $cluster->{name};
 
 326         $gdnsresourcefile->print("    ${name} => ${name}.tile.openstreetmap.org.\n");
 
 329     $gdnsresourcefile->print("  }\n");
 
 330     $gdnsresourcefile->print("}\n");
 
 332     $gdnsresourcefile->close();
 
 333     $gdnsmapfile->close();
 
 336 # Output the target details in origin format if required
 
 337 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
 
 342 # Match an origin against a cluster
 
 350     if ($cluster->{preferred} &&
 
 351         $cluster->{preferred}->{origins} &&
 
 352         grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
 
 354         $match = "preferred";
 
 356     elsif ($cluster->{allowed} &&
 
 357            $cluster->{allowed}->{origins} &&
 
 358            grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
 
 362     elsif ($cluster->{preferred} &&
 
 363            $cluster->{preferred}->{countries} &&
 
 364            grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
 
 366         $match = "preferred";
 
 368     elsif ($cluster->{allowed} &&
 
 369            $cluster->{allowed}->{countries} &&
 
 370            grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
 
 374     elsif ($cluster->{denied} &&
 
 375            $cluster->{denied}->{countries} &&
 
 376            grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
 
 380     elsif ($cluster->{preferred} &&
 
 381            $cluster->{preferred}->{continents} &&
 
 382            grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
 
 384         $match = "preferred";
 
 386     elsif ($cluster->{allowed} &&
 
 387            $cluster->{allowed}->{continents} &&
 
 388            grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
 
 392     elsif ($cluster->{denied} &&
 
 393            $cluster->{denied}->{continents} &&
 
 394            grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
 
 398     elsif ($cluster->{allowed})
 
 411 # Compute the great circle distance between two points
 
 415     my $lat1 = deg2rad(shift);
 
 416     my $lon1 = deg2rad(shift);
 
 417     my $lat2 = deg2rad(shift);
 
 418     my $lon2 = deg2rad(shift);
 
 420     return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
 
 424 # Allocate each origin to a cluster
 
 426 sub allocate_clusters
 
 428     my @mappings = sort { compare_mappings($a, $b) } @_;
 
 430     # Loop over the mappings, trying to assign each origin to the
 
 431     # nearest cluster, but subject to the bandwidth limits
 
 432     while (my $mapping = shift @mappings)
 
 436         push @group, $mapping;
 
 438         while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
 
 440             push @group, shift @mappings;
 
 443         for my $mapping (sort compare_bandwidth @group)
 
 445             my $origin = $mapping->{origin};
 
 446             my $cluster = $mapping->{cluster};
 
 448             if (!exists($origin->{cluster}) &&
 
 449                 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
 
 451                 $origin->{cluster} = $cluster;
 
 452                 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
 
 461 # Compare two mappings to decide which to use
 
 468     return $b->{priority} <=> $a->{priority} ||
 
 469            $a->{distance} <=> $b->{distance};
 
 473 # Compare two mappings to decide which to try first
 
 475 sub compare_bandwidth
 
 477     my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
 
 478     my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
 
 480     return $a_used <=> $b_used;
 
 484 # Output DNS records for a server
 
 488     my $zonefile = shift;
 
 492     foreach my $server (@{$cluster->{servers}})
 
 494         if ($server->{status} eq "up")
 
 496             $zonefile->print("+${name}:$server->{ipv4}:600\n");
 
 500 #                $zonefile->print("3${name}:$server->{ipv6}:600\n");