#!/bin/sh

# EC2 Interfaces Script
#
# Talks to the Amazon metadata API, see
# http://docs.amazonwebservices.com/AWSEC2/2008-08-08/DeveloperGuide/AESDG-chapter-instancedata.html 
#

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    if [ -d 'zxtm/bin' ]
    then
       ZEUSHOME=`pwd`
       export ZEUSHOME
       cd $OLD_PWD
    fi
fi

if [ ! -z "$ZEUSHOME" ]
then
   PROG=$ZEUSHOME/perl/miniperl
fi

exec $PROG -x $0 ${1+"$@"}
#!perl -w
#line 32

BEGIN { unshift @INC, "$ENV{ZEUSHOME}/zxtm/lib/perl",
     "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", "$ENV{ZEUSHOME}/perl" }

use strict;
use Zeus::Execute qw( execute );
use Zeus::NetworkingUtils qw( isV4IPAddress );
use Socket;

sub _get_private_ip_to_eip_map();
sub _get_primary_mac(); 
sub _get_interface_id(;$);
sub _get_publicip_from_meta();
sub _get_public_hostname();
sub _get_all_private_ips(;$); 
sub isValidResponse( $ );
sub _get_subnet_cidr ( $ );

sub usage();

# Report an error
sub error( $$ )
{
   my( $tag, $error ) = @_;
   chomp( $tag, $error );

   # Report the error                                                                                                                                  
   print STDERR "$tag\t$error\n";
}


if( grep /^--?h(elp)?$/, @ARGV ) {
   usage();
   exit( 0 );
}

my( $ACTION, @RESTARGS ) = @ARGV;
$ACTION ||= '';

my $ZEUSHOME = $ENV{ZEUSHOME};
my $METADATA_TIMEOUT = 5;   # metadata server should respond faster than AWS as its inside EC2
my $METADATA_URL = "http://169.254.169.254/latest/meta-data";
my $PLATFORM = `uname`;

# See if theres a custom URL for the metadata URL...
if( open SETTINGS, "$ZEUSHOME/zxtm/conf/settings.cfg" ) {
   while( <SETTINGS> )
   {
       if( /^ec2!metadata_server\s+(https?:\/\/.*)/ ) {
         $METADATA_URL = $1;
       }
   }
   close SETTINGS;
}

my $META_QUERY = "$ZEUSHOME/admin/bin/httpclient -4 -t $METADATA_TIMEOUT -b $METADATA_URL";
my $AWS_TOOL = "$ZEUSHOME/zxtm/bin/awstool";

# ZXTM calls interface takeover <EIP> <PRIVIP> to 'raise' an EIP TIP
if( $ACTION eq 'takeover' ) {

   my ( $IP, $PRIVIP ) =  @RESTARGS;
   my $instance = `$META_QUERY/instance-id`;
   exit( 1 ) if( $? != 0 || !isValidResponse($instance) );

   my $iface_id = undef;
   if ( $PRIVIP && $PRIVIP ne "0.0.0.0" ) {
      # Raise the secondary IP not already raised
      # Get mac to find out about which device to use
      my $mac = _get_primary_mac();
      $iface_id = _get_interface_id( $mac );
      if ( !$mac ) {
        error("EC2_INTERFACE_ERROR", "Failed to get MAC of primary network interface using metadata server");
        exit (1);
      }
      my( $code, $out, $err ) = execute( [ 'ip', 'addr', 'list' ] );
      if ( $code ) {
         error("EC2_INTERFACE_ERROR", "Failed to check IPs on the system :: $err ");
         exit( 1 ); 
      }

      if ( $out !~ /$PRIVIP/m ) {
         my @ifaces = split(/^\w+?:\s/m, $out);
         foreach my $if ( @ifaces ) {
            if ( $if =~ /$mac/m ) {
               my ( $dev ) = $if =~ /(\w+)?:/;
               my $cidr = _get_subnet_cidr( $mac );
               my( $code, $out, $err ) = execute( [ "ip", 'addr', "add", "$PRIVIP/$cidr", "dev", $dev] );
               if ( $code && ( $err !~ /File exists/i ) ) {
                 error("EC2_INTERFACE_ERROR", "Failed to raise $PRIVIP on the system :: $err ");
                 exit( 1 );
               }
               last;          
            }
         } 
      }
   } # No Priv IP
 
   # Now associate EIP      
   if( system( "$AWS_TOOL associate-address $IP $instance $PRIVIP $iface_id > /dev/null" ) == 0 ) {
    exit( 0 );
   } else {
      exit( 1 );
   }
   
# ZXTM calls release <EIP> to 'lower' an EIP TIP (only when the
# TIP is being disabled - not necessary when doing failover)
} elsif( $ACTION eq 'release' ) {
   my ($IP, $INSTANCEID ) = @RESTARGS;
   if( !$INSTANCEID ) {
      $INSTANCEID = `$META_QUERY/instance-id`;
      exit( 1 ) if( $? != 0 || !isValidResponse( $INSTANCEID ));
      
   }
   if( system( "$AWS_TOOL disassociate-address $IP $INSTANCEID > /dev/null" ) == 0 ) {
      exit( 0 );
   } else {
      exit( 1 );
   } 

# ZXTM calls current to determine the EIP currently associated with this VM
} elsif( $ACTION eq 'current' ) {

   my $result = `$AWS_TOOL current`;
   exit( 1 ) if( $? != 0 );
   print $result;
      
# ZXTM calls instance to get its EC2 instance ID
} elsif( $ACTION eq 'instance' ) {

   my $result = `$META_QUERY/instance-id`;
   exit( 1 ) if( $? != 0 || !isValidResponse($result ));
   print $result;
      
# ZXTM calls this to query the meta-data server 
} elsif( $ACTION eq 'vpc-id' ) {
   my $mac = _get_primary_mac();

   if ( !$mac ) {
      exit(1);
   } 

   # First check the properties so that we can
   # distinguish between EC2 and VPC instance
   my $prop = `$META_QUERY/network/interfaces/macs/$mac/`;
   if( $? != 0 || !isValidResponse( $prop ) ) {
      exit(1);
   }

   #Check VPC id is one of the them
   if ( $prop =~ m/vpc-id/ ) {
      my $vpcid = `$META_QUERY/network/interfaces/macs/$mac/vpc-id/`;
      if( $? != 0 || !isValidResponse( $vpcid )  ) {
         exit(1);
      }
      print $vpcid;
   } else {
      # EC2 instance
      print "";
   }

} elsif( $ACTION eq 'metaquery' ) {
   my ( $IP ) = @RESTARGS; 
   $IP = $IP || "";
   my $result = `$META_QUERY/$IP`;
   exit( 1 ) if( $? != 0 || !isValidResponse( $result ) );
   print $result;

} elsif( $ACTION eq 'get_eip_associations' ) {
  # GetEIP asscoiation using metadata server only
  # NOTE: This function only checks using meta data server. Better to use
  #       awstool "./awstool vpc-eip-associations"
  my @privip_to_eip_map = _get_private_ip_to_eip_map( );
  exit(1) if ( !( @privip_to_eip_map ) );
  # Print 
  my $i = 0;
  foreach my $ip ( @privip_to_eip_map ) {
     my $pip = $ip->[0];
     my $eip = $ip->[1] || "0";
     my $type = ($i)?'secondary':'primary';
     print "$pip $eip $type\n";
     $i++;
  } 

} elsif( $ACTION eq 'get_publicip_from_meta' ) {
  # It gets EIP using metadata only 
  # "current" should be used form ZXTM
  my $ip = _get_publicip_from_meta();
  if ( $ip ) {
     print $ip;
  } else {
     exit(1);
  }

} elsif( $ACTION eq 'all_private_ips' ) {
   my ( $mac ) = @RESTARGS;
   # Get all private IPs on network interface
   my $ips = _get_all_private_ips( $mac );
   if( $ips ) {
      print "primary $ips->{'primary'}\n";
      if( $ips->{'secondary'} ) {
         print( "secondary ", join(",", @{$ips->{'secondary'}} ), "\n" );
      }
   } else {
     exit(1);
   }

} elsif( $ACTION eq 'public-hostname' ) {
  #Get the public hostname
  # If instance has multiple, it will return
  # what's associated with primary private IP
  # of primary ENI
  my $host = _get_public_hostname();
  if ( $host ) {
     print $host;
  } else {
     exit(1);
  }
} else {
   usage();
   exit( 1 ); 
}

exit( 0 );

##########################################
# Functions 
##########################################
sub usage() {
   print STDERR "Usage: ec2-interfaces <takeover|release|current|instance|vpc-id|get_eip_associations|get_publicip_from_meta|metaquery|all_private_ips> [args]\n";
   print <<EOF;
       current:                 Gives current public IP of the instance using metadata but 
                                but also checks the describe-addresses call to verify 
                                that the current IP isn't an EIP assigned to another machine.
       all_private_ips:         Returns all private IP addresses in following format
                                   primary <IP>
                                   secondary <IP1>,<IP2>,...
       get_publicip_from_meta:  Gives public IP only using metadata. 
                                For VPC instances, current and get_publicip_from_meta 
                                will return EIP associated (if any ) with private IP 
                                starting with primary private IP of primary network interface. 
       public-hostname:         Returns public hostname. If there are multiple hostnames associated 
                                with an instance e.g. in VPC, it will return hostname
                                which public IP as returned by get_publicip_from_meta resolves to.
       get_eip_associations:     Returns list of all private IPs of Primary network intrface of 
                                this VPC instance and their IPv4 EIP associations in following 
                                format
                                   "<PrivateIP> <EIP> primary"
                                   "<PrivateIP> 0 secondary" 
                                   "<PrivateIP> <EIP secondary" 
                                 NOTE: This function only checks using meta data server. 
                                 Better to use awstool "./awstool vpc-eip-associations"
EOF
}


# _get_private_ip_to_eip_map
# Returns a list all private IPs of a VPC instance and it's EIP association
# Value for EIP will be 0 if there is no EIP associated with private IP
# in following format
# ( [ priv_ip, EIP], [], [] )...
#  e.g
# (    ['10.0.0.10', '107.0.3.20'], ['10.0.0.11', '0'] ... )
# Array is in order same as list of private ip addresses returned by metadata server.
# So first IP is primary ip and subsequent ones are secondary IPs 
# 
sub _get_private_ip_to_eip_map() {
   my $privip_to_eip_map = {};

   my $mac = _get_primary_mac();

   if( !$mac ) {
      return;
   }

   my $ips = _get_all_private_ips( $mac );
   my @all_priv_ips = ();
   if( $ips ) {
      push( @all_priv_ips, $ips->{'primary'} );
      if( $ips->{'secondary'} ) {
         push( @all_priv_ips, @{$ips->{'secondary'}} );
      }
      
   } else { 
      return; 
   }

   #Add all IPs in the hash
   foreach my $ip ( @all_priv_ips ) {
      $privip_to_eip_map->{$ip} = 0;
   }

   my $public_ipv4s = `$META_QUERY/network/interfaces/macs/$mac/ipv4-associations/`;
   if( ( $? == 0 ) && isValidResponse( $public_ipv4s ) ) {  
      my @eips = split( '\n', $public_ipv4s );
      foreach my $eip ( @eips ) {
         my $priv_ip = `$META_QUERY/network/interfaces/macs/$mac/ipv4-associations/$eip/`;
         return if( $? != 0 || !isValidResponse( $priv_ip ) );
         $privip_to_eip_map->{$priv_ip} = $eip;
      } 
   }

   # To maintain the order of private IPs
   my @map = ();
   foreach my $ip ( @all_priv_ips ) {
     push( @map, [ $ip, $privip_to_eip_map->{$ip}] );
   }
   return @map;

}

# Returns Mac of Primary Network Interface
sub _get_primary_mac() 
{
   #Get MAC of primary network interface
   my $mac = `$META_QUERY/mac`;
   return if( $? != 0 || !isValidResponse( $mac ) );
 
   chomp( $mac );
   $mac = lc($mac);
   return $mac;
}

sub _get_interface_id( ;$ ) {
   my ( $mac ) = @_;
   if( !$mac ) {
      $mac = _get_primary_mac();
   }

   my $id = `$META_QUERY/network/interfaces/macs/$mac/interface-id`;
   if( ( $? != 0 ) || !isValidResponse( $id ) ) {
     return;
   }
   return $id;
}


# Returns a hash of primary and secondary IPs in following format
#   { 'primary' => 10.0.0.200,
#      'secondary' => [10.0.0.201, 10.0.0.202 ]
#   }
sub _get_all_private_ips(;$) {
   my ( $mac ) = @_;
   if( !$mac ) {
      $mac = _get_primary_mac();
   }
   
   my $local_ipv4s = `$META_QUERY/network/interfaces/macs/$mac/local-ipv4s`;
   if( $? != 0 || !isValidResponse( $local_ipv4s ) ) {
     return;
   }
   my @all_priv_ips = split( '\n', $local_ipv4s );

   # First address will be primary IP
   my $primary = shift( @all_priv_ips );

   my $ips = {};
   if( $primary ) {
      $ips->{'primary'} = $primary;
   } 
   $ips->{'secondary'} = [];
   foreach my $sip ( @all_priv_ips ) {
      if( isV4IPAddress( $sip ) ) {
         push( @{$ips->{'secondary'}}, $sip );
      }
   }

  return $ips;
}

 
# Get The Public IP of an instance just using metadata
# It returns IP which is
# Returns
#     - EIP IP associated with primary private IP of primary network interface
#     - EIP associated with Secondary private ip starting from first one of 
#        primary network interface
#     - Failing that, whatever meta-data/public-ipv4 returns.
# KEEP THIS IN SYNC WITH WHAT IS SAID IN Usage()
#     
sub _get_publicip_from_meta()
{
   my @priv_ip_to_eip_map = _get_private_ip_to_eip_map();
   my $eip = undef;

   if( @priv_ip_to_eip_map ) {
      for( my $index = 0; $index < @priv_ip_to_eip_map; $index++ ) {
         my $pip = $priv_ip_to_eip_map[$index]->[0];
         $eip = $priv_ip_to_eip_map[$index]->[1];
         last if $eip;
      }

   }
   
  if( !$eip ) {
     $eip = `$META_QUERY/public-ipv4`;
     if( ( $? != 0 ) || !isValidResponse( $eip ) ) {
        return;
     }
  } 
   
  return $eip;
}

sub _get_public_hostname()
{
  my $host = `$META_QUERY/public-hostname`;
  if( ( $? != 0 ) || !isValidResponse( $host ) ) {
     return;
  }

  if( !$host ) {
     return;
  }

  # Get public IP so that we can return its hostname
  my $publicip = _get_publicip_from_meta();

  my @all_hosts = split(/amazonaws\.com/, $host );
  if( ( scalar( @all_hosts ) > 1 ) && $publicip ) {
     # Set host to empty string as we either want to return something
     # useful or nothing
     $host = "";
 
     my $name = gethostbyaddr( inet_aton($publicip), AF_INET );
     if( $name ) {
        foreach my $h ( @all_hosts ) {
	        $h = $h . 'amazonaws.com';
           if( $name eq $h ) {
              return $h;
           }
         }
     }
   }

  return $host;

}

sub isValidResponse( $ ) {
   my ( $out ) = @_;
   if( ( $out =~ /<\?xml/ ) || ( $out =~ /404.*?Not found/i )) { 
      return 0;
   }
   return 1;
}

sub _get_subnet_cidr ( $ )
{
   my ( $mac ) = @_;
   # Use 24 by default
   my $cidr = 24;

   if( !$mac ) {
      $mac = _get_primary_mac();
   }

   my  $cidr_block  =`$META_QUERY/network/interfaces/macs/$mac/subnet-ipv4-cidr-block` ;
   if( ( $? != 0 ) || !isValidResponse( $cidr_block ) ) {
     return $cidr;
   }
   
   if( $cidr_block && ( $cidr_block =~ /\d+\.\d+.\d+.\d+\/(\d+)/ ) ) {
      $cidr = $1;
   }
   
   return $cidr;
}


