/**
 * Copyright (c) 2018 Netflix, Inc.  All rights reserved.
 */
package com.netflix.ndbench.core.discovery;

import com.amazonaws.services.autoscaling.AmazonAutoScaling;
import com.amazonaws.services.autoscaling.AmazonAutoScalingClientBuilder;
import com.amazonaws.services.autoscaling.model.*;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.netflix.ndbench.core.config.IConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.ec2.model.Instance;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AWSAsgDiscovery assumes you have enough permissions to run autoscaling:DescribeAutoScalingInstances and
 * describeInstances request on AWS.
 *
 * This class also assumes that NdBench is deployed in an ASG.
 *
 * <b>Important:</b> Be sure to fill in your AWS access credentials in
 * ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows
 * users) before you try to run this sample.
 * @author vchella
 */
public class AwsAsgDiscovery implements IClusterDiscovery {
    private static final Logger logger = LoggerFactory.getLogger(LocalClusterDiscovery.class.getName());

    IConfiguration config;
    @Inject
    public AwsAsgDiscovery(IConfiguration configuration)
    {
        this.config = configuration;
    }
    @Override
    public List<String> getApps() {
        return Arrays.asList(getCurrentAsgName());
    }

    @Override
    public List<String> getEndpoints(String appName, int defaultPort) {

        return getRacMembership().stream().map(s -> s+":"+defaultPort).collect(Collectors.toList());

    }

    public List<String> getRacMembership()
    {
        List<String> instanceIps = new LinkedList<>();


         /*
         * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users)
         * and save the following lines after replacing the underlined values with your own.
         *
         * [default]
         * aws_access_key_id = YOUR_ACCESS_KEY_ID
         * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
         */

        AmazonAutoScaling client = null;
        AmazonEC2 ec2Client = null;

        try
        {
            client = getAutoScalingClient();
            ec2Client = AmazonEC2ClientBuilder.standard().build();

            String myAsgName = getCurrentAsgName();

            DescribeAutoScalingGroupsRequest asgReq = new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(myAsgName);

            DescribeAutoScalingGroupsResult res = client.describeAutoScalingGroups(asgReq);

            List<String> instanceIds = Lists.newArrayList();
            for (AutoScalingGroup asg : res.getAutoScalingGroups())
            {
                for (com.amazonaws.services.autoscaling.model.Instance ins : asg.getInstances())
                    if (!(ins.getLifecycleState().equalsIgnoreCase("Terminating") || ins.getLifecycleState().equalsIgnoreCase("shutting-down") || ins.getLifecycleState()
                            .equalsIgnoreCase("Terminated")))
                        instanceIds.add(ins.getInstanceId());
            }
            logger.info(String.format("Querying Amazon returned following instance in the ASG: %s --> %s", myAsgName, StringUtils.join(instanceIds, ",")));


            DescribeInstancesRequest insReq = new DescribeInstancesRequest().withInstanceIds(instanceIds);

            DescribeInstancesResult insRes = ec2Client.describeInstances(insReq);

            instanceIps =  insRes.getReservations().get(0)
                    .getInstances()
                    .stream()
                    .map(Instance::getPrivateIpAddress)
                    .collect(Collectors.toList());



            return instanceIps;
        }
        catch (Exception e)
        {
            logger.error("Exception in getting private IPs from current ASG",e);
        }
        finally
        {
            if (client != null)
                client.shutdown();
            if(ec2Client !=null)
                ec2Client.shutdown();
        }
        return instanceIps;
    }

    private String getCurrentAsgName()
    {
        DescribeAutoScalingInstancesRequest asgInsReq = new DescribeAutoScalingInstancesRequest()
                .withInstanceIds(AWSUtil.getLocalInstanceId());

        DescribeAutoScalingInstancesResult asgInsRes = getAutoScalingClient().describeAutoScalingInstances(asgInsReq);
        String myAsgName = asgInsRes.getAutoScalingInstances().get(0).getAutoScalingGroupName();
        return myAsgName!=null && myAsgName.length() > 0 ? myAsgName : "NdBench_Aws_cluster";
    }

    protected AmazonAutoScaling getAutoScalingClient() {
        AmazonAutoScaling client = AmazonAutoScalingClientBuilder.standard().build();
        return client;
    }


}

@@ -339,59 +339,8 @@
 C2;%0A
-import com.amazonaws.services.ec2.AmazonEC2Client;%0A
 impo
@@ -524,16 +524,66 @@
 Result;%0A
+import com.amazonaws.services.ec2.model.Instance;%0A
 import c
@@ -808,134 +808,27 @@
 ry;%0A
-import com.amazonaws.services.ec2.model.Instance;%0A%0Aimport java.util.Arrays;%0Aimport java.util.LinkedList;%0Aimport java.util.List
+%0Aimport java.util.*
 ;%0Aim
@@ -1957,65 +1957,8 @@
   %7B%0A
-        List%3CString%3E instanceIps = new LinkedList%3C%3E();%0A%0A%0A
     
@@ -3720,32 +3720,44 @@
 q);%0A%0A           
+ Set%3CString%3E
  instanceIps =  
@@ -3753,14 +3753,18 @@
 ance
-Ip
+DnsName
 s =
- 
  ins
@@ -3785,21 +3785,23 @@
 tions().
-get(0
+stream(
 )%0A      
@@ -3819,43 +3819,37 @@
    .
-getInstances()%0A                    
+flatMap(r -%3E r.getInstances()
 .str
@@ -3845,32 +3845,33 @@
 ances().stream()
+)
 %0A               
@@ -3898,23 +3898,20 @@
 getP
-rivateIpAddress
+ublicDnsName
 )%0A  
@@ -3954,20 +3954,17 @@
 s.to
-Lis
+Se
 t());%0A%0A
-%0A%0A
     
@@ -3974,35 +3974,57 @@
      return 
-instanceIps
+new ArrayList%3C%3E(instanceDnsNames)
 ;%0A        %7D%0A
@@ -4142,16 +4142,60 @@
 SG%22,e);%0A
+            return Collections.emptyList();%0A
         
@@ -4374,36 +4374,8 @@
   %7D%0A
-        return instanceIps;%0A
     

Make AWS_ASG discovery find instances cross reservations (#70)