com.amazonaws.services.ec2.model.DescribeInstancesRequest Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.DescribeInstancesRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/***
 * Get list of EC2 {@link Instance}s for a auto scaling group
 *
 * @param groupName Auto scaling group name
 * @param status Instance status (eg. running)
 * @return List of EC2 instances found for the input auto scaling group
 */
public List<Instance> getInstancesForGroup(String groupName,
    String status) {

  final AmazonEC2 amazonEC2 = getEc2Client();

  final DescribeInstancesResult instancesResult = amazonEC2.describeInstances(new DescribeInstancesRequest()
      .withFilters(new Filter().withName("tag:aws:autoscaling:groupName").withValues(groupName)));

  final List<Instance> instances = new ArrayList<>();
  for (Reservation reservation : instancesResult.getReservations()) {
    for (Instance instance : reservation.getInstances()) {
      if (null == status|| null == instance.getState()
          || status.equals(instance.getState().getName())) {
        instances.add(instance);
        LOGGER.info("Found instance: " + instance + " which qualified filter: " + status);
      } else {
        LOGGER.info("Found instance: " + instance + " but did not qualify for filter: " + status);
      }
    }
  }

  return instances;
}
 
Example #2
Source File: AwsInstanceCloudConnector.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<List<Instance>> getInstances(List<String> instanceIds) {
    if (instanceIds.isEmpty()) {
        return Observable.just(Collections.emptyList());
    }
    List<Observable<List<Instance>>> chunkObservable = CollectionsExt.chop(instanceIds, AWS_INSTANCE_ID_MAX).stream()
            .map(chunk -> {
                Observable<DescribeInstancesResult> ec2DescribeObservable = toObservable(new DescribeInstancesRequest().withInstanceIds(chunk), ec2Client::describeInstancesAsync);
                Observable<DescribeAutoScalingInstancesResult> asgDescribeObservable = toObservable(new DescribeAutoScalingInstancesRequest().withInstanceIds(chunk), autoScalingClient::describeAutoScalingInstancesAsync);
                return Observable.zip(ec2DescribeObservable, asgDescribeObservable, (ec2Data, autoScalerData) -> toInstances(ec2Data.getReservations(), autoScalerData.getAutoScalingInstances()));
            })
            .collect(Collectors.toList());
    return Observable.merge(chunkObservable, AWS_PARALLELISM)
            .timeout(configuration.getAwsRequestTimeoutMs(), TimeUnit.MILLISECONDS)
            .reduce(new ArrayList<>(), (acc, result) -> {
                acc.addAll(result);
                return acc;
            });
}
 
Example #3
Source File: EC2ClientActions.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public List<String> getInstanceVolumeIds(List<String> instanceIds) {
    AmazonEC2 ec2Client = buildEC2Client();
    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds));
    Map<String, Set<String>> instanceIdVolumeIdMap = describeInstancesResult.getReservations()
            .stream()
            .map(Reservation::getInstances)
            .flatMap(Collection::stream)
            .collect(Collectors.toMap(Instance::getInstanceId,
                    instance -> instance.getBlockDeviceMappings()
                            .stream()
                            .filter(dev -> !"/dev/xvda".equals(dev.getDeviceName()))
                            .map(InstanceBlockDeviceMapping::getEbs)
                            .map(EbsInstanceBlockDevice::getVolumeId)
                            .collect(Collectors.toSet())
            ));
    instanceIdVolumeIdMap.forEach((instanceId, volumeIds) -> Log.log(LOGGER, format(" Attached volume IDs are %s for [%s] EC2 instance ",
            volumeIds.toString(), instanceId)));
    return instanceIdVolumeIdMap
            .values()
            .stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
}
 
Example #4
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<String> getInstanceName(String region, String instanceId) {
    final AmazonEC2 amazonEC2 = AmazonEC2ClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();

    List<String> instanceIds = new ArrayList<>();
    instanceIds.add(instanceId);

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);

    DescribeInstancesResult result = amazonEC2.describeInstances(request);
    Optional<String> tagOptional = result.getReservations()
            .stream()
            .flatMap(reservation -> reservation.getInstances().stream())
            .flatMap(instance -> instance.getTags().stream())
            .filter(tag -> NAME_ENTRY.equals(tag.getKey()))
            .findFirst()
            .map(Tag::getValue);
    return tagOptional;
}
 
Example #5
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
   * Gets the instance details for ec 2.
   *
   * @param clientMap the client map
   * @param resourceId the resource id
   * @return the instance details for ec 2
   * @throws Exception the exception
   */
  public static Instance getInstanceDetailsForEc2(Map<String,Object> clientMap,String resourceId) throws Exception {
  	AmazonEC2 ec2Client = (AmazonEC2) clientMap.get("client");
  	DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setInstanceIds(Arrays.asList(resourceId));


RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
RetryRegistry registry = RetryRegistry.of(config);

Retry retry = registry.retry(describeInstancesRequest.toString());
 		
Function<Integer, Instance> decorated
  =  Retry.decorateFunction(retry, (Integer s) -> {
	  DescribeInstancesResult  describeInstancesResult =  ec2Client.describeInstances(describeInstancesRequest);
	  List<Reservation> reservations = describeInstancesResult.getReservations();
		Reservation reservation = reservations.get(0);
		List<Instance> instances = reservation.getInstances();
		return instances.get(0);
    });
return decorated.apply(1);
	
  }
 
Example #6
Source File: Ec2Facade.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 6 votes vote down vote up
public String getInstanceId(Tag instanceTag) {
    Filter tagFilter = new Filter("tag:" + instanceTag.getKey(), ImmutableList.of(instanceTag.getValue()));
    DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(tagFilter, RUNNING_INSTANCE_FILTER);
    DescribeInstancesResult result = ec2.describeInstances(request);

    List<String> instanceIds;
    if (result.getReservations() != null) {
        instanceIds = result.getReservations().stream()
                .flatMap(reservation -> reservation.getInstances().stream())
                .map(Instance::getInstanceId)
                .collect(ImmutableList.toImmutableList());
    } else {
        instanceIds = ImmutableList.of();
    }

    if (instanceIds.isEmpty()) {
        String message = String.format(
                "Invalid FulfillmentConfig. No instances found with TagKey: %s and TagValue: %s",
                instanceTag.getKey(),
                instanceTag.getValue());
        throw new RuntimeException(message);
    }

    int randomIndex = randomGenerator.nextInt(instanceIds.size());
    return instanceIds.get(randomIndex);
}
 
Example #7
Source File: EC2ApiTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void describeInstances_shouldFailIfNotAbleToParseNotFoundExceptionFromEc2Api() {
    // given
    Set<String> instanceIds = new HashSet<>();
    instanceIds.add("i-1");
    instanceIds.add("i-f");
    instanceIds.add("i-3");

    AmazonEC2Exception notFoundException = new AmazonEC2Exception(
            "unparseable");
    notFoundException.setErrorCode("InvalidInstanceID.NotFound");

    when(amazonEC2.describeInstances(any(DescribeInstancesRequest.class)))
            .thenThrow(notFoundException);

    // when
    try {
        new EC2Api().describeInstances(amazonEC2, instanceIds);
        Assert.fail();
    } catch (AmazonEC2Exception exception) {
        Assert.assertSame(notFoundException, exception);
    }
}
 
Example #8
Source File: AwsEc2SeedHostsProvider.java    From crate with Apache License 2.0 6 votes vote down vote up
private DescribeInstancesRequest buildDescribeInstancesRequest() {
    final DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
        .withFilters(
            new Filter("instance-state-name").withValues("running", "pending")
        );

    for (final Map.Entry<String, List<String>> tagFilter : tags.entrySet()) {
        // for a given tag key, OR relationship for multiple different values
        describeInstancesRequest.withFilters(
            new Filter("tag:" + tagFilter.getKey()).withValues(tagFilter.getValue())
        );
    }

    if (!availabilityZones.isEmpty()) {
        // OR relationship amongst multiple values of the availability-zone filter
        describeInstancesRequest.withFilters(
            new Filter("availability-zone").withValues(availabilityZones)
        );
    }

    return describeInstancesRequest;
}
 
Example #9
Source File: EC2ApiTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void describeInstances_shouldThrowExceptionIfEc2DescribeFailsWithException() {
    // given
    Set<String> instanceIds = new HashSet<>();
    instanceIds.add("a");

    UnsupportedOperationException exception = new UnsupportedOperationException("test");
    when(amazonEC2.describeInstances(any(DescribeInstancesRequest.class)))
            .thenThrow(exception);

    // when
    try {
        new EC2Api().describeInstances(amazonEC2, instanceIds);
        Assert.fail();
    } catch (UnsupportedOperationException e) {
        Assert.assertSame(exception, e);
    }
}
 
Example #10
Source File: BaseTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Describe instances.
 *
  * @return list of instances
 */
protected final List<Instance> describeInstances() {

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    DescribeInstancesResult result = amazonEC2Client
            .describeInstances(request);
    List<Instance> instanceList = new ArrayList<Instance>();
    if (result.getReservations().size() > 0) {
     Assert.assertTrue(result.getReservations().size() > 0);

     for (Reservation reservation : result.getReservations()) {
         List<Instance> instances = reservation.getInstances();
	
         if (null != instances) {
             for (Instance i : instances) {
                 instanceList.add(i);
             }
         }
     }
    }
    return instanceList;
}
 
Example #11
Source File: EC2Communication.java    From development with Apache License 2.0 6 votes vote down vote up
public String getInstanceState(String instanceId) {
    LOGGER.debug("getInstanceState('{}') entered", instanceId);
    DescribeInstancesResult result = getEC2().describeInstances(
            new DescribeInstancesRequest().withInstanceIds(instanceId));
    List<Reservation> reservations = result.getReservations();
    Set<Instance> instances = new HashSet<Instance>();

    for (Reservation reservation : reservations) {
        instances.addAll(reservation.getInstances());
        if (instances.size() > 0) {
            String state = instances.iterator().next().getState().getName();
            LOGGER.debug("  InstanceState: {}", state);
            return state;
        }
    }
    LOGGER.debug("getInstanceState('{}') left", instanceId);
    return null;
}
 
Example #12
Source File: EC2Utils.java    From amazon-kinesis-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Return the DNS name of one Amazon EC2 instance with the provided filter name and value.
 * 
 * @param ec2Client
 *        an Amazon EC2 instance
 * @param filterName
 *        the name of the filter
 * @param filterValue
 *        the value of the filter
 * @return the public DNS name of an instance with the filter name and value. Null if none exist.
 */
public static String getEndpointForFirstActiveInstanceWithTag(AmazonEC2 ec2Client,
        String filterName,
        String filterValue) {
    DescribeInstancesRequest describeInstancesRequest =
            new DescribeInstancesRequest().withFilters(new Filter().withName(filterName).withValues(filterValue));
    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest);

    List<Reservation> reservations = describeInstancesResult.getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> ec2Instances = reservation.getInstances();
        for (Instance ec2Instance : ec2Instances) {
            if (InstanceStateName.Running.toString().equals(ec2Instance.getState().getName())) {
                return ec2Instance.getPublicDnsName();
            }
        }
    }
    return null;
}
 
Example #13
Source File: EC2ProcessorTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void process_STOPING() throws Exception {
    // given
    ec2mock.createDescribeInstancesResult("instance1", "stopped", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ph.setOperation(Operation.EC2_OPERATION);
    ph.setState(FlowState.STOPPING);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertTrue(result.isReady());
    assertEquals(FlowState.FINISHED, ph.getState());

    verify(ec2).describeInstances(any(DescribeInstancesRequest.class));
}
 
Example #14
Source File: AutomationReaperTask.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void doWork() {
    log.info("Running " + AutomationReaperTask.NAME);
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    Filter filter = new Filter("tag:LaunchSource");
    filter.withValues("SeleniumGridScalerPlugin");
    describeInstancesRequest.withFilters(filter);
    List<Reservation> reservations = ec2.describeInstances(describeInstancesRequest);
    for(Reservation reservation : reservations) {
        for(Instance instance : reservation.getInstances()) {
            // Look for orphaned nodes
            Date threshold = AutomationUtils.modifyDate(new Date(),-30, Calendar.MINUTE);
            String instanceId = instance.getInstanceId();
            // If we found a node old enough AND we're not internally tracking it, this means this is an orphaned node and we should terminate it
            if(threshold.after(instance.getLaunchTime()) && !AutomationContext.getContext().nodeExists(instanceId)) {
                log.info("Terminating orphaned node: " + instanceId);
                ec2.terminateInstance(instanceId);
            }
        }
    }
}
 
Example #15
Source File: EC2InstanceProviderImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
@Cacheable(cacheNames = "ec2-instance", cacheManager = "twoHoursTTLCacheManager")
public Optional<Instance> getById(final String accountId, final Region region, final String instanceId) {
    try {
        return clientProvider.getClient(AmazonEC2Client.class, accountId, region)
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId))
                .getReservations().stream()
                .flatMap(reservation -> reservation.getInstances().stream())
                .filter(instance -> Objects.equals(instance.getInstanceId(), instanceId))
                .findFirst();
    } catch (AmazonEC2Exception e) {
        if (Objects.equals(e.getErrorCode(), "InvalidInstanceID.NotFound")) {
            return Optional.empty();
        } else {
            throw e;
        }
    }
}
 
Example #16
Source File: AmiIdProviderImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
private Optional<String> getAmiIdFromEC2Api(final EC2InstanceContext context) {
    final String instanceId = context.getInstanceId();
    try {
        return context.getClient(AmazonEC2Client.class)
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId))
                .getReservations()
                .stream()
                .map(Reservation::getInstances)
                .flatMap(Collection::stream)
                .filter(i -> i.getInstanceId().equals(instanceId))
                .map(Instance::getImageId)
                .findFirst();
    } catch (final AmazonClientException e) {
        log.warn("Could not describe instance " + instanceId, e);
        return empty();
    }
}
 
Example #17
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
// @HystrixCommand(fallback = my coole exception)
// command for account id and client type -> generate new credentials
public void processEvent(final CloudTrailEvent event) {

    final String parameters = event.getEventData().getRequestParameters();
    final String instanceId = getFromParameters(parameters);

    final AmazonEC2 client = getClientForAccount(
            event.getEventData().getUserIdentity().getAccountId(),
            Region.getRegion(Regions.fromName(event.getEventData().getAwsRegion())));

    final DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(Collections.singleton(instanceId));

    // try
    final DescribeInstancesResult result = client.describeInstances(request);
    // catch credentials are old
    // throw new my coole exception ( account id, CLIENTTYPE.EC2, exception) -> this will trigger hystrix

    LOG.info("SAVING RESULT INTO MAGIC DB", result);
}
 
Example #18
Source File: AwsRepairTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void upscaleStack() throws Exception {
    AuthenticatedContext authenticatedContext = componentTestUtil.getAuthenticatedContext();
    CloudStack stack = componentTestUtil.getStack(InstanceStatus.CREATE_REQUESTED, InstanceStatus.STARTED);
    List<CloudResource> cloudResources = List.of(
            CloudResource.builder()
                    .name(AWS_SUBNET_ID)
                    .type(ResourceType.AWS_SUBNET)
                    .build(),
            createVolumeResource(VOLUME_ID_1, INSTANCE_ID_1, SIZE_DISK_1, FSTAB_1, CommonStatus.DETACHED),
            createVolumeResource(VOLUME_ID_2, INSTANCE_ID_2, SIZE_DISK_2, FSTAB_2, CommonStatus.DETACHED),
            createVolumeResource(VOLUME_ID_3, INSTANCE_ID_3, SIZE_DISK_2, FSTAB_2, CommonStatus.CREATED));

    InMemoryStateStore.putStack(1L, PollGroup.POLLABLE);

    when(amazonCloudFormationRetryClient.describeStackResource(any()))
            .thenReturn(new DescribeStackResourceResult()
                    .withStackResourceDetail(new StackResourceDetail().withPhysicalResourceId(AUTOSCALING_GROUP_NAME)));

    when(amazonAutoScalingRetryClient.describeAutoScalingGroups(any()))
            .thenReturn(new DescribeAutoScalingGroupsResult()
                    .withAutoScalingGroups(new AutoScalingGroup()
                            .withAutoScalingGroupName(AUTOSCALING_GROUP_NAME)
                            .withInstances(List.of(
                                    new Instance().withInstanceId(INSTANCE_ID_1).withLifecycleState(LifecycleState.InService),
                                    new Instance().withInstanceId(INSTANCE_ID_2).withLifecycleState(LifecycleState.InService)))
                    ));

    when(amazonEC2Client.describeVolumes(any()))
            .thenReturn(new DescribeVolumesResult().withVolumes(
                    new com.amazonaws.services.ec2.model.Volume().withVolumeId(VOLUME_ID_1).withState(VolumeState.Available),
                    new com.amazonaws.services.ec2.model.Volume().withVolumeId(VOLUME_ID_2).withState(VolumeState.Available),
                    new com.amazonaws.services.ec2.model.Volume().withVolumeId(VOLUME_ID_3).withState(VolumeState.InUse)
            ));

    when(amazonEC2Client.describeInstances(any())).thenReturn(
            new DescribeInstancesResult().withReservations(
                    new Reservation().withInstances(new com.amazonaws.services.ec2.model.Instance().withInstanceId("i-instance")))
    );


    AmazonEC2Waiters waiters = mock(AmazonEC2Waiters.class);
    when(amazonEC2Client.waiters()).thenReturn(waiters);
    Waiter<DescribeInstancesRequest> instanceWaiter = mock(Waiter.class);
    when(waiters.instanceRunning()).thenReturn(instanceWaiter);

    when(amazonAutoScalingClient.waiters()).thenReturn(asWaiters);
    when(asWaiters.groupInService()).thenReturn(describeAutoScalingGroupsRequestWaiter);

    underTest.upscale(authenticatedContext, stack, cloudResources);

    verify(amazonAutoScalingRetryClient).resumeProcesses(argThat(argument -> AUTOSCALING_GROUP_NAME.equals(argument.getAutoScalingGroupName())
            && argument.getScalingProcesses().contains("Launch")));
    verify(amazonAutoScalingRetryClient).updateAutoScalingGroup(argThat(argument -> {
        Group workerGroup = stack.getGroups().get(1);
        return AUTOSCALING_GROUP_NAME.equals(argument.getAutoScalingGroupName())
                && workerGroup.getInstancesSize().equals(argument.getMaxSize())
                && workerGroup.getInstancesSize().equals(argument.getDesiredCapacity());
    }));

    verify(amazonAutoScalingRetryClient, times(stack.getGroups().size()))
            .suspendProcesses(argThat(argument -> AUTOSCALING_GROUP_NAME.equals(argument.getAutoScalingGroupName())
                    && SUSPENDED_PROCESSES.equals(argument.getScalingProcesses())));

    ArgumentCaptor<CloudResource> updatedCloudResourceArgumentCaptor = ArgumentCaptor.forClass(CloudResource.class);
    verify(resourceNotifier, times(4)).notifyUpdate(updatedCloudResourceArgumentCaptor.capture(), any());

    assertVolumeResource(updatedCloudResourceArgumentCaptor.getAllValues(), INSTANCE_ID_1, SIZE_DISK_1, FSTAB_1);
    assertVolumeResource(updatedCloudResourceArgumentCaptor.getAllValues(), INSTANCE_ID_2, SIZE_DISK_2, FSTAB_2);
}
 
Example #19
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStopSdkExceptionRetry() {
    when(amazonEC2Client.describeInstances(any(DescribeInstancesRequest.class))).thenThrow(new SdkClientException("lamb"),
            new SdkClientException("sheep"),
            new SdkClientException("shepherd")).thenReturn(getDescribeInstancesResult("stopped", 55));
    List<CloudVmInstanceStatus> result = underTest.stop(authenticatedContext, List.of(), inputList);
    verify(amazonEC2Client, times(5)).describeInstances(any(DescribeInstancesRequest.class));
    Assert.assertThat(result, hasSize(2));
}
 
Example #20
Source File: AwsAutoScalingDeployUtils.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public List<Ec2Instance> getInstancesForAutoScalingGroup(Log log, AutoScalingGroup autoScalingGroup) throws MojoFailureException {
    log.info("retrieving list of instanceId's for auto scaling group with id : " + activeConfiguration.getAutoScalingGroupId());

    activeConfiguration.getHosts().clear();

    log.debug("describing instances in auto scaling group");

    if (autoScalingGroup.getInstances().isEmpty()) {
        return new ArrayList<>();
    }

    Map<String, Instance> instanceMap = autoScalingGroup.getInstances().stream().collect(Collectors.toMap(Instance::getInstanceId, Function.identity()));

    try {
        DescribeInstancesResult instancesResult = awsEc2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(autoScalingGroup.getInstances().stream().map(Instance::getInstanceId).collect(Collectors.toList())));
        List<Ec2Instance> ec2Instances = instancesResult.getReservations().stream().flatMap(r -> r.getInstances().stream()).map(this::toEc2Instance).collect(Collectors.toList());
        log.debug("describing elb status");
        autoScalingGroup.getLoadBalancerNames().forEach(elb -> this.updateInstancesStateOnLoadBalancer(elb, ec2Instances));
        ec2Instances.forEach(i -> i.updateAsState(AwsState.map(instanceMap.get(i.getInstanceId()).getLifecycleState())));
        ec2Instances.sort((o1, o2) -> {

            int sComp = o1.getAsState().compareTo(o2.getAsState());

            if (sComp != 0) {
                return sComp;
            } else {
                return o1.getElbState().compareTo(o2.getElbState());
            }
        });
        if (activeConfiguration.isIgnoreInStandby()) {
            return ec2Instances.stream().filter(i -> i.getAsState() != AwsState.STANDBY).collect(Collectors.toList());
        }
        return ec2Instances;
    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
        throw new MojoFailureException(e.getMessage());
    }

}
 
Example #21
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartSdkExceptionRetry() {
    when(amazonEC2Client.describeInstances(any(DescribeInstancesRequest.class))).thenThrow(new SdkClientException("lamb"),
            new SdkClientException("sheep"),
            new SdkClientException("shepherd")).thenReturn(getDescribeInstancesResult("running", 16));
    List<CloudVmInstanceStatus> result = underTest.start(authenticatedContext, List.of(), inputList);
    verify(amazonEC2Client, times(5)).describeInstances(any(DescribeInstancesRequest.class));
    Assert.assertThat(result, hasSize(2));
}
 
Example #22
Source File: SubnetImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public InstanceCollection getInstances(DescribeInstancesRequest request) {
    ResourceCollectionImpl result = resource.getCollection("Instances",
            request);

    if (result == null) return null;
    return new InstanceCollectionImpl(result);
}
 
Example #23
Source File: PlacementGroupImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public InstanceCollection getInstances(DescribeInstancesRequest request) {
    ResourceCollectionImpl result = resource.getCollection("Instances",
            request);

    if (result == null) return null;
    return new InstanceCollectionImpl(result);
}
 
Example #24
Source File: MockAmazonEc2Client.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@Override
public DescribeInstancesResult describeInstances(DescribeInstancesRequest describeInstancesRequest) throws AmazonClientException {
    if(throwDescribeInstancesError) {
        throwDescribeInstancesError = false;
        throw new AmazonClientException("testError");
    }
    return describeInstancesResult;
}
 
Example #25
Source File: AwsAutoScalingDeployUtils.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public boolean checkEc2Instance(String instanceId) {
    boolean instanceTerminated = false;
    try {
        DescribeInstancesResult result = awsEc2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId));
        List<com.amazonaws.services.ec2.model.Instance> instances = result.getReservations().stream()
                .flatMap(r -> r.getInstances().stream())
                .filter(i -> i.getInstanceId().equals(instanceId))
                .collect(Collectors.toList());
        instanceTerminated = instances.isEmpty() || instances.stream()
                .map(com.amazonaws.services.ec2.model.Instance::getState)
                .anyMatch(s -> s.getCode().equals(48));
    } catch (AmazonServiceException e) {
        log.info(e.toString(), e);
        if (e.getStatusCode() == 400) {
            instanceTerminated = true;
        }
    }

    if (instanceTerminated) {
        log.warn("Invalid instance " + instanceId + " in group " + activeConfiguration.getAutoScalingGroupId() + ". Detaching instance.");
        awsAsClient.detachInstances(new DetachInstancesRequest()
                .withAutoScalingGroupName(activeConfiguration.getAutoScalingGroupId())
                .withInstanceIds(instanceId)
                .withShouldDecrementDesiredCapacity(false));
    }
    return instanceTerminated;
}
 
Example #26
Source File: BeanstalkConnector.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Collection<String> getEnvIPs(String envName, int timeout) {
    DescribeEnvironmentResourcesRequest request = new DescribeEnvironmentResourcesRequest()
            .withEnvironmentName(envName);
    List<Instance> instances = null;
    System.out.print("Waiting for environment ips");
    while(timeout-->0){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(BeanstalkConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.print("-");
        DescribeEnvironmentResourcesResult res = beanstalkClient.describeEnvironmentResources(request);
        instances = res.getEnvironmentResources().getInstances();
        if(instances.size()==0)
            continue;
        AmazonEC2Client ec2 = new AmazonEC2Client(awsCredentials);
        ec2.setEndpoint(beanstalkEndpoint.replace("elasticbeanstalk", "ec2"));
        List<String> instanceIds = new ArrayList<String>();
        for (Instance instance : instances) {
            instanceIds.add(instance.getId());
        }
        List<String> ips = new ArrayList<String>();
        DescribeInstancesRequest desins = new DescribeInstancesRequest().withInstanceIds(instanceIds);
        DescribeInstancesResult desinres = ec2.describeInstances(desins);
        for (Reservation reservation : desinres.getReservations()) {
            for (com.amazonaws.services.ec2.model.Instance ins : reservation.getInstances()) {
                String ip = ins.getPublicIpAddress();
                if(ip!=null && ip.length()>0)
                    ips.add(ip);
            }
        }
        if(ips.size()>0)
            return ips;

    }
    return Collections.EMPTY_LIST;
}
 
Example #27
Source File: AwsTagReporter.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    log.info("AwsTagReporter thread initialized");
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    Collection<String> instanceIds = new ArrayList<>();
    for(Instance instance : instances) {
        instanceIds.add(instance.getInstanceId());
    }
    request.withInstanceIds(instanceIds);
    long startTime = System.currentTimeMillis();
    boolean instancesFound = false;
    do{
        // Wait up to 10 seconds for the instances to exist with AWS
        if(System.currentTimeMillis() > startTime + AwsTagReporter.TIMEOUT_IN_SECONDS) {
            throw new RuntimeException("Error waiting for instances to exist to add tags");
        }
        try{
            DescribeInstancesResult existingInstances = ec2Client.describeInstances(request);
            if(existingInstances.getReservations().get(0).getInstances().size() == instances.size()) {
                log.info("Correct instances were found to add tags to!");
                instancesFound = true;
            }
        } catch(Throwable t) {
            log.error("Error finding instances.  Sleeping.");
            try {
                sleep();
            } catch (InterruptedException e) {
                log.error("Error sleeping for adding tags", e);
            }
        }
    } while(!instancesFound);
    associateTags(instances);
    log.info("AwsTagReporter thread completed successfully");
}
 
Example #28
Source File: Ec2MachineConfigurator.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether a VM is started or not (which is stronger than {@link #checkVmIsKnown()}).
 * @return true if the VM is started, false otherwise
 */
private boolean checkVmIsStarted() {

	DescribeInstancesRequest dis = new DescribeInstancesRequest();
	dis.setInstanceIds(Collections.singletonList(this.machineId));

	DescribeInstancesResult disresult = this.ec2Api.describeInstances( dis );
	// Obtain availability zone (for later use, eg. volume attachment).
	// Necessary if no availability zone is specified in configuration
	// (because volumes must be attached to instances in the same availability zone).
	this.availabilityZone = disresult.getReservations().get(0).getInstances().get(0).getPlacement().getAvailabilityZone();
	return "running".equalsIgnoreCase( disresult.getReservations().get(0).getInstances().get(0).getState().getName());
}
 
Example #29
Source File: EC2InstanceManager.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * Queries instances with given Ids on AWS
 *
 * @param instanceIds   List of instance IDs
 * @return
 */
protected Collection<com.amazonaws.services.ec2.model.Instance> getEC2Instances( Collection<String> instanceIds ) {
    if( instanceIds == null || instanceIds.size() == 0 ) {
        return new ArrayList<com.amazonaws.services.ec2.model.Instance>();
    }

    Collection<com.amazonaws.services.ec2.model.Instance> instances =
            new LinkedList<com.amazonaws.services.ec2.model.Instance>();

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

    DescribeInstancesResult result = null;
    try {
        result = client.describeInstances( request );
    }
    catch ( Exception e ) {
        LOG.error( "Error while getting instance information from AWS.", e );
        return Collections.EMPTY_LIST;
    }

    for ( Reservation reservation : result.getReservations() ) {
        for ( com.amazonaws.services.ec2.model.Instance in : reservation.getInstances() ) {
            instances.add( in );
        }
    }

    return instances;
}
 
Example #30
Source File: AwsAutoScalingDeployUtils.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public boolean checkInstanceInService(String instanceId) {
    DescribeInstancesResult instancesResult = awsEc2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId));
    return instancesResult.getReservations().stream()
            .flatMap(r -> r.getInstances().stream())
            .filter(instance -> instance.getInstanceId().equals(instanceId))
            .map(this::toEc2Instance).findFirst().map(ec2Instance -> ec2Instance.isReachable(activeConfiguration.getAwsPrivateIp(), activeConfiguration.getPort(), log)).orElse(false);
}