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<Server> convertInstanceToServer(List<Instance> instances) { List<Server> servers = new ArrayList<>(); for (Instance instance : instances) { Server server = new Server(instance.getInstanceId()); for (Tag tag : instance.getTags()) { if (tag != null && tag.getKey() != null && tag.getKey().equals("Name")) { server.setName(tag.getValue()); } } server.setStatus(instance.getState().getName()); server.setType(instance.getInstanceType()); server.setPublicIP(Arrays.asList(instance.getPublicIpAddress())); server.setPrivateIP(Arrays.asList(instance.getPrivateIpAddress())); servers.add(server); } return servers; }
@Override public Map<AvailabilityZone, List<Instance>> getInstancesMapForZone( AvailabilityZone zone, AmazonEC2Client client) throws Exception { OperationStats op = new OperationStats("ec2InstanceStore", "getInstancesMapForZone"); try { Map<AvailabilityZone, List<Instance>> ret = new HashMap<>(); ret.put(zone, getInstancesForZone(zone, client)); op.succeed(); return ret; } catch (Exception e) { op.failed(); logger.error(ExceptionUtils.getRootCauseMessage(e)); throw e; } }
protected HashMap getAwsInstanceProperties(Instance awsInstance) throws Exception { HashMap map = mapper.readValue(mapper.writeValueAsString(awsInstance), HashMap.class); if (awsInstance.getMonitoring() != null && awsInstance.getMonitoring().getState() != null) { //Have to comply with the current AWS_V1 schema map.put("monitoring", awsInstance.getMonitoring().getState().toString()); } if (awsInstance.getPlacement() != null && awsInstance.getPlacement().getAvailabilityZone() != null) { //Be backward compatible for tools Map placement = (Map) map.get("placement"); if (placement != null) { placement.put("availability_zone", awsInstance.getPlacement().getAvailabilityZone()); } } return map; }
private Boolean calculateDailyInstanceCounts() { try { DateTime utcNow = DateTime.now(DateTimeZone.UTC); List<Instance> instances = cloudInstanceStore.getInstances(region); List<ReservedInstances> reservedInstances = cloudInstanceStore.getReservedInstances(region); // Generate instance counts per type per Availability zone List<EsInstanceCountRecord> instanceCountRecords = getInstanceCountRecords(instances, reservedInstances, utcNow); logger.info("Number of instance count records {}", instanceCountRecords.size()); // Insert records into soundwave store. instanceCounterStore.bulkInsert(instanceCountRecords); logger.info("Bulk insert succeeded for instance count records"); return true; } catch (Exception e) { logger.error(ExceptionUtils.getRootCauseMessage(e)); return false; } }
private void logReconcileStats(Collection<Instance> ec2Instances, Collection<EsInstance> cmdbInstances) { int ec2RunningCount = 0; for (Instance inst : ec2Instances) { if (inst.getState().getCode() == 16) { //EC2 API may return some terminated instances. Only get the running count ec2RunningCount++; } } Stats.setGauge(StatsUtil.getStatsName("awsreconcile", "ec2TotalRunningCount"), ec2RunningCount); Stats.setGauge(StatsUtil.getStatsName("awsreconcile", "cmdbTotalRunningCount"), cmdbInstances.size()); Stats.setGauge(StatsUtil.getStatsName("awsreconcile", "diffcount"), Math.abs(ec2RunningCount - cmdbInstances.size())); int serviceMappingMissingCount = 0; for (EsInstance instance : cmdbInstances) { /*if (instance.getServiceMappings() == null || instance.getServiceMappings().length == 0) { serviceMappingMissingCount++; }*/ } Stats.setGauge(StatsUtil.getStatsName("awsreconcile", "servicemappingmissingcount"), serviceMappingMissingCount); }
/** * Return a list of tags that need to be updated to the Ec2Instance. * The tags are either not in Ec2Instance tags or having different * values * @param ec2Instance * @param esInstance * @return A list of tags */ public List<Tag> getUpdateTags(Instance ec2Instance, EsInstance esInstance) { Preconditions.checkNotNull(ec2Instance); Preconditions.checkNotNull(esInstance); List<Tag> updateTags = new ArrayList<>(); List<Tag> currentEc2Tag = ec2Instance.getTags(); List<Tag> esUploadTags = getUpdateTags(esInstance); for (Tag tag : esUploadTags) { boolean shouldUpdate = true; for (Tag ec2Tag : currentEc2Tag) { if (ec2Tag.getKey().equals(tag.getKey()) && ec2Tag.getValue().equals(tag.getValue())) { shouldUpdate = false; break; } } if (shouldUpdate) { updateTags.add(tag); } } return updateTags; }
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(); } }
private void runSearch(T type) { AmazonWebServiceRequest descRequest = buildRequest(type); AsyncHandler describeHandler = buildHandler(type); if (type instanceof Instance) { this.amazonEC2Client.describeInstancesAsync( (DescribeInstancesRequest) descRequest, describeHandler); } else if (type instanceof NatGateway) { this.amazonEC2Client.describeNatGatewaysAsync( (DescribeNatGatewaysRequest) descRequest, describeHandler); } else if (type instanceof Volume) { this.amazonEC2Client.describeVolumesAsync( (DescribeVolumesRequest) descRequest, describeHandler); } else { AWSTaskStatusChecker.this.taskManager.patchTaskToFailure( new IllegalArgumentException("Invalid type " + type)); } }
@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()); }
private static void registerAWSInstancesToLoadBalancer(VerificationHost host, AmazonElasticLoadBalancingAsyncClient client, String name, List<String> instanceIds) { RegisterInstancesWithLoadBalancerRequest registerRequest = new RegisterInstancesWithLoadBalancerRequest() .withLoadBalancerName(name) .withInstances(instanceIds.stream() .map(com.amazonaws.services.elasticloadbalancing.model.Instance::new) .collect(Collectors.toList()) ); RegisterInstancesWithLoadBalancerResult result = null; try { result = client.registerInstancesWithLoadBalancer(registerRequest); } catch (Exception e) { host.log(Level.SEVERE, "Error registering instances with load balancer %s", Utils.toString(e)); } assertNotNull(result); assertFalse(result.getInstances().isEmpty()); }
@Test public void testGetComputeDescriptionKeyFromAWSInstance() throws Throwable { Map<String, ZoneData> zones = new HashMap<>(); zones.put(AWS_ZONE_ID, ZoneData.build(AWS_REGION_ID, AWS_ZONE_ID, "")); Instance awsInstance = new Instance(); awsInstance.setInstanceId(AWS_INSTANCE_ID); Placement placement = new Placement(); placement.setAvailabilityZone(AWS_ZONE_ID); awsInstance.setPlacement(placement); String regionId = getRegionId(awsInstance); awsInstance.setInstanceType(AWS_INSTANCE_TYPE); awsInstance.setVpcId(AWS_VPC_ID); assertEquals(AWS_REGION_ID, regionId); InstanceDescKey computeDescriptionKey = getKeyForComputeDescriptionFromInstance(awsInstance, zones); assertEquals(AWS_COMPUTE_DESCRIPTION_KEY, computeDescriptionKey); }
protected void assertBootDiskConfiguration(AmazonEC2AsyncClient client, Instance awsInstance, String diskLink) { DiskState diskState = getDiskState(diskLink); Volume bootVolume = getVolume(client, awsInstance, awsInstance.getRootDeviceName()); assertEquals("Boot Disk capacity in diskstate is not matching the boot disk size of the " + "vm launched in aws", diskState.capacityMBytes, bootVolume.getSize() * 1024); assertEquals( "Boot disk type in diskstate is not same as the type of the volume attached to the VM", diskState.customProperties.get("volumeType"), bootVolume.getVolumeType()); assertEquals( "Boot disk iops in diskstate is the same as the iops of the volume attached to the VM", Integer.parseInt(diskState.customProperties.get("iops")), bootVolume.getIops().intValue()); assertEquals("Boot disk attach status is not matching", DiskService.DiskStatus.ATTACHED, diskState.status); }
protected Volume getVolume(AmazonEC2AsyncClient client, Instance awsInstance, String deviceName) { InstanceBlockDeviceMapping bootDiskMapping = awsInstance.getBlockDeviceMappings().stream() .filter(blockDeviceMapping -> blockDeviceMapping.getDeviceName().equals(deviceName)) .findAny() .orElse(null); //The ami used in this test is an ebs-backed AMI assertNotNull("Device type should be ebs type", bootDiskMapping.getEbs()); String bootVolumeId = bootDiskMapping.getEbs().getVolumeId(); DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest() .withVolumeIds(bootVolumeId); DescribeVolumesResult describeVolumesResult = client .describeVolumes(describeVolumesRequest); return describeVolumesResult.getVolumes().get(0); }
public static boolean isInstanceEligible( Instance instance, String namePrefix, String nameRegex ) { boolean eligible = true; int stateCode = instance.getState().getCode().intValue(); String name = EC2Util.getTagValue( instance, "Name" ); if ( stateCode != 16 ) { eligible = false; } else if ( !namePrefix.isEmpty() && !name.startsWith( namePrefix ) ) { eligible = false; } else if ( !nameRegex.isEmpty() && !name.matches( nameRegex ) ) { eligible = false; } return eligible; }
@Override public void fetchMetrics() { try { // For each instance fetch the ec2 cloud watch metrics List<Instance> instances = EC2Util.lookupElligibleInstances( ec2Client, namePrefix, nameRegex ); for ( Instance instance : instances ) { String instanceId = instance.getInstanceId(); for ( EC2CloudWatchMetric cloudWatchMetric : ec2CloudWatchMetrics ) { cloudWatchAccessor.lookupAndSaveMetricData( cloudWatchMetric, instanceId, EC2Util.TYPE_NAME ); } } } catch ( CandlestackException e ) { LOGGER.error( "EC2MetricsFetcher encountered an error while trying to fetch metrics", e ); } }
/** * 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)); }
@Override public Collection<EC2Instance> find(final EC2InstanceTemplate template, Collection<String> virtualInstanceIds) throws InterruptedException { LOG.debug("Finding virtual instances {}", virtualInstanceIds); final Collection<EC2Instance> ec2Instances = Lists.newArrayListWithExpectedSize(virtualInstanceIds.size()); forEachInstance(virtualInstanceIds, new InstanceHandler() { @Override public void handle(Instance instance) { String virtualInstanceId = checkInstanceIsManagedByDirector(instance, template); fillMissingProperties(instance); ec2Instances.add(new EC2Instance(template, virtualInstanceId, instance)); } }); LOG.debug("Found {} instances for {} virtual instance IDs", ec2Instances.size(), virtualInstanceIds.size()); return ec2Instances; }
/** * Performs a sequence of strict instance ownership checks to avoid any potential harmful * accidents. * * @param instance the instance * @param template the template from which the instance was created, or <code>null</code> * if it is unknown (such as during a delete call) * @return the virtual instance ID * @throws IllegalStateException if the instance fails an ownership check */ private String checkInstanceIsManagedByDirector(Instance instance, EC2InstanceTemplate template) { String virtualInstanceId = getVirtualInstanceId(instance.getTags(), "instance"); String instanceIds = instance.getInstanceId() + " / " + virtualInstanceId; String instanceKeyName = instance.getKeyName(); if (template != null) { if (!template.getKeyName().equals(Optional.fromNullable(instanceKeyName))) { LOG.warn("Found unexpected key name: {} for instance: {}", instanceKeyName, instanceIds); } String instanceType = instance.getInstanceType(); if (!template.getType().equals(instanceType)) { LOG.warn("Found unexpected type: {} for instance: {}", instanceType, instanceIds); } String instanceImageId = instance.getImageId(); if (!template.getImage().equals(instanceImageId)) { LOG.warn("Found unexpected image: {} for instance: {}", instanceImageId, instanceIds); } } return virtualInstanceId; }
/** * 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; }
/** * @param data * @param instance * @param region * @return */ public VMInformation instanceToVmInformation(Reservation data, Instance instance, VMRegion region) { VMInformation info = new VMInformation(); info.setProvider(VMProvider.Amazon); info.setRequestId(data.getRequesterId()); info.setImageId(instance.getImageId()); info.setInstanceId(instance.getInstanceId()); info.setKeyName(instance.getKeyName()); // info.setLaunchTime(); info.setRegion(region); info.setPlatform(instance.getPlatform()); info.setPrivateDNS(instance.getPrivateDnsName()); info.setPublicDNS(instance.getPublicDnsName()); info.setState(instance.getState().getName()); info.setSize(instance.getInstanceType()); return info; }
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; }
private int listFailedInstances(Map<String, Instance> instances, ConcurrentHashMap<String, Integer> completedHosts) { int failedInstancesCount = instances.size() - completedHosts.size(); for (Instance instance : instances.values()) { String host = getPreferredHostName(instance); if (!completedHosts.containsKey(host)) { System.out.format("No result collected from hostname: %s%n", host); } else if (completedHosts.get(host) != 0) { System.out.format("Unsuccessful result code: %d on hostname: %s%n", completedHosts.get(host), host); failedInstancesCount++; } } System.out.format("Load generators were unsuccessful. Failed instances count: %d%n", failedInstancesCount); System.out.println(); return failedInstancesCount; }
@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; } } }
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(); } }
private Instance _describeInstance() throws AmazonClientException, InterruptedException { // Sometimes even after a successful RunInstances, DescribeInstances // returns an error for a few seconds. We do a few retries instead of // failing instantly. See [JENKINS-15319]. for (int i = 0; i < 5; i++) { try { return _describeInstanceOnce(); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) { // retry in 5 seconds. Thread.sleep(5000); continue; } throw e; } } // Last time, throw on any error. return _describeInstanceOnce(); }
public List<Instance> runInstances(RunInstancesRequest request, Tag... tags) throws Exception { logger.info("create ec2 instance, request={}", request); RunInstancesResult result = new Runner<RunInstancesResult>() .maxAttempts(3) .retryInterval(Duration.ofSeconds(20)) .retryOn(this::retryOnRunInstance) .run(() -> ec2.runInstances(request)); Threads.sleepRoughly(Duration.ofSeconds(5)); // wait little bit to make sure instance is visible to tag service List<String> instanceIds = result.getReservation().getInstances().stream().map(Instance::getInstanceId).collect(Collectors.toList()); CreateTagsRequest tagsRequest = new CreateTagsRequest() .withResources(instanceIds) .withTags(tags); createTags(tagsRequest); waitUntilRunning(instanceIds); return describeInstances(instanceIds); }
public void run() throws IOException, JSchException, SftpException, InterruptedException { List<String> commands = context.params(Param.EXECUTE_COMMAND); String script = context.param(Param.EXECUTE_SCRIPT); Asserts.isTrue(commands != null || script != null, "{} or {} is required", Param.EXECUTE_COMMAND.key, Param.EXECUTE_SCRIPT.key); String index = context.param(Param.INSTANCE_INDEX); for (int i = 0; i < remoteInstances.size(); i++) { Instance remoteInstance = remoteInstances.get(i); if (InstanceState.RUNNING.equalsTo(remoteInstance.getState()) && indexMatches(index, i)) { try (SSH ssh = new SSH(remoteInstance.getPublicDnsName(), "ubuntu", KeyPair.keyFile(remoteInstance.getKeyName(), env))) { if (commands != null) { ssh.executeCommands(commands.toArray(new String[commands.size()])); } else { executeScript(ssh, env.envDir.resolve(script)); } } } } }
private List<Instance> runningInstances(String resourceId) { Tag tag = new EC2TagHelper(env).resourceId(resourceId); DescribeTagsRequest request = new DescribeTagsRequest() .withFilters(new Filter("key").withValues(tag.getKey()), new Filter("value").withValues(tag.getValue()), new Filter("resource-type").withValues("instance")); List<TagDescription> remoteTags = AWS.ec2.describeTags(request); List<String> instanceIds = remoteTags.stream().map(TagDescription::getResourceId).collect(Collectors.toList()); if (instanceIds.isEmpty()) { com.amazonaws.services.autoscaling.model.AutoScalingGroup asGroup = AWS.as.describeASGroup(env.name + "-" + this.resourceId); if (asGroup == null) throw new Error("can not find any running instance or asGroup, id=" + this.resourceId); instanceIds = asGroup.getInstances().stream() .map(com.amazonaws.services.autoscaling.model.Instance::getInstanceId) .collect(Collectors.toList()); } logger.info("find instanceId, {} => {}", resourceId, instanceIds); List<Instance> instances = AWS.ec2.describeInstances(instanceIds) .stream().filter(instance -> "running".equals(instance.getState().getName())).collect(Collectors.toList()); if (instances.isEmpty()) throw new Error("can not find any running instance, id=" + resourceId); return instances; }
public AmazonEC2HostProvider(final AWSCredentials credentials, final ClientConfiguration configuration, String endpoint, Function<Instance, Host> instance_converter) { this.instance_converter = instance_converter; ec2_client = new AmazonEC2Client(credentials, configuration); ec2_client.setEndpoint(endpoint); next_host_index = new AtomicInteger(); }
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; }