#!/bin/sh

#   -*- mode:perl -*-
# vim:set syn=perl:
# VMWare vSphere Client
#
# Talks to the vSphere vCenter Server SOAP API, see references at:
# http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/index.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 34

=head1 NAME

vsphere-client - Autoscaler script for vCenter Web Services API.

=head1 SYNOPSIS

B<vsphere-client>

=head1 DESCRIPTION

B<vsphere-client> is used by the Zeus Traffic Manager Autoscaler process
to scale virtual machines on VMWare ESX hosts through vCenter server.

=head1 COPYRIGHT

Copyright (C) 2000-2013 Zeus Technology Limited. All rights reserved.

=cut


#-----------------------------------------------------------------------------#
# Start of perl code - Check environment
#-----------------------------------------------------------------------------#

BEGIN {
   if( defined $ENV{ZEUSHOME} ) {
      unshift( @INC, "$ENV{ZEUSHOME}/zxtmadmin/lib/perl/vSphere",
               "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
               "$ENV{ZEUSHOME}/admin/lib/perl",
               "$ENV{ZEUSHOME}/zxtm/lib/perl",
               "$ENV{ZEUSHOME}/perl" );
   }
}

use Zeus::ZXTM::VSphereClient;
use Zeus::KeyValueConfigFile;
use Zeus::ZXTM::ZJSON qw( parseJSON formatJSON );

my $verbose = 0;

# print usage information:
sub usage($);

# convert cmd-line arguments to args used by our functions
# returns: 0 on success, 1 on failure
sub check_usage();

my @node_status_fmt = ( "sizeid", "status", "name", "public_ip", "created",
                        "uniq_id", "private_ip", "imageid", "complete" );

# these functions all take a hashref as argument and return 0/1 to indicate success/failure:
my $funs = {
            status => \&get_status,
            createnode => \&create_node,
            destroynode => \&destroy_node,
            search => \&search,
           };


# The hash containing the arguments to the scripts.
# Action can be either createnode, status or destroynode, see help()
# for the arguments.
my $args = { action => undef, arguments => {}, result => "", status => 137 };

usage( STDERR ) if check_usage(); 

my $client = Zeus::ZXTM::VSphereClient->new({ timeout => 60, keepalive => 60 }); 

$verbose = $args->{arguments}->{verbose};
$client->verbose() if( $verbose );

# Call the handler.
$funs->{$args->{action}}->();


# Remove warning while printing UTF8 wide characters.
binmode STDOUT, ":utf8";

# Print the result.
print STDOUT $args->{result} if defined( $args->{result} );

exit $args->{status};

# internal methods follow
sub usage($)
{
   my $fd = shift;

   if( !defined( $fd ) ) {
      $fd = 1;
   }

   print $fd "Usage: $0 [--help] action options\n",
       "\n",
       "action: [status|createnode|destroynode]\n",
       "common options:  --verbose=1 --cloudcreds=name \n",
       "Other valid options depend on the chosen action:\n",
       "  status:        --datacenter=dc	Only reports status of VMs in the specified datacenter dc(Optional)\n",
       "                 --prefix=vmPrefix      Only reports status of VMs starting with the specified prefix(Optional)\n\n",
       "  createnode:    --name=newname 	Associate name newname (must be unique) with the new instance\n",
       "                 --imageid=path 	Path of the VMWare template image from which to create a new instance\n",
       "                 --cluster=host/cluster Name of the ESX cluster/host on which to create the new instance.\n",
       "                 --datacenter=dc  	Create an instance in a specific datacenter\n",
       "                 --datastore=ds 	Specify the datastore on which to create the new instance(Optional)\n\n",
       "  destroynode:   --datacenter=dc 	The datacenter on which the VM is running\n",
       "                 --id=uuid 	        The instance uuid of the VM to destroy\n",
       "                 or\n",                    
       "                 --vm_path=fullPath     full path of the instance to destroy\n\n",
       "  search:        --object=objectPath    full path of the object to find in VCenter inventory\n";
   exit 0;
}

# Validates the presence of required arguments.
sub check_usage()
{
   my $failed = 0;

   # parse args:
   if( scalar( @ARGV ) > 0 ) {
      $args->{action} = shift @ARGV;
      foreach my $arg( @ARGV ) {
         if( $arg =~ /--([^=]+)=(.+)/ ) {
            $args->{arguments}->{$1} = $2;
         }
      }
      if( $args->{action} eq '--help' ) {
         usage( STDOUT ); # exits
      } elsif( $args->{action} eq 'createnode' ) {
         my $arguments = $args->{arguments};
         if( !exists( $arguments->{name} ) ||
             !exists( $arguments->{cluster} ) ||
             !exists( $arguments->{imageid} ) ||
             !exists( $arguments->{datacenter} ) ) {
            print STDERR "Action 'createnode' requires a datacenter, cluster or host, the VM template path( imageid ) and the name of the VM to create\n\n";
            $failed = 1;
         }
      } elsif( $args->{action} eq 'destroynode' ) {
         my $arguments = $args->{arguments};
         # Either vm_path should be input or both datacenter and vm_name.
         if( !exists( $arguments->{vm_path} ) && 
             !( exists( $arguments->{datacenter} ) && 
                exists( $arguments->{id} )) ) { 
            print STDERR "Action 'destroynode' requires either the datacenter and instace uuid of the VM to destroy OR the full path of the vm to destroy.\n\n";
            $failed = 1;
         }
      } elsif( $args->{action} eq 'search' ) {
         my $arguments = $args->{arguments};
         if( !exists( $arguments->{object} ) ) { 
            print STDERR "Action 'search' requires the object name to be searched.\n\n";
            $failed = 1;
         }
      } elsif( $args->{action} eq 'status' ) {
         # Do nothing
      } else {
         print STDERR "Unkown action: '$args->{action}'\n\n";
         $failed = 1;
      }
   }
   if( !defined( $args->{action} ) ) {
      print STDERR "No action given\n\n";
      $failed = 1;
   } elsif( !defined( $args->{arguments}->{cloudcreds} ) ) {
      print STDERR "No credential file given\n\n";
      $failed = 1;
   }
   return $failed;
}


sub get_status()
{
   my $call_args = $args->{arguments};

   login( $call_args->{cloudcreds} );

   my %response;
   $response{version} = 1;

   my $details = [ 
      "name",
      "guest.net",
      "summary.guest.ipAddress",
      "summary.runtime.powerState",
      "summary.config.instanceUuid",
      "summary.config.template",
      "summary.quickStats.uptimeSeconds",
      "summary.runtime.bootTime"
      ];

   my( $vms, $error ) = $client->getVMs( $call_args->{datacenter},
                                         $call_args->{prefix},
                                         $details
                                       );

   logout();
  
   if( $error ) {
      print( STDERR "Error in getting status of nodes: $error\n" );
      $args->{status} = -1;
      return;
   }
   
   my $result = { NodeStatusResponse => { code => 200, version => 1 } };
   my $nodes = [];
   my $now = time();

   foreach my $vm ( keys %$vms ) {
      my $node_details = {};
      my $node = $vms->{$vm};

      # Only report VM's that are powered on.
      if( $node->{'summary.runtime.powerState'} ne 'poweredOn' ) {
         next;
      } 

      $node_details->{'sizeid'} = '';
      $node_details->{'status'} = ( $node->{'summary.runtime.powerState'} eq 'poweredOn' )
                                  ? 'active' : 'unknown';
      $node_details->{'name'} = $vm; 
      my $node_public_ip = $node->{'summary.guest.ipAddress'}
                                       || $node->{'guest.net'} 
                                       || "";
      $node_details->{'public_ip'} = $node_public_ip;
      $node_details->{'private_ip'} = $node_public_ip; 

      if( $node_public_ip ne '0.0.0.0' ) {
         $node_details->{'complete'} = 100;
      } else {
         $node_details->{'status'} = 'pending';
         $node_details->{'complete'} = 50; # a bit arbitrary...
      }

      $node_details->{'uniq_id'} = $node->{'summary.config.instanceUuid'};
      $node_details->{'imageid'} = '';
      my $uptime = $node->{'summary.quickStats.uptimeSeconds'} || 0;
      $node_details->{'created'} = $now - $uptime;
      push( @$nodes, $node_details );
   }

   $result->{NodeStatusResponse}->{nodes} = $nodes;

   $args->{result} = formatJSON( $result );
   $args->{status} = 1;
}

# Create a a new VM on the vCenter.
sub create_node()
{
   my $call_args = $args->{arguments};

   login( $call_args->{cloudcreds} );

   my $failed = 0;

   # The path of the VM is of the form <Datacenter>/vm/<VMname>
   my $vm_fullpath = "/".$call_args->{datacenter}."/vm/".$call_args->{name};

   if( existsV( $vm_fullpath ) ) {
      print( STDERR "VM '$call_args->{name}' already exists on the vCenter installation\n" );
      $args->{status} = -1;
      logout();
      return;
   }
   # Checks for datacenter, template, cluster and datastore are done in VSphereClient.pm.

   my %params = ( 
      vm_name => $call_args->{name},
      template_path => $call_args->{imageid},
      datacenter => $call_args->{datacenter},
      cluster => $call_args->{cluster},
      datastore => $call_args->{datastore},
      );
                
		
   my( $vms, $error ) = $client->cloneVM( %params );
   logout();

   if( $error ) {
      print( STDERR "Error in creating node: $error\n" );
      $args->{status} = -1;
      return;
   }
   
   my $result = { CreateNodeResponse => { code => 202, version => 1 } };
   my $now = time;

   my $nodes = [];
   foreach my $vm ( keys %$vms ) {
      my $node_details = {};
      my $node = $vms->{$vm};

      if( $node->{'summary.runtime.powerState'} ne 'poweredOn' ) {
         next;
      }

      $node_details->{'sizeid'} = '';
      $node_details->{'status'} = ( $node->{'summary.runtime.powerState'}
                                  eq 'poweredOn' ) ? 'active' : '?';
      $node_details->{'name'} = $vm;
      $node_details->{'public_ip'} = $node->{'summary.guest.ipAddress'} 
                                       || $node->{'guest.net'}
                                       || '0.0.0.0';
      $node_details->{'private_ip'} = $node_details->{'public_ip'};
      $node_details->{'uniq_id'} = $node->{'summary.config.instanceUuid'};
      $node_details->{'imageid'} = '';

      $uptime = $node->{'summary.quickStats.uptimeSeconds'} || 0;
      $node_details->{'created'} = $now - $uptime;

      $node_details->{'complete'} = 100;
      push @$nodes, $node_details;
   }

   $result->{CreateNodeResponse}->{nodes} = $nodes;
 
   $args->{result} = formatJSON( $result );
   $args->{status} = 1;

}
   
# Destroy a VM with either a give UID of the VM or the full
# inventory path of the VM.
sub destroy_node()
{
   my $call_args = $args->{arguments};

   login( $call_args->{cloudcreds} );

   my $vmid = $call_args->{id} || 0;
   my $vmPath = $call_args->{vm_path} || ''; 
   my $datacenter = $call_args->{datacenter} || ""; 

   my( $status, $error ) = $client->destroyVM( $datacenter, $vmid, $vmPath );
   logout();

   if( $error ) {
      print( STDERR "Error in destroying node: $error\n" );
      $args->{status} = -1;
      return;
   }

   my $result = { DestroyNodeResponse => { code => 202, version => 1 } };

   my $node = {};
   $node->{"created"} = 0;
   $node->{"sizeid"} = "unknown";
   $node->{"uniq_id"} = $vmid;
   $node->{"status"} = "destroyed";
   $node->{"name"} = "unknown";
   $node->{"imageid"} = "unknown";
   $node->{"complete"} = 100;
   
   my $nodes = [ $node ];

   $result->{DestroyNodeResponse}->{nodes} = $nodes;

   $args->{result} = formatJSON( $result );
   $args->{status} = 1;

}

# Looks to see if an object exists in the VCenter inventory.
# The object should have the full inventory path.
sub search()
{
   my $call_args = $args->{arguments};

   login( $call_args->{cloudcreds} );
  
   my $obj = $call_args->{object};
   if( !existsV( $obj ) ) {
      print( STDERR "The object '$obj' cannot be found in vCenter inventory\n" );
   }

   logout();
}

# Check if the object exists in the VCenter inventory.
sub existsV($)
{
   my( $obj ) = @_;

   my $call_args = $args->{arguments};
   my $ref = $client->findByPath( $obj );

   return $ref;
}

sub login($)
{
   my( $credname ) = @_;
   
   my( $user, $password, $proxy ) = get_credentials( $credname );

   if( !$proxy ) {
      die "No API server in the credentials file\n";
   }

   # Sanitize proxy IP/name.
   $proxy = "https://$proxy/sdk/vimService";
   $client->set_proxy( $proxy );

   my $error = $client->login( $user, $password );
   if( $error ) {
      die "Cannot login to VMWare vCentre, please check your credentials - Error: $error\n";
   }
}

sub logout()
{
   $client->logout();
}

sub get_credentials($)
{
   my( $file ) = @_;
   my $conf = "$ENV{ZEUSHOME}/zxtm/conf/cloudcredentials/$file";

   if( ! -e $conf ) {
      print( STDERR "Cannot continue, credentials file '$conf' does not exist.\n" );
      exit( -1 );
   } 

   my $cred_cfg = new Zeus::KeyValueConfigFile( $conf );

   my $user = $cred_cfg->get( 'cred1' );
   my $password = $cred_cfg->get( 'cred2' );
   my $proxy = $cred_cfg->get( 'api_server' );

   TRACE( "GetCredentials - UserName: ", $user );
   TRACE( "GetCredentials - Password: ", $password );
   TRACE( "GetCredentials - API Server: ", $proxy );

   return( $user, $password, $proxy );
}

sub TRACE($$)
{
   my ( $text, $obj ) = @_;
   
   return unless $verbose;
   print( STDERR $text );
   print( STDERR "$obj\n" );
}
