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);
 
  20 # Initialise cluster details
 
  21 while (my($name,$cluster) = each %$clusters)
 
  23     if ($cluster->{servers})
 
  25         $cluster->{bandwidth} = 0;
 
  27         foreach my $server (@{$cluster->{servers}})
 
  29             $server->{cluster} = $cluster;
 
  30             $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth};
 
  32             push @servers, $server;
 
  39             pingdom => $cluster->{pingdom},
 
  40             bandwidth => $cluster->{bandwidth},
 
  41             ipv4 => $cluster->{ipv4},
 
  42             ipv6 => $cluster->{ipv6}
 
  45         $cluster->{servers} = [ $server ];
 
  47         push @servers, $server;
 
  50     $cluster->{name} = $name;
 
  51     $cluster->{status} = "down";
 
  54 # Initialise server details
 
  55 foreach my $server (@servers)
 
  57     $server->{status} = "up";
 
  60 # If pingdom support is enabled then check which servers are up
 
  61 if ($ENV{PINGDOM_USERNAME} && $ENV{PINGDOM_PASSWORD})
 
  63     my $ua = LWP::UserAgent->new;
 
  67     $ua->default_header("App-Key", "2cohi62u5haxvqmypk3ljqqrze1jufrh");
 
  68     $ua->credentials("api.pingdom.com:443", "Pingdom API", $ENV{PINGDOM_USERNAME}, $ENV{PINGDOM_PASSWORD});
 
  72         $cache = YAML::LoadFile("pingdom.yml");
 
  79     foreach my $server (@servers)
 
  81         if (my $checkid = $server->{pingdom})
 
  83             my $response = $ua->get("https://api.pingdom.com/api/2.0/checks/${checkid}");
 
  85             if ($response->is_success)
 
  87                 my $check = decode_json($response->content);
 
  89                 $server->{status} = $check->{check}->{status};
 
  90                 $cache->{$server->{pingdom}} = $check->{check}->{status};
 
  94                 $server->{status} = $cache->{$server->{pingdom}} || "down";
 
  99             $server->{status} = "down";
 
 103     YAML::DumpFile("pingdom.yml", $cache);
 
 106 # Mark a cluster as up if any servers are up
 
 107 foreach my $server (@servers)
 
 109     if ($server->{status} eq "up")
 
 111         $server->{cluster}->{status} = "up";
 
 115         $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth};
 
 119 # Create target origins object
 
 120 my $targetorigins = {};
 
 122 # Initialise cluster details
 
 123 while (my($name,$cluster) = each %$clusters)
 
 125     $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024;
 
 126     $cluster->{bandwidth_used} = 0;
 
 128     $targetorigins->{$cluster->{name}} = {
 
 129         code => $cluster->{name},
 
 130         name => $cluster->{name},
 
 131         lat => $cluster->{lat},
 
 132         lon => $cluster->{lon},
 
 139 # Scan origins and work out which clusters each can use
 
 140 foreach my $origin (values %$origins)
 
 142     foreach my $cluster (values %$clusters)
 
 144         my $match = match_origin($cluster, $origin);
 
 146         if ($cluster->{status} eq "up" && $match ne "denied")
 
 148             my $priority = $match eq "preferred" ? 20 : 10;
 
 149             my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon});
 
 152                 origin => $origin, cluster => $cluster,
 
 153                 priority => $priority, distance => $distance
 
 159 # Allocate each country to a cluster
 
 160 allocate_clusters(@mappings);
 
 162 # If we failed to allocate every origin then loop, increasing
 
 163 # the bandwidth for each cluster by a little and retrying until
 
 164 # we manage to allocate everything
 
 165 while (grep { !exists($_->{cluster}) } values %$origins)
 
 167     # Clear any existing mappings of countries to clusters
 
 168     foreach my $origin (values %$origins)
 
 170         delete $origin->{cluster};
 
 173     # Reset bandwidth usage for clusters and increase limits by 10%
 
 174     foreach my $cluster (values %$clusters)
 
 176         $cluster->{bandwidth_used} = 0;
 
 177         $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1;
 
 180     # Try the allocate again
 
 181     allocate_clusters(@mappings);
 
 184 # Create JSON collection object
 
 188 my $zonefile = IO::File->new("> data/${zone}") || die "$!";
 
 189 my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!";
 
 191 # Output details for each country
 
 192 foreach my $origin (sort { $a->{name} cmp $b->{name} } values %$origins)
 
 194     my $cluster = $origin->{cluster};
 
 195     my $clon = $origin->{lon};
 
 196     my $clat = $origin->{lat};
 
 197     my $slon = $cluster->{lon};
 
 198     my $slat = $cluster->{lat};
 
 200     if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon)
 
 204     elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon)
 
 209     $zonefile->print("# $origin->{name}\n");
 
 210     $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n");
 
 215             type => "LineString",
 
 216             coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ]
 
 219             origin => $origin->{name},
 
 220             server => $cluster->{name},
 
 221             colour => $cluster->{colour}
 
 225     $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth};
 
 228 # Header for default records
 
 229 $zonefile->print("# Unknown origins\n");
 
 231 # Output default records for IPs that can't be mapped to a country
 
 232 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 234     my $name = $cluster->{name};
 
 236     if (my $default = $cluster->{default})
 
 238         output_server($zonefile, "${default}.${zone}", $cluster);
 
 240     elsif (exists($cluster->{default}))
 
 242         output_server($zonefile, "${zone}", $cluster);
 
 246 # Header for underlying servers
 
 247 $zonefile->print("# Servers\n");
 
 249 # Output A records for each cluster
 
 250 foreach my $cluster (sort { $a->{name} cmp $b->{name} } values %$clusters)
 
 252     my $name = $cluster->{name};
 
 254     output_server($zonefile, "${name}.${zone}", $cluster);
 
 257 # Output the GeoJSON text
 
 258 $jsonfile->print(encode_json(\@json));
 
 260 # Close the output files
 
 264 # Output the target details in origin format if required
 
 265 YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile;
 
 270 # Match an origin against a cluster
 
 278     if ($cluster->{preferred} &&
 
 279         $cluster->{preferred}->{countries} &&
 
 280         grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}})
 
 282         $match = "preferred";
 
 284     elsif ($cluster->{allowed} &&
 
 285            $cluster->{allowed}->{countries} &&
 
 286            grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}})
 
 290     elsif ($cluster->{denied} &&
 
 291            $cluster->{denied}->{countries} &&
 
 292            grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}})
 
 296     elsif ($cluster->{preferred} &&
 
 297            $cluster->{preferred}->{continents} &&
 
 298            grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}})
 
 300         $match = "preferred";
 
 302     elsif ($cluster->{allowed} &&
 
 303            $cluster->{allowed}->{continents} &&
 
 304            grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}})
 
 308     elsif ($cluster->{denied} &&
 
 309            $cluster->{denied}->{continents} &&
 
 310            grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}})
 
 314     elsif ($cluster->{allowed})
 
 327 # Compute the great circle distance between two points
 
 331     my $lat1 = deg2rad(shift);
 
 332     my $lon1 = deg2rad(shift);
 
 333     my $lat2 = deg2rad(shift);
 
 334     my $lon2 = deg2rad(shift);
 
 336     return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2);
 
 340 # Allocate each origin to a cluster
 
 342 sub allocate_clusters
 
 344     my @mappings = sort { compare_mappings($a, $b) } @_;
 
 346     # Loop over the mappings, trying to assign each origin to the
 
 347     # nearest cluster, but subject to the bandwidth limits
 
 348     while (my $mapping = shift @mappings)
 
 352         push @group, $mapping;
 
 354         while (@mappings && compare_mappings($mapping, $mappings[0]) == 0)
 
 356             push @group, shift @mappings;
 
 359         for my $mapping (sort compare_bandwidth @group)
 
 361             my $origin = $mapping->{origin};
 
 362             my $cluster = $mapping->{cluster};
 
 364             if (!exists($origin->{cluster}) &&
 
 365                 $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit})
 
 367                 $origin->{cluster} = $cluster;
 
 368                 $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth};
 
 377 # Compare two mappings to decide which to use
 
 384     return $b->{priority} <=> $a->{priority} ||
 
 385            $a->{distance} <=> $b->{distance};
 
 389 # Compare two mappings to decide which to try first
 
 391 sub compare_bandwidth
 
 393     my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 );
 
 394     my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 );
 
 396     return $a_used <=> $b_used;
 
 400 # Output DNS records for a server
 
 404     my $zonefile = shift;
 
 408     foreach my $server (@{$cluster->{servers}})
 
 410         if ($server->{status} eq "up")
 
 412             $zonefile->print("+${name}:$server->{ipv4}:600\n");
 
 416 #                $zonefile->print("3${name}:$server->{ipv6}:600\n");