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; }
private List<Instance> processResponse(DescribeInstancesResult response) { List<Instance> returnedInstances = new ArrayList<>(); for (Reservation reservation : response.getReservations()) { for (com.amazonaws.services.ec2.model.Instance instance : reservation.getInstances()) { // Don't show dead servers or servers not tagged as belonging to Swordfish if (instance.getState().getName().equals("terminated") || !instance.getTags().contains(new Tag().withKey("Swordfish").withValue("true"))) { continue; } Instance instanceDetails = getInstanceDetails(instance); returnedInstances.add(instanceDetails); instanceRepository.save(instanceDetails); refreshClient(instanceDetails); } } return returnedInstances; }
/** * InstanceList can list instances. */ @Test public void listsInstances() { Mockito.when( this.client.describeInstances( Mockito.any(DescribeInstancesRequest.class) ) ).thenReturn( new DescribeInstancesResult() .withReservations( Collections.singletonList(this.fakeReservation()) ) ); final List<Instance> instances = new InstanceList( "blah", this.fakeConfig(), this.provider ).get(); Assertions.assertThat(instances).hasSize(1); }
/** * InstanceList can list instances. */ @Test public void listsInstancesFromMultipleReservartions() { Mockito.when( this.client.describeInstances( Mockito.any(DescribeInstancesRequest.class) ) ).thenReturn( new DescribeInstancesResult() .withReservations( Arrays.asList( this.fakeReservation(), this.fakeReservation(), this.fakeReservation(), this.fakeReservation() ) ) ); final List<Instance> instances = new InstanceList( "blah", this.fakeConfig(), this.provider ).get(); Assertions.assertThat(instances).hasSize(4); }
public String getInstanceStateName(InstanceRequest instanceRequest, Context context) { AmazonEC2Async client = createEC2Client(); try { DescribeInstancesResult result = client .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceRequest.getInstanceId())); List<Instance> instances = result.getReservations().get(0).getInstances(); if (instances.size() != 1) { throw new RuntimeException("instance can not be found."); } return instances.get(0).getState().getName(); } finally { client.shutdown(); } }
/** * Get the instances from AWS filtered by the instances Ids known to the local system. */ public void getRemoteInstances(EnumerationDeletionContext aws, AWSEnumerationDeletionSubStage next) { if (aws.localInstanceIds == null || aws.localInstanceIds.size() == 0) { logFine(() -> "No local records found. No states need to be fetched from the AWS" + " endpoint."); aws.subStage = next; deleteResourcesInLocalSystem(aws); return; } DescribeInstancesRequest request = new DescribeInstancesRequest(); Filter runningInstanceFilter = getAWSNonTerminatedInstancesFilter(); request.getFilters().add(runningInstanceFilter); // Get only the instances from the remote system for which a compute state exists in the // local system. logFine(() -> String.format("Fetching instance details for %d instances on the AWS" + " endpoint.", aws.localInstanceIds.keySet().size())); request.getInstanceIds().addAll(new ArrayList<>(aws.localInstanceIds.keySet())); AsyncHandler<DescribeInstancesRequest, DescribeInstancesResult> resultHandler = new AWSEnumerationAsyncHandler(this, aws, next); aws.amazonEC2Client.describeInstancesAsync(request, resultHandler); }
@Override public void onSuccess(DescribeInstancesRequest request, DescribeInstancesResult result) { OperationContext.restoreOperationContext(this.opContext); int totalNumberOfInstances = 0; // Print the details of the instances discovered on the AWS endpoint for (Reservation r : result.getReservations()) { for (Instance i : r.getInstances()) { ++totalNumberOfInstances; final int finalTotal1 = totalNumberOfInstances; this.service.logFine(() -> String.format("%d=====Instance details %s =====", finalTotal1, i.getInstanceId())); this.aws.remoteInstanceIds.add(i.getInstanceId()); } } final int finalTotal2 = totalNumberOfInstances; this.service.logFine(() -> String.format("Successfully enumerated %d instances on the" + " AWS host.", finalTotal2)); this.aws.subStage = this.next; ((AWSEnumerationAndDeletionAdapterService) this.service) .deleteResourcesInLocalSystem(this.aws); return; }
/** * Method to get Instance details directly from Amazon * * @throws Throwable */ public static List<Instance> getAwsInstancesByIds(AmazonEC2AsyncClient client, VerificationHost host, List<String> instanceIds) throws Throwable { host.log("Getting instances with ids " + instanceIds + " from the AWS endpoint using the EC2 client."); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest() .withInstanceIds(instanceIds); DescribeInstancesResult describeInstancesResult = client .describeInstances(describeInstancesRequest); return describeInstancesResult.getReservations().stream() .flatMap(r -> r.getInstances().stream()).collect(Collectors.toList()); }
/** * For a given AutoScaling group logical id, get the public dns names associated with each instance. * * @param logicalId AutoScaling group logical id * @return List of public dns names */ public List<String> getPublicDnsForAutoScalingGroup(final String logicalId) { final List<String> instanceIds = Lists.newLinkedList(); final Optional<AutoScalingGroup> autoScalingGroup = describeAutoScalingGroup(logicalId); final List<String> publicDnsNames = Lists.newLinkedList(); if (autoScalingGroup.isPresent()) { autoScalingGroup.get() .getInstances().stream().forEach(instance -> instanceIds.add(instance.getInstanceId())); final DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest() .withInstanceIds(instanceIds); final DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest); describeInstancesResult.getReservations().forEach(reservation -> reservation.getInstances().stream().forEach(instance -> publicDnsNames.add(instance.getPublicDnsName())) ); } return publicDnsNames; }
/** * Gets all EC2 instances with the given tag key/value pair * @param tagKey - Key of the tag * @param tagValue - Value of the tag * @param filters - Array of EC2 filters * @return - List of instances with the given tag */ public List<Instance> getInstancesByTag(final String tagKey, final String tagValue, final Filter... filters) { final String filterName = String.format(FILTER_NAME_TEMPL_FOR_EC2_TAGS, tagKey); final Filter tagFilter = new Filter().withName(filterName).withValues(tagValue); final Set<Filter> filterSet = Sets.newHashSet(filters); filterSet.add(tagFilter); final DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(filterSet); DescribeInstancesResult result = ec2Client.describeInstances(request); List<Instance> instances = Lists.newArrayList(); result.getReservations().forEach(reservation -> { instances.addAll(reservation.getInstances()); }); return instances; }
@Test public void testGetInstancesByTagHappy() { String tagKey = "tag key"; String tagValue = "tag value"; Filter filter = new Filter().withName(INSTANCE_STATE_FILTER_NAME).withValues(INSTANCE_STATE_RUNNING_FILTER_VALUE); Instance instance = mock(Instance.class); when(ec2Client.describeInstances(new DescribeInstancesRequest() .withFilters( filter, new Filter() .withName(String.format(FILTER_NAME_TEMPL_FOR_EC2_TAGS, tagKey)) .withValues(tagValue) ) )).thenReturn( new DescribeInstancesResult() .withReservations( new Reservation() .withInstances(instance)) ); List<Instance> instances = ec2Service.getInstancesByTag(tagKey, tagValue, filter); assertTrue(instances.contains(instance)); }
private void describeInstances(AmazonEC2Client ec2Client, Exchange exchange) { Collection instanceIds; DescribeInstancesRequest request = new DescribeInstancesRequest(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS))) { instanceIds = exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS, Collection.class); request.withInstanceIds(instanceIds); } DescribeInstancesResult result; try { result = ec2Client.describeInstances(request); } catch (AmazonServiceException ase) { LOG.trace("Describe Instances command returned the error code {}", ase.getErrorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); }
/** * Iterates through the instances in the specified {@code DescribeInstancesResult} * and calls the specified handler on each instance. This method will retrieve the * follow-on {@code DescribeInstanceResult}s if the result holds a {@code nextToken}. * * @param result the {@code DescribeInstancesResult} * @param instanceHandler the instance handler */ @VisibleForTesting void forEachInstance(DescribeInstancesResult result, InstanceHandler instanceHandler) { List<Reservation> reservations; while (!(reservations = result.getReservations()).isEmpty()) { for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) { LOG.debug("Calling instance handler with instance {}", instance); instanceHandler.handle(instance); } } if (result.getNextToken() != null) { result = client.describeInstances( new DescribeInstancesRequest().withNextToken(result.getNextToken())); } else { break; } } }
/** * * @{inheritDoc */ @Override public List<VMInformation> describeInstances(String... instanceIds) { List<VMInformation> result = new ArrayList<VMInformation>(); try { DescribeInstancesResult results = asynchEc2Client.describeInstances(); HashSet<String> ids = new HashSet<String>(Arrays.asList(instanceIds)); for (Reservation reservationDescription : results.getReservations()) { for (com.amazonaws.services.ec2.model.Instance instance : reservationDescription.getInstances()) { if (ids.contains(instance.getInstanceId())) { result.add(new AmazonDataConverter().instanceToVmInformation(reservationDescription, instance, vmRegion)); } } // result.addAll(TypicaDataConverter.processReservationDescription(reservationDescription)); } } catch (Exception e) { LOG.error("Failed to retrieve instance from Amazon: " + e.getMessage()); throw new RuntimeException(e); } return result; }
/** * @{inheritDoc */ @Override public List<VMInformation> findInstancesOfType(VMRegion region, VMImageType type) { List<VMInformation> ret = new ArrayList<VMInformation>(); try { DescribeInstancesResult instances = asynchEc2Client.describeInstances(); InstanceDescription instanceForRegionAndType = new TankConfig().getVmManagerConfig().getInstanceForRegionAndType(region, type); for (Reservation res : instances.getReservations()) { if (res.getInstances() != null) { for (com.amazonaws.services.ec2.model.Instance inst : res.getInstances()) { if ((inst.getState().getName().equalsIgnoreCase("running") || inst.getState().getName().equalsIgnoreCase("pending")) && inst.getImageId().equals(instanceForRegionAndType.getAmi())) { ret.add(new AmazonDataConverter().instanceToVmInformation(res, inst, region)); } } } } } catch (Exception e) { LOG.error("Error getting instances: " + e.toString(), e); throw new RuntimeException(e); } return ret; }
/** * @{inheritDoc */ private List<VMInformation> findAllInstancesOfType(VMRegion region, VMImageType type) { List<VMInformation> ret = new ArrayList<VMInformation>(); try { DescribeInstancesResult instances = asynchEc2Client.describeInstances(); InstanceDescription instanceForRegionAndType = new TankConfig().getVmManagerConfig().getInstanceForRegionAndType(region, type); for (Reservation res : instances.getReservations()) { if (res.getInstances() != null) { for (com.amazonaws.services.ec2.model.Instance inst : res.getInstances()) { if (inst.getImageId().equals(instanceForRegionAndType.getAmi())) { ret.add(new AmazonDataConverter().instanceToVmInformation(res, inst, region)); } } } } } catch (Exception e) { LOG.error("Error getting instances: " + e.toString(), e); throw new RuntimeException(e); } return ret; }
public List<String> getAllRunningInstances() { logger.info("Get running instances request"); DescribeInstancesRequest request = new DescribeInstancesRequest(); List<String> valuesT1 = new ArrayList<String>(); valuesT1.add(_defaultTag); Filter filter1 = new Filter("tag:" + _tagKey, valuesT1); List<String> valuesT2 = new ArrayList<String>(); valuesT2.add("running"); valuesT2.add("pending"); Filter filter2 = new Filter("instance-state-name",valuesT2); DescribeInstancesResult result = _ec2.describeInstances(request.withFilters(filter1,filter2)); List<Reservation> reservations = result.getReservations(); List<String> instancesID = new ArrayList<String>(); for (Reservation reservation : reservations) { List<Instance> instances = reservation.getInstances(); for (Instance instance : instances) { instancesID.add(instance.getInstanceId()); } } return instancesID; }
/** * Search Ec2 Instance by Name tag. * * @param ec2 * @param targetName * Search Keyword for Name tag * @return Instance with Name tag equals targetName. If it does't found, * then return null. */ public static Instance findInstanceByName(AmazonEC2 ec2, String targetName) { DescribeInstancesResult instanceResult = ec2.describeInstances(); List<Reservation> reservations = instanceResult.getReservations(); for (Reservation reservation : reservations) { List<Instance> instances = reservation.getInstances(); for (Instance instance : instances) { List<Tag> tagList = instance.getTags(); String name = ""; for (Tag tag : tagList) { String tagKey = tag.getKey(); String tagValue = tag.getValue(); if (tagKey.contains("Name")) { name = tagValue; if (targetName.equals(name)) { return instance; } break; } } } } return null; }
public static String getIp(String id) { if (id == null) { return null; } com.amazonaws.services.ec2.AmazonEC2 client = AmazonEC2.connect(); DescribeInstancesRequest instanceReq = new DescribeInstancesRequest(); List<String> instanceIds = new ArrayList<String>(); instanceIds.add(id); instanceReq.setInstanceIds(instanceIds); DescribeInstancesResult instanceRes = client .describeInstances(instanceReq); String ip = null; try { ip = instanceRes.getReservations().get(0).getInstances().get(0) .getPublicIpAddress(); } catch (Exception e) { logger.error("Error while getting the IP.", e); } return ip; }
@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 AmazonEC2Client 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); }
public List<ServerEnvironment> getEnvironmentsByTag(Region region, String searchTag) { LOGGER.info("getEnvironmentsByTag " + region + " tag: " + searchTag); List<ServerEnvironment> environments = new ArrayList<ServerEnvironment>(); ec2.setRegion(region); DescribeInstancesResult instances = ec2.describeInstances(); for (Reservation reservation : instances.getReservations()) { for (Instance instance : reservation.getInstances()) { for (Tag tag : instance.getTags()) { if (tag.getValue().equalsIgnoreCase(searchTag)) { environments.add(getEnvironmentFromInstance(instance)); } } } } return environments; }
@Override public boolean tagEnvironmentWithVersion(Region region, DeployJobVariables jobVariables) { String searchTag = jobVariables.getEnvironment(); String version = jobVariables.getVersion(); LOGGER.info("tagEnvironmentWithVersion " + region + " Tag " + searchTag + " version " + version); boolean environmentSuccessfulTagged = false; ec2.setRegion(region); DescribeInstancesResult instances = ec2.describeInstances(); for (Reservation reservation : instances.getReservations()) { for (Instance instance : reservation.getInstances()) { for (Tag tag : instance.getTags()) { if (tag.getValue().equalsIgnoreCase(searchTag)) { CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag(VERSION_TAG, version)); LOGGER.info("Create Tag " + version + " for instance " + instance.getInstanceId()); ec2.createTags(createTagsRequest); environmentSuccessfulTagged = true; } } } } return environmentSuccessfulTagged; }
private Instances describeInstances(DescribeInstancesRequest request) { final Instances instances = new Instances(); DescribeInstancesResult result = ec2_.describeInstances(request); for (Reservation reservation : result.getReservations()) { for (Instance instance : reservation.getInstances()) { instances.addInstance(toExcaliburInstance(instance, null)); } } return instances; }
/*** * 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; }
@Override public List<Instance> call() { List<Instance> instances = new ArrayList<>(); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.withInstanceIds(this.instanceIds); request.withFilters(this.filters); // paginate through result as long as there is another response token boolean moreResults = false; do { DescribeInstancesResult result = getClient().getApi().describeInstances(request); instances.addAll(instances(result)); moreResults = result.getNextToken() != null && !result.getNextToken().equals(""); request.setNextToken(result.getNextToken()); } while (moreResults); return instances; }
@Test public void testTagsAssociated() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); Collection<Instance> instances = Arrays.asList(new Instance()); DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult(); Reservation reservation = new Reservation(); describeInstancesResult.setReservations(Arrays.asList(reservation)); reservation.setInstances(instances); client.setDescribeInstances(describeInstancesResult); Properties properties = new Properties(); properties.setProperty("tagAccounting","key,value"); properties.setProperty("function_tag","foo2"); properties.setProperty("product_tag","foo3"); AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties); reporter.run(); }
@Test public void testExceptionCaught() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); Collection<Instance> instances = Arrays.asList(new Instance()); DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult(); Reservation reservation = new Reservation(); describeInstancesResult.setReservations(Arrays.asList(reservation)); reservation.setInstances(instances); client.setDescribeInstances(describeInstancesResult); Properties properties = new Properties(); properties.setProperty("tagAccounting","key"); properties.setProperty("function_tag","foo2"); properties.setProperty("product_tag","foo3"); AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties); reporter.run(); }
@Test public void testClientThrowsErrors() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); client.setDescribeInstancesToThrowError(); Collection<Instance> instances = Arrays.asList(new Instance()); DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult(); Reservation reservation = new Reservation(); describeInstancesResult.setReservations(Arrays.asList(reservation)); reservation.setInstances(instances); client.setDescribeInstances(describeInstancesResult); Properties properties = new Properties(); properties.setProperty("accounting_tag","foo"); properties.setProperty("function_tag","foo2"); properties.setProperty("product_tag","foo3"); AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties) { @Override void sleep() throws InterruptedException { // do nothing } }; reporter.run(); }
@Test public void testSleepThrowsErrors() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); client.setDescribeInstancesToThrowError(); Collection<Instance> instances = Arrays.asList(new Instance()); DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult(); Reservation reservation = new Reservation(); describeInstancesResult.setReservations(Arrays.asList(reservation)); reservation.setInstances(instances); client.setDescribeInstances(describeInstancesResult); Properties properties = new Properties(); properties.setProperty("accounting_tag","foo"); properties.setProperty("function_tag","foo2"); properties.setProperty("product_tag","foo3"); AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties) { @Override void sleep() throws InterruptedException { throw new InterruptedException(); } }; reporter.run(); }
@Test() public void testThreadTimesOut() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); Collection<Instance> instances = Arrays.asList(new Instance()); DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult(); Reservation reservation = new Reservation(); describeInstancesResult.setReservations(Arrays.asList(reservation)); // Make count mismatch reservation.setInstances(Arrays.asList(new Instance(),new Instance())); client.setDescribeInstances(describeInstancesResult); Properties properties = new Properties(); properties.setProperty("accounting_tag","foo"); properties.setProperty("function_tag","foo2"); properties.setProperty("product_tag","foo3"); AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties); AwsTagReporter.TIMEOUT_IN_SECONDS = 1; try{ reporter.run(); } catch(RuntimeException e) { Assert.assertEquals("Error waiting for instances to exist to add tags",e.getMessage()); return; } Assert.fail("Exception should have been thrown since tags were never filed"); }
@Override public List<CloudVmInstanceStatus> check(AuthenticatedContext ac, List<CloudInstance> vms) { List<CloudVmInstanceStatus> cloudVmInstanceStatuses = new ArrayList<>(); for (CloudInstance vm : vms) { DescribeInstancesResult result = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()), ac.getCloudContext().getLocation().getRegion().value()) .describeInstances(new DescribeInstancesRequest().withInstanceIds(vm.getInstanceId())); for (Reservation reservation : result.getReservations()) { for (Instance instance : reservation.getInstances()) { if ("Stopped".equalsIgnoreCase(instance.getState().getName())) { LOGGER.info("AWS instance is in Stopped state, polling stack."); cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.STOPPED)); } else if ("Running".equalsIgnoreCase(instance.getState().getName())) { LOGGER.info("AWS instance is in Started state, polling stack."); cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.STARTED)); } else if ("Terminated".equalsIgnoreCase(instance.getState().getName())) { LOGGER.info("AWS instance is in Terminated state, polling stack."); cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.TERMINATED)); } else { cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.IN_PROGRESS)); } } } } return cloudVmInstanceStatuses; }
protected static void checkTagsAws(Regions region, List<String> instanceIdList, Map<String, String> tagsToCheckMap) { Map<String, String> extractedTagsToCheck = new HashMap<>(); List<Tag> extractedTags; AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).build(); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); describeInstancesRequest.withInstanceIds(instanceIdList); DescribeInstancesResult describeInstancesResultAll = ec2.describeInstances(describeInstancesRequest); List<Reservation> reservationsAll = describeInstancesResultAll.getReservations(); for (Reservation reservation : reservationsAll) { for (Instance instance : reservation.getInstances()) { extractedTags = instance.getTags(); Assert.assertNotNull(extractedTags); for (Tag tag : extractedTags) { extractedTagsToCheck.put(tag.getKey(), tag.getValue()); } checkTags(tagsToCheckMap, extractedTagsToCheck); extractedTags.clear(); } } }
private Instance getEc2Instance(IMachine machine, AmazonEC2 connector) throws ConnectorException { DescribeInstancesResult describeInstancesResult = null; try { DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); describeInstancesResult = connector.describeInstances(describeInstancesRequest.withInstanceIds(machine.getName())); List<Reservation> reservations = describeInstancesResult.getReservations(); if (reservations.size() == 0) { // machine not found MUST have been terminated return null; } // always it will be in the first reservation as the query is on // only one machine List<Instance> instances = reservations.get(0).getInstances(); for (Instance instance : instances) { if (instance.getInstanceId().equals(machine.getName())) { // found the machine return instance; } } } catch (Exception e) { throw new ConnectorException(e); } return null; }
@Override public List<AbstractResource<?>> describeReservations(Account account, Region region, DateTime dt, Ec2Filter... filters) { AmazonEC2 ec2 = findClient(account, region); DescribeInstancesRequest req = new DescribeInstancesRequest(); for (Ec2Filter filter : filters) { Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues()); req.withFilters(f); } log.debug("start describing instances for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region); DescribeInstancesResult res = ec2.describeInstances(req); List<Map<String, Ec2InstanceAttribute>> attributes = new ArrayList<>(); for (Reservation r : res.getReservations()) { Map<String, Ec2InstanceAttribute> attribute = new HashMap<>(); for (Instance i : r.getInstances()) { Boolean terminationProtection = findTerminationProtection(account, region, i.getInstanceId()); String shutdownBehavior = findShutdownBehavior(account, region, i.getInstanceId()); String userData = findUserData(account, region, i.getInstanceId()); Ec2InstanceAttribute ia = new Ec2InstanceAttribute(terminationProtection, shutdownBehavior, userData); attribute.put(i.getInstanceId(), ia); } attributes.add(attribute); } return converter.toEc2Reservations(res.getReservations(), attributes, account.getId(), region, dt); }
/** * Describe instances. * * @param instanceIds instances' IDs * @param enableLogging log to standard out * @return list of instances */ protected final List<Instance> describeInstances( final Collection<String> instanceIds, final boolean enableLogging) { if (enableLogging) { log.info("Describe instances:" + toString(instanceIds)); } DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(instanceIds); DescribeInstancesResult result = amazonEC2Client .describeInstances(request); Assert.assertTrue(result.getReservations().size() > 0); List<Instance> instanceList = new ArrayList<Instance>(); for (Reservation reservation : result.getReservations()) { List<Instance> instances = reservation.getInstances(); if (null != instances) { for (Instance i : instances) { instanceList.add(i); } } } return instanceList; }
/** * 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; }
/** * @inheritDoc */ @Override public WorkerInstance describeInstance( String instanceId, Identity identity ) { AmazonEC2 ec2 = ActivityUtils.createClient( AmazonEC2Client.class, identity ); DescribeInstancesResult result = ec2.describeInstances( new DescribeInstancesRequest().withInstanceIds( instanceId ) ); if ( result.getReservations().isEmpty() ) { return null; } Reservation resv = result.getReservations().get( 0 ); if ( resv.getInstances().isEmpty() ) { return null; } Instance ins = resv.getInstances().get( 0 ); WorkerInstance wi = new WorkerInstance(); wi.setInstanceId( ins.getInstanceId() ); wi.setInstanceStatus( ins.getState().getName() ); wi.setPublicIpAddress( ins.getPublicIpAddress() ); return wi; }
private List<Instance> getInstances() { final List<Instance> all_instances = new ArrayList<>(); final DescribeInstancesRequest request = new DescribeInstancesRequest(); final DescribeInstancesResult result = ec2_client.describeInstances(request); final List<Reservation> reservations = result.getReservations(); for (Reservation reservation : reservations) { List<Instance> instances = reservation.getInstances(); all_instances.addAll(instances); } return all_instances; }
public String getPublicDNS(String 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) { return instances.iterator().next().getPublicDnsName(); } } return null; }