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     next if $cluster->{global};
 
 268     $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
 
 271 # Skip default records if we don't need them
 
 272 if (!defined($gdnsname))
 
 274     # Output default records for IPs that can't be mapped to a country
 
 275     foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 277         my $name = $cluster->{name};
 
 279         if (my $default = $cluster->{default})
 
 281             output_server($zonefile, "${default}.${zone}", $cluster, 0);
 
 283         elsif (exists($cluster->{default}))
 
 285             output_server($zonefile, "${zone}", $cluster, 0);
 
 290 # Output A records for each cluster
 
 291 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 293     my $name = $cluster->{name};
 
 295     if (@{$cluster->{servers}} > 1)
 
 297         output_server($zonefile, "${name}-%02d.${zone}", $cluster, 1);
 
 301         output_server($zonefile, "${name}.${zone}", $cluster, 1);
 
 305 # Output the GeoJSON text
 
 306 $jsonfile->print(encode_json(\@json));
 
 309 $zonefile->print("];\n");
 
 311 # Close the output files
 
 315 # Output gdnsd configuration
 
 316 if (defined($gdnsname))
 
 318     my $gdnsmapfile = IO::File->new("> gdns/${gdnsname}.map") || die "$!";
 
 319     my $gdnsresourcefile = IO::File->new("> gdns/${gdnsname}.resource") || die "$!";
 
 320     my $gdnsweightedfile = IO::File->new("> gdns/${gdnsname}.weighted") || die "$!";
 
 323     $gdnsmapfile->print("${gdnsname} => {\n");
 
 324     $gdnsmapfile->print("  geoip2_db => /usr/share/GeoIP/GeoLite2-Country.mmdb\n");
 
 325     $gdnsmapfile->print("  datacenters => [" . join(",", sort(keys(%$clusters))) . "]\n");
 
 326     $gdnsmapfile->print("  map => {\n");
 
 327     $gdnsmapfile->print("    default => [" . join(",", sort(map { $_->{name} } grep { $_->{default} } values(%$clusters))) . "]\n");
 
 329     foreach my $origin (sort { $a->{continent} cmp $b->{continent} || $a->{code} cmp $b->{code} } values %$origins)
 
 331         my $code = $origin->{code};
 
 332         my $cluster = $origin->{cluster}->{name};
 
 334         next if $code eq "XK";
 
 336         if ($continent ne $origin->{continent})
 
 338             $gdnsmapfile->print("    }\n") if $continent;
 
 340             $continent = $origin->{continent};
 
 342             $gdnsmapfile->print("    ${continent} => {\n");
 
 345         $gdnsmapfile->print("      ${code} => [${cluster}]\n");
 
 348     $gdnsmapfile->print("    }\n") if $continent;
 
 350     $gdnsmapfile->print("  }\n");
 
 351     $gdnsmapfile->print("}\n");
 
 353     $gdnsresourcefile->print("${gdnsname} => {\n");
 
 354     $gdnsresourcefile->print("  map => ${gdnsname}\n");
 
 355     $gdnsresourcefile->print("  dcmap => {\n");
 
 357     foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 359         my $name = $cluster->{name};
 
 361         if (@{$cluster->{servers}} > 1 && grep { $_->{status} eq "up" } @{$cluster->{servers}})
 
 363             $gdnsweightedfile->print("${name} => {\n");
 
 365             while (my($index,$server) = each @{$cluster->{servers}})
 
 367                 if ($server->{status} eq "up")
 
 369                     my $number = sprintf("%02d", $index + 1);
 
 370                     my $bandwidth = $server->{bandwidth};
 
 372                     if (my $cname = $server->{cname})
 
 374                         $gdnsweightedfile->print("  ${name}-${number} = [ ${cname}., ${bandwidth} ]\n");
 
 378                         $gdnsweightedfile->print("  ${name}-${number} = [ ${name}-${number}.${zone}.openstreetmap.org., ${bandwidth} ]\n");
 
 383             $gdnsweightedfile->print("}\n");
 
 385             $gdnsresourcefile->print("    ${name} => %weighted!${name}\n");
 
 387         elsif (my $cname = $cluster->{cname})
 
 389             $gdnsresourcefile->print("    ${name} => ${cname}.\n");
 
 393             $gdnsresourcefile->print("    ${name} => ${name}.${zone}.openstreetmap.org.\n");
 
 397     $gdnsresourcefile->print("  }\n");
 
 398     $gdnsresourcefile->print("}\n");
 
 400     $gdnsweightedfile->close();
 
 401     $gdnsresourcefile->close();
 
 402     $gdnsmapfile->close();
 
 405 # Output the target details in origin format if required
 
 406 DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
 
 411 # Match an origin against a cluster
 
 419     if ($cluster->{preferred} &&
 
 420         $cluster->{preferred}->{origins} &&
 
 421         grep { $_ eq $origin->{name} } @{$cluster->{preferred}->{origins}})
 
 423         $match = "preferred";
 
 425     elsif ($cluster->{allowed} &&
 
 426            $cluster->{allowed}->{origins} &&
 
 427            grep { $_ eq $origin->{name} } @{$cluster->{allowed}->{origins}})
 
 431     elsif ($cluster->{preferred} &&
 
 432            $cluster->{preferred}->{countries} &&
 
 433            grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
 
 435         $match = "preferred";
 
 437     elsif ($cluster->{allowed} &&
 
 438            $cluster->{allowed}->{countries} &&
 
 439            grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
 
 443     elsif ($cluster->{denied} &&
 
 444            $cluster->{denied}->{countries} &&
 
 445            grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
 
 449     elsif ($cluster->{preferred} &&
 
 450            $cluster->{preferred}->{continents} &&
 
 451            grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
 
 453         $match = "preferred";
 
 455     elsif ($cluster->{allowed} &&
 
 456            $cluster->{allowed}->{continents} &&
 
 457            grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
 
 461     elsif ($cluster->{denied} &&
 
 462            $cluster->{denied}->{continents} &&
 
 463            grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
 
 467     elsif ($cluster->{allowed})
 
 480 # Compute the great circle distance between two points
 
 484     my $lat1 = deg2rad(shift);
 
 485     my $lon1 = deg2rad(shift);
 
 486     my $lat2 = deg2rad(shift);
 
 487     my $lon2 = deg2rad(shift);
 
 489     return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
 
 493 # Allocate each origin to a cluster
 
 495 sub allocate_clusters
 
 497     my @mappings = sort { compare_mappings($a, $b) } @_;
 
 499     # Loop over the mappings, trying to assign each origin to the
 
 500     # nearest cluster, but subject to the bandwidth limits
 
 501     while (my $mapping = shift @mappings)
 
 505         push @group, $mapping;
 
 507         while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
 
 509             push @group, shift @mappings;
 
 512         for my $mapping (sort compare_bandwidth @group)
 
 514             my $origin = $mapping->{origin};
 
 515             my $cluster = $mapping->{cluster};
 
 517             if (!exists($origin->{cluster}) &&
 
 518                 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
 
 520                 $origin->{cluster} = $cluster;
 
 521                 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
 
 530 # Compare two mappings to decide which to use
 
 537     return $b->{priority} <=> $a->{priority} ||
 
 538            $a->{distance} <=> $b->{distance};
 
 542 # Compare two mappings to decide which to try first
 
 544 sub compare_bandwidth
 
 546     my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
 
 547     my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
 
 549     return $a_used <=> $b_used;
 
 553 # Output DNS records for a server
 
 557     my $zonefile = shift;
 
 562     while (my($index,$server) = each @{$cluster->{servers}})
 
 564         if ($all || $server->{status} eq "up")
 
 568                 $zonefile->printf("  A(\"${name}\", \"$server->{ipv4}\", TTL(\"10m\")),\n", $index + 1);
 
 573                 $zonefile->printf("  AAAA(\"${name}\", \"$server->{ipv6}\", TTL(\"10m\")),\n", $index + 1);