Search in sources :

Example 6 with AmazonEC2Client

use of com.amazonaws.services.ec2.AmazonEC2Client in project druid by druid-io.

the class EC2AutoScalerTest method testScale.

@Test
public void testScale() {
    RunInstancesResult runInstancesResult = EasyMock.createMock(RunInstancesResult.class);
    EC2AutoScaler autoScaler = new EC2AutoScaler(0, 1, ENV_CONFIG, amazonEC2Client, managementConfig);
    EasyMock.expect(amazonEC2Client.runInstances(EasyMock.anyObject(RunInstancesRequest.class))).andReturn(runInstancesResult);
    EasyMock.expect(amazonEC2Client.describeInstances(EasyMock.anyObject(DescribeInstancesRequest.class))).andReturn(describeInstancesResult);
    EasyMock.expect(amazonEC2Client.terminateInstances(EasyMock.anyObject(TerminateInstancesRequest.class))).andReturn(null);
    EasyMock.replay(amazonEC2Client);
    EasyMock.expect(runInstancesResult.getReservation()).andReturn(reservation).atLeastOnce();
    EasyMock.replay(runInstancesResult);
    EasyMock.expect(describeInstancesResult.getReservations()).andReturn(Collections.singletonList(reservation)).atLeastOnce();
    EasyMock.replay(describeInstancesResult);
    EasyMock.expect(reservation.getInstances()).andReturn(Collections.singletonList(instance)).atLeastOnce();
    EasyMock.replay(reservation);
    AutoScalingData created = autoScaler.provision();
    Assert.assertEquals(created.getNodeIds().size(), 1);
    Assert.assertEquals("theInstance", created.getNodeIds().get(0));
    AutoScalingData deleted = autoScaler.terminate(Arrays.asList("dummyIP"));
    Assert.assertEquals(deleted.getNodeIds().size(), 1);
    Assert.assertEquals(INSTANCE_ID, deleted.getNodeIds().get(0));
    EasyMock.verify(runInstancesResult);
}
Also used : RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest) EC2AutoScaler(io.druid.indexing.overlord.autoscaling.ec2.EC2AutoScaler) TerminateInstancesRequest(com.amazonaws.services.ec2.model.TerminateInstancesRequest) Test(org.junit.Test)

Example 7 with AmazonEC2Client

use of com.amazonaws.services.ec2.AmazonEC2Client in project elasticsearch by elastic.

the class AwsEc2ServiceImpl method client.

@Override
public synchronized AmazonEC2 client() {
    if (client != null) {
        return client;
    }
    this.client = new AmazonEC2Client(buildCredentials(logger, settings), buildConfiguration(logger, settings));
    String endpoint = findEndpoint(logger, settings);
    if (endpoint != null) {
        client.setEndpoint(endpoint);
    }
    return this.client;
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client)

Example 8 with AmazonEC2Client

use of com.amazonaws.services.ec2.AmazonEC2Client in project SimianArmy by Netflix.

the class AWSClient method ec2Client.

/**
     * Amazon EC2 client. Abstracted to aid testing.
     *
     * @return the Amazon EC2 client
     */
protected AmazonEC2 ec2Client() {
    AmazonEC2 client;
    if (awsClientConfig == null) {
        if (awsCredentialsProvider == null) {
            client = new AmazonEC2Client();
        } else {
            client = new AmazonEC2Client(awsCredentialsProvider);
        }
    } else {
        if (awsCredentialsProvider == null) {
            client = new AmazonEC2Client(awsClientConfig);
        } else {
            client = new AmazonEC2Client(awsCredentialsProvider, awsClientConfig);
        }
    }
    client.setEndpoint("ec2." + region + ".amazonaws.com");
    return client;
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2)

Example 9 with AmazonEC2Client

use of com.amazonaws.services.ec2.AmazonEC2Client in project ice by Netflix.

the class BasicReservationService method pollAPI.

private void pollAPI() throws Exception {
    long currentTime = new DateMidnight().getMillis();
    DescribeReservedInstancesOfferingsRequest req = new DescribeReservedInstancesOfferingsRequest().withFilters(new com.amazonaws.services.ec2.model.Filter().withName("marketplace").withValues("false"));
    String token = null;
    boolean hasNewPrice = false;
    AmazonEC2Client ec2Client = new AmazonEC2Client(AwsUtils.awsCredentialsProvider, AwsUtils.clientConfig);
    for (Region region : Region.getAllRegions()) {
        ec2Client.setEndpoint("ec2." + region.name + ".amazonaws.com");
        do {
            if (!StringUtils.isEmpty(token))
                req.setNextToken(token);
            DescribeReservedInstancesOfferingsResult offers = ec2Client.describeReservedInstancesOfferings(req);
            token = offers.getNextToken();
            for (ReservedInstancesOffering offer : offers.getReservedInstancesOfferings()) {
                if (offer.getProductDescription().indexOf("Amazon VPC") >= 0)
                    continue;
                ReservationUtilization utilization = ReservationUtilization.get(offer.getOfferingType());
                Ec2InstanceReservationPrice.ReservationPeriod term = offer.getDuration() / 24 / 3600 > 366 ? Ec2InstanceReservationPrice.ReservationPeriod.threeyear : Ec2InstanceReservationPrice.ReservationPeriod.oneyear;
                if (term != this.term)
                    continue;
                double hourly = offer.getUsagePrice();
                if (hourly <= 0) {
                    for (RecurringCharge recurringCharge : offer.getRecurringCharges()) {
                        if (recurringCharge.getFrequency().equals("Hourly")) {
                            hourly = recurringCharge.getAmount();
                            break;
                        }
                    }
                }
                UsageType usageType = getUsageType(offer.getInstanceType(), offer.getProductDescription());
                // Unknown Zone
                if (Zone.getZone(offer.getAvailabilityZone()) == null) {
                    logger.error("No Zone for " + offer.getAvailabilityZone());
                } else {
                    hasNewPrice = setPrice(utilization, currentTime, Zone.getZone(offer.getAvailabilityZone()).region, usageType, offer.getFixedPrice(), hourly) || hasNewPrice;
                    logger.info("Setting RI price for " + Zone.getZone(offer.getAvailabilityZone()).region + " " + utilization + " " + usageType + " " + offer.getFixedPrice() + " " + hourly);
                }
            }
        } while (!StringUtils.isEmpty(token));
    }
    ec2Client.shutdown();
    if (hasNewPrice) {
        for (ReservationUtilization utilization : files.keySet()) {
            File file = files.get(utilization);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
            try {
                Serializer.serialize(out, this.ec2InstanceReservationPrices.get(utilization));
                AwsUtils.upload(config.workS3BucketName, config.workS3BucketPrefix, file);
            } finally {
                out.close();
            }
        }
    }
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) Ec2InstanceReservationPrice(com.netflix.ice.processor.Ec2InstanceReservationPrice) DateMidnight(org.joda.time.DateMidnight) Region(com.netflix.ice.tag.Region) com.amazonaws.services.ec2.model(com.amazonaws.services.ec2.model)

Example 10 with AmazonEC2Client

use of com.amazonaws.services.ec2.AmazonEC2Client in project h2o-2 by h2oai.

the class EC2 method resize.

//@formatter:on
/**
   * Create or terminate EC2 instances. Uses their Name tag to find existing ones.
   */
public Cloud resize() throws Exception {
    AmazonEC2Client ec2 = new AmazonEC2Client(new PersistS3.H2OAWSCredentialsProviderChain());
    ec2.setEndpoint("ec2." + region + ".amazonaws.com");
    DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesResult.getReservations();
    List<Instance> instances = new ArrayList<Instance>();
    for (Reservation reservation : reservations) {
        for (Instance instance : reservation.getInstances()) {
            String ip = ip(instance);
            if (ip != null) {
                String name = null;
                if (instance.getTags().size() > 0)
                    name = instance.getTags().get(0).getValue();
                if (NAME.equals(name))
                    instances.add(instance);
            }
        }
    }
    System.out.println("Found " + instances.size() + " EC2 instances for user " + USER);
    if (instances.size() > boxes) {
        for (int i = 0; i < instances.size() - boxes; i++) {
        // TODO terminate?
        }
    } else if (instances.size() < boxes) {
        int launchCount = boxes - instances.size();
        System.out.println("Creating " + launchCount + " EC2 instances.");
        if (confirm) {
            System.out.println("Please confirm [y/n]");
            String s = Utils.readConsole();
            if (s == null || !s.equalsIgnoreCase("y"))
                throw new Exception("Aborted");
        }
        CreatePlacementGroupRequest group = new CreatePlacementGroupRequest();
        group.withGroupName(USER);
        group.withStrategy(PlacementStrategy.Cluster);
        try {
            ec2.createPlacementGroup(group);
        } catch (AmazonServiceException ex) {
            if (!"InvalidPlacementGroup.Duplicate".equals(ex.getErrorCode()))
                throw ex;
        }
        RunInstancesRequest run = new RunInstancesRequest();
        run.withInstanceType(type);
        run.withImageId(image);
        run.withMinCount(launchCount).withMaxCount(launchCount);
        run.withSecurityGroupIds(securityGroup);
        Placement placement = new Placement();
        placement.setGroupName(USER);
        run.withPlacement(placement);
        BlockDeviceMapping map = new BlockDeviceMapping();
        map.setDeviceName("/dev/sdb");
        map.setVirtualName("ephemeral0");
        run.withBlockDeviceMappings(map);
        run.withUserData(new String(Base64.encodeBase64(cloudConfig.getBytes())));
        RunInstancesResult runRes = ec2.runInstances(run);
        ArrayList<String> ids = new ArrayList<String>();
        for (Instance instance : runRes.getReservation().getInstances()) ids.add(instance.getInstanceId());
        List<Instance> created = wait(ec2, ids);
        System.out.println("Created " + created.size() + " EC2 instances.");
        instances.addAll(created);
    }
    String[] pub = new String[boxes];
    String[] prv = new String[boxes];
    for (int i = 0; i < boxes; i++) {
        pub[i] = instances.get(i).getPublicIpAddress();
        prv[i] = instances.get(i).getPrivateIpAddress();
    }
    System.out.println("EC2 public IPs: " + Utils.join(' ', pub));
    System.out.println("EC2 private IPs: " + Utils.join(' ', prv));
    Cloud cloud = new Cloud();
    cloud.publicIPs.addAll(Arrays.asList(pub));
    cloud.privateIPs.addAll(Arrays.asList(prv));
    return cloud;
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) PersistS3(water.persist.PersistS3) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonServiceException(com.amazonaws.AmazonServiceException)

Aggregations

AmazonEC2Client (com.amazonaws.services.ec2.AmazonEC2Client)15 AmazonServiceException (com.amazonaws.AmazonServiceException)12 Collection (java.util.Collection)11 Message (org.apache.camel.Message)10 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)8 AWSCredentials (com.amazonaws.auth.AWSCredentials)7 PropertiesCredentials (com.amazonaws.auth.PropertiesCredentials)6 DescribeInstancesRequest (com.amazonaws.services.ec2.model.DescribeInstancesRequest)4 Instance (com.amazonaws.services.ec2.model.Instance)4 File (java.io.File)4 BasicAWSCredentials (com.amazonaws.auth.BasicAWSCredentials)3 Reservation (com.amazonaws.services.ec2.model.Reservation)3 EC2AutoScaler (io.druid.indexing.overlord.autoscaling.ec2.EC2AutoScaler)3 IOException (java.io.IOException)3 Date (java.util.Date)3 Test (org.junit.Test)3 InstanceProfileCredentialsProvider (com.amazonaws.auth.InstanceProfileCredentialsProvider)2 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)2 Filter (com.amazonaws.services.ec2.model.Filter)2 RunInstancesRequest (com.amazonaws.services.ec2.model.RunInstancesRequest)2