#!/usr/bin/perl use strict; use warnings; use IO::File; use Math::Trig qw(deg2rad pip2 great_circle_distance); use JSON::XS; use LWP::UserAgent; use YAML; my $originfile = shift @ARGV; my $clusterfile = shift @ARGV; my $zone = shift @ARGV; my $targetoriginfile = shift @ARGV; my $origins = YAML::LoadFile($originfile); my $clusters = YAML::LoadFile($clusterfile); my @servers; # Initialise cluster details while (my($name,$cluster) = each %$clusters) { if ($cluster->{servers}) { $cluster->{bandwidth} = 0; foreach my $server (@{$cluster->{servers}}) { $server->{cluster} = $cluster; $cluster->{bandwidth} = $cluster->{bandwidth} + $server->{bandwidth}; push @servers, $server; } } else { my $server = { cluster => $cluster, pingdom => $cluster->{pingdom}, bandwidth => $cluster->{bandwidth}, ipv4 => $cluster->{ipv4}, ipv6 => $cluster->{ipv6} }; $cluster->{servers} = [ $server ]; push @servers, $server; } $cluster->{name} = $name; $cluster->{status} = "down"; } # Initialise server details foreach my $server (@servers) { $server->{status} = "up"; } # If pingdom support is enabled then check which servers are up if ($ENV{PINGDOM_USERNAME} && $ENV{PINGDOM_PASSWORD}) { my $ua = LWP::UserAgent->new; my $cache; $ua->timeout(5); $ua->default_header("App-Key", "2cohi62u5haxvqmypk3ljqqrze1jufrh"); $ua->credentials("api.pingdom.com:443", "Pingdom API", $ENV{PINGDOM_USERNAME}, $ENV{PINGDOM_PASSWORD}); if (-f "pingdom.yml") { $cache = YAML::LoadFile("pingdom.yml"); } else { $cache = {}; } foreach my $server (@servers) { if (my $checkid = $server->{pingdom}) { my $response = $ua->get("https://api.pingdom.com/api/2.0/checks/${checkid}"); if ($response->is_success) { my $check = decode_json($response->content); $server->{status} = $check->{check}->{status}; $cache->{$server->{pingdom}} = $check->{check}->{status}; } else { $server->{status} = $cache->{$server->{pingdom}} || "down"; } } else { $server->{status} = "down"; } } YAML::DumpFile("pingdom.yml", $cache); } # Mark a cluster as up if any servers are up foreach my $server (@servers) { if ($server->{status} eq "up") { $server->{cluster}->{status} = "up"; } else { $server->{cluster}->{bandwidth} = $server->{cluster}->{bandwidth} - $server->{bandwidth}; } } # Create target origins object my $targetorigins = {}; # Initialise cluster details while (my($name,$cluster) = each %$clusters) { $cluster->{bandwidth_limit} = $cluster->{bandwidth} * 1024 * 1024; $cluster->{bandwidth_used} = 0; $targetorigins->{$cluster->{name}} = { code => $cluster->{name}, name => $cluster->{name}, lat => $cluster->{lat}, lon => $cluster->{lon}, bandwidth => 0 }; } my @mappings = (); # Scan origins and work out which clusters each can use foreach my $origin (values %$origins) { foreach my $cluster (values %$clusters) { my $match = match_origin($cluster, $origin); if ($cluster->{status} eq "up" && $match ne "denied") { my $priority = $match eq "preferred" ? 20 : 10; my $distance = distance($origin->{lat}, $origin->{lon}, $cluster->{lat}, $cluster->{lon}); push @mappings, { origin => $origin, cluster => $cluster, priority => $priority, distance => $distance }; } } } # Allocate each country to a cluster allocate_clusters(@mappings); # If we failed to allocate every origin then loop, increasing # the bandwidth for each cluster by a little and retrying until # we manage to allocate everything while (grep { !exists($_->{cluster}) } values %$origins) { # Clear any existing mappings of countries to clusters foreach my $origin (values %$origins) { delete $origin->{cluster}; } # Reset bandwidth usage for clusters and increase limits by 10% foreach my $cluster (values %$clusters) { $cluster->{bandwidth_used} = 0; $cluster->{bandwidth_limit} = $cluster->{bandwidth_limit} * 1.1; } # Try the allocate again allocate_clusters(@mappings); } # Create JSON collection object my @json; # Open output files my $zonefile = IO::File->new("> data/${zone}") || die "$!"; my $jsonfile = IO::File->new("> json/${zone}.json") || die "$!"; # Output details for each country foreach my $origin (values %$origins) { my $cluster = $origin->{cluster}; my $clon = $origin->{lon}; my $clat = $origin->{lat}; my $slon = $cluster->{lon}; my $slat = $cluster->{lat}; if ($clon > 0 && $slon < 0 && 360 + $slon - $clon < $clon - $slon) { $slon = $slon + 360; } elsif ($slon > 0 && $clon < 0 && 360 + $clon - $slon < $slon - $clon) { $clon = $clon + 360; } $zonefile->print("# $origin->{name}\n"); $zonefile->print("C\L$origin->{code}\E.${zone}:$cluster->{name}.${zone}:600\n"); push @json, { type => "Feature", geometry => { type => "LineString", coordinates => [ [ $clon, $clat ], [ $slon, $slat ] ] }, properties => { origin => $origin->{name}, server => $cluster->{name}, colour => $cluster->{colour} } }; $targetorigins->{$cluster->{name}}->{bandwidth} += $origin->{bandwidth}; } # Header for default records $zonefile->print("# Unknown origins\n"); # Output default records for IPs that can't be mapped to a country while (my($name,$cluster) = each %$clusters) { if (my $default = $cluster->{default}) { output_server($zonefile, "${default}.${zone}", $cluster); } elsif (exists($cluster->{default})) { output_server($zonefile, "${zone}", $cluster); } } # Header for underlying servers $zonefile->print("# Servers\n"); # Output A records for each cluster while (my($name,$cluster) = each %$clusters) { output_server($zonefile, "${name}.${zone}", $cluster); } # Output the GeoJSON text $jsonfile->print(encode_json(\@json)); # Close the output files $jsonfile->close(); $zonefile->close(); # Output the target details in origin format if required YAML::DumpFile($targetoriginfile, $targetorigins) if $targetoriginfile; exit 0; # # Match an origin against a cluster # sub match_origin { my $cluster = shift; my $origin = shift; my $match; if ($cluster->{preferred} && $cluster->{preferred}->{countries} && grep { $_ eq $origin->{country} } @{$cluster->{preferred}->{countries}}) { $match = "preferred"; } elsif ($cluster->{allowed} && $cluster->{allowed}->{countries} && grep { $_ eq $origin->{country} } @{$cluster->{allowed}->{countries}}) { $match = "allowed"; } elsif ($cluster->{denied} && $cluster->{denied}->{countries} && grep { $_ eq $origin->{country} } @{$cluster->{denied}->{countries}}) { $match = "denied"; } elsif ($cluster->{preferred} && $cluster->{preferred}->{continents} && grep { $_ eq $origin->{continent} } @{$cluster->{preferred}->{continents}}) { $match = "preferred"; } elsif ($cluster->{allowed} && $cluster->{allowed}->{continents} && grep { $_ eq $origin->{continent} } @{$cluster->{allowed}->{continents}}) { $match = "allowed"; } elsif ($cluster->{denied} && $cluster->{denied}->{continents} && grep { $_ eq $origin->{continent} } @{$cluster->{denied}->{continents}}) { $match = "denied"; } elsif ($cluster->{allowed}) { $match = "denied"; } else { $match = "allowed"; } return $match; } # # Compute the great circle distance between two points # sub distance { my $lat1 = deg2rad(shift); my $lon1 = deg2rad(shift); my $lat2 = deg2rad(shift); my $lon2 = deg2rad(shift); return great_circle_distance($lon1, pip2 - $lat1, $lon2, pip2 - $lat2); } # # Allocate each origin to a cluster # sub allocate_clusters { my @mappings = sort { compare_mappings($a, $b) } @_; # Loop over the mappings, trying to assign each origin to the # nearest cluster, but subject to the bandwidth limits while (my $mapping = shift @mappings) { my @group; push @group, $mapping; while (@mappings && compare_mappings($mapping, $mappings[0]) == 0) { push @group, shift @mappings; } for my $mapping (sort compare_bandwidth @group) { my $origin = $mapping->{origin}; my $cluster = $mapping->{cluster}; if (!exists($origin->{cluster}) && $cluster->{bandwidth_used} + $origin->{bandwidth} <= $cluster->{bandwidth_limit}) { $origin->{cluster} = $cluster; $cluster->{bandwidth_used} = $cluster->{bandwidth_used} + $origin->{bandwidth}; } } } return; } # # Compare two mappings to decide which to use # sub compare_mappings { my $a = shift; my $b = shift; return $b->{priority} <=> $a->{priority} || $a->{distance} <=> $b->{distance}; } # # Compare two mappings to decide which to try first # sub compare_bandwidth { my $a_used = ( $a->{cluster}->{bandwidth_used} * 100.0 ) / ( $a->{cluster}->{bandwidth_limit} * 1.0 ); my $b_used = ( $b->{cluster}->{bandwidth_used} * 100.0 ) / ( $b->{cluster}->{bandwidth_limit} * 1.0 ); return $a_used <=> $b_used; } # # Output DNS records for a server # sub output_server { my $zonefile = shift; my $name = shift; my $cluster = shift; foreach my $server (@{$cluster->{servers}}) { if ($server->{status} eq "up") { $zonefile->print("+${name}:$server->{ipv4}:600\n"); if ($server->{ipv6}) { # $zonefile->print("3${name}:$server->{ipv6}:600\n"); } } } return; }