public void createDescribeInstanceStatusResult(String instanceId, String stateName, String instanceStatusName, String systemStatusName) { InstanceState state = new InstanceState().withName(stateName); InstanceStatusSummary instanceSummary = new InstanceStatusSummary() .withStatus(instanceStatusName); InstanceStatusSummary systemSummary = new InstanceStatusSummary() .withStatus(systemStatusName); InstanceStatus instanceStatus = new com.amazonaws.services.ec2.model.InstanceStatus() .withInstanceId(instanceId).withInstanceState(state) .withInstanceStatus(instanceSummary) .withSystemStatus(systemSummary); DescribeInstanceStatusResult instanceStatusResult = new DescribeInstanceStatusResult() .withInstanceStatuses(instanceStatus); doReturn(instanceStatusResult).when(ec2).describeInstanceStatus( any(DescribeInstanceStatusRequest.class)); }
public void addDescribeInstanceStatusResult(String instanceId, String stateName, String instanceStatusName, String systemStatusName) { InstanceState state = new InstanceState().withName(stateName); InstanceStatusSummary instanceSummary = new InstanceStatusSummary() .withStatus(instanceStatusName); InstanceStatusSummary systemSummary = new InstanceStatusSummary() .withStatus(systemStatusName); com.amazonaws.services.ec2.model.InstanceStatus instanceStatus = new com.amazonaws.services.ec2.model.InstanceStatus() .withInstanceId(instanceId).withInstanceState(state) .withInstanceStatus(instanceSummary) .withSystemStatus(systemSummary); DescribeInstanceStatusResult instanceStatusResult = new DescribeInstanceStatusResult() .withInstanceStatuses(instanceStatus); answerDescribeInstanceStatus.add(instanceStatusResult); }
@Override public StartInstancesResult startInstances(StartInstancesRequest startInstancesRequest) { StartInstancesResult result = new StartInstancesResult(); if (startInstancesRequest.getInstanceIds().get(0).equals("test-1")) { Collection<InstanceStateChange> coll = new ArrayList<InstanceStateChange>(); InstanceStateChange sc = new InstanceStateChange(); InstanceState previousState = new InstanceState(); previousState.setCode(80); previousState.setName(InstanceStateName.Stopped); InstanceState newState = new InstanceState(); newState.setCode(16); newState.setName(InstanceStateName.Running); sc.setPreviousState(previousState); sc.setCurrentState(newState); sc.setInstanceId("test-1"); coll.add(sc); result.setStartingInstances(coll); } else { throw new AmazonServiceException("The image-id doesn't exists"); } return result; }
@Override public StopInstancesResult stopInstances(StopInstancesRequest stopInstancesRequest) { StopInstancesResult result = new StopInstancesResult(); if (stopInstancesRequest.getInstanceIds().get(0).equals("test-1")) { Collection<InstanceStateChange> coll = new ArrayList<InstanceStateChange>(); InstanceStateChange sc = new InstanceStateChange(); InstanceState previousState = new InstanceState(); previousState.setCode(80); previousState.setName(InstanceStateName.Running); InstanceState newState = new InstanceState(); newState.setCode(16); newState.setName(InstanceStateName.Stopped); sc.setPreviousState(previousState); sc.setCurrentState(newState); sc.setInstanceId("test-1"); coll.add(sc); result.setStoppingInstances(coll); } else { throw new AmazonServiceException("The image-id doesn't exists"); } return result; }
@Override public TerminateInstancesResult terminateInstances(TerminateInstancesRequest terminateInstancesRequest) { TerminateInstancesResult result = new TerminateInstancesResult(); if (terminateInstancesRequest.getInstanceIds().contains("test-1")) { Collection<InstanceStateChange> coll = new ArrayList<InstanceStateChange>(); InstanceStateChange sc = new InstanceStateChange(); InstanceState previousState = new InstanceState(); previousState.setCode(80); previousState.setName(InstanceStateName.Running); InstanceState newState = new InstanceState(); newState.setCode(16); newState.setName(InstanceStateName.Terminated); sc.setPreviousState(previousState); sc.setCurrentState(newState); sc.setInstanceId("test-1"); coll.add(sc); result.setTerminatingInstances(coll); } else { throw new AmazonServiceException("The image-id doesn't exists"); } return result; }
@Test public void itShouldStartAnEC2InstanceFromAnAMI() throws ServiceBrokerException { when( ec2Client.runInstances(awsRqst(r -> r.getImageId().equals( "test_image")))).thenReturn(runInstanceResult); when(ec2Client.describeAddresses()).thenReturn( new DescribeAddressesResult().withAddresses(Collections .singleton(new Address().withPublicIp("10.10.10.10")))); when(ec2Client.describeInstanceStatus(any())).thenReturn( new DescribeInstanceStatusResult() .withInstanceStatuses(Collections .singleton(new InstanceStatus() .withInstanceState(new InstanceState() .withName("running"))))); when(hostUtils.waitForBoot(anyString(), anyInt())).thenReturn(true); assertThat(aws.startEC2Instance("test_image"), is(equalTo("test_instance"))); }
@Test public void testStartInstance() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Stopped))); final StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(INSTANCE_ID); final StartInstancesResult startInstancesResult = new StartInstancesResult().withStartingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Running))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); Mockito.doReturn(startInstancesResult).when(amazonEC2Client).startInstances(startInstancesRequest); amazonEC2Service.startInstance(INSTANCE_ID); final InOrder inOrder = Mockito.inOrder(amazonEC2Client); inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); inOrder.verify(amazonEC2Client).startInstances(startInstancesRequest); }
@Test public void testStopInstanceStopping() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running))); final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(INSTANCE_ID); final StopInstancesResult stopInstancesResult = new StopInstancesResult().withStoppingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Stopping))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); Mockito.doReturn(stopInstancesResult).when(amazonEC2Client).stopInstances(stopInstancesRequest); amazonEC2Service.stopInstance(INSTANCE_ID); final InOrder inOrder = Mockito.inOrder(amazonEC2Client); inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); inOrder.verify(amazonEC2Client).stopInstances(stopInstancesRequest); }
@Test public void testStopInstanceStopped() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running))); final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(INSTANCE_ID); final StopInstancesResult stopInstancesResult = new StopInstancesResult().withStoppingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Stopped))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); Mockito.doReturn(stopInstancesResult).when(amazonEC2Client).stopInstances(stopInstancesRequest); amazonEC2Service.stopInstance(INSTANCE_ID); final InOrder inOrder = Mockito.inOrder(amazonEC2Client); inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); inOrder.verify(amazonEC2Client).stopInstances(stopInstancesRequest); }
@Override protected InstanceStateChange convertObject(TerminatingInstanceDescription from) { InstanceStateChange to = new InstanceStateChange(); to.setInstanceId(from.getInstanceId()); InstanceState previousState = new InstanceState(); previousState.setCode(from.getPreviousStateCode()); previousState.setName(from.getPreviousState()); to.setPreviousState(previousState); InstanceState currentState = new InstanceState(); currentState.setCode(from.getShutdownStateCode()); currentState.setName(from.getShutdownState()); to.setCurrentState(currentState); return to; }
/** * Convert an {@link InstanceState} to a {@link MachineState}. * * @see com.google.common.base.Function#apply(java.lang.Object) */ @Override public MachineState apply(InstanceState state) { switch (state.getName()) { case "pending": return MachineState.PENDING; case "running": return MachineState.RUNNING; case "shutting-down": return MachineState.TERMINATING; case "terminated": return MachineState.TERMINATED; case "stopping": return MachineState.TERMINATING; case "stopped": return MachineState.TERMINATED; default: throw new IllegalArgumentException( String.format("failed to translate unrecognized instance state '%s'", state.getName())); } }
@Override public List<Instance> launchInstances(Ec2ProvisioningTemplate provisioningDetails, int count) throws AmazonClientException { List<Instance> launchedInstances = new ArrayList<>(); for (int i = 0; i < count; i++) { int idNum = ++this.idSequencer; Instance newInstance = new Instance().withInstanceId("i-" + idNum) .withState(new InstanceState().withName("pending")).withPublicIpAddress("1.2.3." + idNum) .withImageId(provisioningDetails.getAmiId()) .withInstanceType(provisioningDetails.getInstanceType()); for (Entry<String, String> tagItem : provisioningDetails.getTags().entrySet()) { newInstance.withTags(new Tag(tagItem.getKey(), tagItem.getValue())); } this.instances.add(newInstance); launchedInstances.add(newInstance); } return launchedInstances; }
@Override public List<Instance> launchInstances(Ec2ProvisioningTemplate template, int count) throws AmazonClientException { List<Instance> launchedInstances = new ArrayList<>(); for (int i = 0; i < count; i++) { int idNum = ++this.idSequencer; String id = "i-" + idNum; LOG.info("launching instance {} into fake account ...", id); Instance newInstance = new Instance().withInstanceId(id).withState(new InstanceState().withName("pending")) .withPublicIpAddress("1.2.3." + idNum).withImageId(template.getAmiId()) .withInstanceType(template.getInstanceType()); if (!template.getTags().isEmpty()) { List<Tag> tags = new ArrayList<>(); for (Entry<String, String> tag : template.getTags().entrySet()) { tags.add(new Tag(tag.getKey(), tag.getValue())); } newInstance.withTags(tags); } this.instances.put(newInstance.getInstanceId(), newInstance); launchedInstances.add(newInstance); } return launchedInstances; }
@Override public TerminateInstancesResult terminateInstances(List<String> instanceIds) throws NotFoundException, AmazonClientException { TerminateInstancesResult result = new TerminateInstancesResult(); for (String instanceId : instanceIds) { if (!this.instances.containsKey(instanceId)) { throw new AmazonServiceException(String.format( "The instance ID '%s' does not exist " + "(Service: AmazonEC2; Status Code: 400; Error Code: " + "InvalidInstanceID.NotFound;" + " Request ID: 12a2ebaf-c480-4998-95fb-6d47b4393e00)", instanceId)); } this.instances.remove(instanceId); result.withTerminatingInstances(new InstanceStateChange().withInstanceId(instanceId) .withCurrentState(new InstanceState().withName(InstanceStateName.ShuttingDown))); } return result; }
@Test public void convertCompleteInstance() { DateTime launchTime = UtcTime.now(); Instance instance = new Instance().withInstanceId("i-1") .withState(new InstanceState().withName(InstanceStateName.Running)).withPublicIpAddress("1.2.3.4") .withPrivateIpAddress("1.2.3.5").withInstanceType(InstanceType.M1Small) .withLaunchTime(launchTime.toDate()) .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen) .withPlacement(new Placement("us-east-1c")); Machine machine = convert(instance); assertThat(machine.getId(), is(instance.getInstanceId())); assertThat(machine.getLaunchTime(), is(launchTime)); assertThat(machine.getMachineState(), is(MachineState.RUNNING)); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.small")); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps().size(), is(1)); assertThat(machine.getPublicIps().get(0), is(instance.getPublicIpAddress())); assertThat(machine.getPrivateIps().size(), is(1)); assertThat(machine.getPrivateIps().get(0), is(instance.getPrivateIpAddress())); assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance))); }
@Test public void convertInstanceMissingPublicIp() { DateTime launchTime = UtcTime.now(); Instance instance = new Instance().withInstanceId("i-1") .withState(new InstanceState().withName(InstanceStateName.Running)).withPrivateIpAddress("1.2.3.5") .withInstanceType(InstanceType.M1Small).withLaunchTime(launchTime.toDate()) .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen) .withPlacement(new Placement("us-east-1a")); Machine machine = convert(instance); assertThat(machine.getId(), is(instance.getInstanceId())); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.small")); assertThat(machine.getLaunchTime(), is(launchTime)); assertThat(machine.getMachineState(), is(MachineState.RUNNING)); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps().size(), is(0)); assertThat(machine.getPrivateIps().size(), is(1)); assertThat(machine.getPrivateIps().get(0), is(instance.getPrivateIpAddress())); assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance))); }
@Test public void convertInstanceMissingPrivateIp() { DateTime launchTime = UtcTime.now(); Instance instance = new Instance().withInstanceId("i-1") .withState(new InstanceState().withName(InstanceStateName.Running)).withPublicIpAddress("1.2.3.4") .withInstanceType(InstanceType.M1Medium).withLaunchTime(launchTime.toDate()) .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen) .withPlacement(new Placement("us-east-1b")); Machine machine = convert(instance); assertThat(machine.getId(), is(instance.getInstanceId())); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.medium")); assertThat(machine.getLaunchTime(), is(launchTime)); assertThat(machine.getMachineState(), is(MachineState.RUNNING)); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps().size(), is(1)); assertThat(machine.getPublicIps().get(0), is(instance.getPublicIpAddress())); assertThat(machine.getPrivateIps().size(), is(0)); assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance))); }
/** * A converted spot instance {@link Machine} should have a cloud provider * value of {@link CloudProviders#AWS_SPOT} to distinguish it from a regular * EC2 on-demand instance. */ @Test public void convertSpotInstance() { // convert on-demand instance: cloud provider should be AWS_EC2 Instance onDemandInstance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium) .withState(new InstanceState().withName(InstanceStateName.Running)) .withPlacement(new Placement("us-east-1b")); Machine onDemandMachine = convert(onDemandInstance); assertThat(onDemandMachine.getCloudProvider(), is(CloudProviders.AWS_EC2)); // convert spot instance: cloud provider should be AWS_EC2 Instance spotInstance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium) .withState(new InstanceState().withName(InstanceStateName.Running)).withSpotInstanceRequestId("sir-123") .withPlacement(new Placement("us-east-1b")); Machine spotMachine = convert(spotInstance); assertThat(spotMachine.getCloudProvider(), is(CloudProviders.AWS_SPOT)); }
private static LifecycleState ec2StateToLifecycleState(InstanceState state) { switch (state.getName()) { case "pending": return LifecycleState.Pending; case "running": return LifecycleState.InService; case "shutting-down": return LifecycleState.Terminating; case "terminated": return LifecycleState.Terminated; case "stopping": return LifecycleState.Terminating; case "stopped": return LifecycleState.Terminated; default: throw new IllegalArgumentException(String.format("unrecognized instance state: '%s'", state)); } }
/** * Updates the group by adding/removing instances to reach the set desired * capacity for the group ({@link #setDesiredSize(String, int)}. */ public void updateToDesiredSize() { int delta = this.memberInstances.size() - this.desiredCapacity; if (delta > 0) { // add instance(s) to group for (int i = 0; i < delta; i++) { int idNum = ++this.idSequencer; Instance newInstance = new Instance().withInstanceId("i-" + idNum) .withState(new InstanceState().withName("pending")).withPublicIpAddress("1.2.3." + idNum); this.allInstances.add(newInstance); this.memberInstances.add(newInstance); } } else if (delta < 0) { // remove instance(s) from group int toTerminate = -delta; for (int i = 0; i < toTerminate; i++) { terminateInstance(this.autoScalingGroupName, this.memberInstances.get(0).getInstanceId()); } } }
@Test // Test terminating instances works correctly public void testTerminateInstance() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); String instanceId="foo"; TerminateInstancesResult terminateInstancesResult = new TerminateInstancesResult(); client.setTerminateInstancesResult(terminateInstancesResult); InstanceStateChange stateChange = new InstanceStateChange(); stateChange.withInstanceId(instanceId); stateChange.setCurrentState(new InstanceState().withCode(32)); terminateInstancesResult.setTerminatingInstances(Arrays.asList(stateChange)); Properties properties = new Properties(); String region = "east"; MockManageVm manageEC2 = new MockManageVm(client,properties,region); boolean success = manageEC2.terminateInstance(instanceId); TerminateInstancesRequest request = client.getTerminateInstancesRequest(); Assert.assertEquals("Instance id size should match", 1, request.getInstanceIds().size()); Assert.assertEquals("Instance ids should match", instanceId, request.getInstanceIds().get(0)); Assert.assertTrue("Termination call should have been successful", success); }
@Test // Tests terminating an invalid instance is handled correctly public void testTerminateInstanceInvalidRunningCode() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); String instanceId="foo"; TerminateInstancesResult terminateInstancesResult = new TerminateInstancesResult(); client.setTerminateInstancesResult(terminateInstancesResult); InstanceStateChange stateChange = new InstanceStateChange(); stateChange.withInstanceId(instanceId); stateChange.setCurrentState(new InstanceState().withCode(8)); terminateInstancesResult.setTerminatingInstances(Arrays.asList(stateChange)); Properties properties = new Properties(); String region = "east"; MockManageVm manageEC2 = new MockManageVm(client,properties,region); boolean success = manageEC2.terminateInstance(instanceId); TerminateInstancesRequest request = client.getTerminateInstancesRequest(); Assert.assertEquals("Instance id size should match", 1, request.getInstanceIds().size()); Assert.assertEquals("Instance ids should match", instanceId, request.getInstanceIds().get(0)); Assert.assertFalse("Termination call should have not been successful", success); }
@Test // Test terminating a valid but not matching instances is handled correctly public void testTerminateInstanceNoMatchingInstance() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); String instanceId="foo"; TerminateInstancesResult terminateInstancesResult = new TerminateInstancesResult(); client.setTerminateInstancesResult(terminateInstancesResult); InstanceStateChange stateChange = new InstanceStateChange(); stateChange.withInstanceId("notMatching"); stateChange.setCurrentState(new InstanceState().withCode(8)); terminateInstancesResult.setTerminatingInstances(Arrays.asList(stateChange)); Properties properties = new Properties(); String region = "east"; MockManageVm manageEC2 = new MockManageVm(client,properties,region); boolean success = manageEC2.terminateInstance(instanceId); TerminateInstancesRequest request = client.getTerminateInstancesRequest(); Assert.assertEquals("Instance id size should match", 1, request.getInstanceIds().size()); Assert.assertEquals("Instance ids should match", instanceId, request.getInstanceIds().get(0)); Assert.assertFalse("Termination call should have not been successful", success); }
private MachineState getMachineState(Instance instance) { InstanceState state = instance.getState(); String stateName = state.getName(); if (stateName.equals("running")) { return STARTED; } else if (stateName.equals("pending")) { return STARTING; } else if (stateName.equals("shutting-down")) { return STOPPING; } else if (stateName.equals("terminated")) { return STOPPED; } else if (stateName.equals("stopped")) { return STARTED; // we dont need to create a new state as workflow dont support this } else { throw new IllegalStateException("State " + stateName + " is not known"); } }
public void createDescribeInstancesResult(String instanceId, String stateName, String publicDnsName) { InstanceState state = new InstanceState().withName(stateName); Instance instance = new Instance().withInstanceId(instanceId) .withState(state).withPublicDnsName(publicDnsName); Reservation reservation = new Reservation().withInstances(instance); DescribeInstancesResult instancesResult = new DescribeInstancesResult() .withReservations(reservation); doReturn(instancesResult).when(ec2) .describeInstances(any(DescribeInstancesRequest.class)); }
public void addDescribeInstancesResult(String instanceId, String stateName, String publicDnsName) { InstanceState state = new InstanceState().withName(stateName); Instance instance = new Instance().withInstanceId(instanceId) .withState(state).withPublicDnsName(publicDnsName); Reservation reservation = new Reservation().withInstances(instance); DescribeInstancesResult instancesResult = new DescribeInstancesResult() .withReservations(reservation); answerDescribeInstances.add(instancesResult); }
private boolean isRunningOrPending(InstanceState state) { boolean ret = false; if (state != null) { ret = state.getCode() == 0 || state.getCode() == 16; //0 - pending. 16 -- running } return ret; }
/** * {@link EC2ToTurbineInstance} can convert a running ec2 instance into * a turbine instance. */ @Test public void convertsRunningInstances() { final String ip = "172.13.131.215"; final String cluster = "blah"; final Instance ec2 = new Instance() .withPrivateIpAddress(ip) .withState(new InstanceState().withName(InstanceStateName.Running)); Assertions.assertThat(new EC2ToTurbineInstance(cluster).convert(ec2)) .isNotNull() .matches(instance -> instance.getHostname().equals(ip)) .matches(com.netflix.turbine.discovery.Instance::isUp); }
/** * {@link EC2ToTurbineInstance} can convert a running ec2 instance into * a turbine instance with an invalid name as address. */ @Test public void convertsRunningInstancesWithInvalidName() { final String ip = "172.13.131.215"; final String name = "asdasdasdasdasda"; final String cluster = "blah"; final Instance ec2 = new Instance() .withPrivateIpAddress(ip) .withTags(new Tag("Name", name)) .withState(new InstanceState().withName(InstanceStateName.Running)); Assertions.assertThat(new EC2ToTurbineInstance(cluster).convert(ec2)) .isNotNull() .matches(instance -> instance.getHostname().equals(ip)) .matches(com.netflix.turbine.discovery.Instance::isUp); }
/** * {@link EC2ToTurbineInstance} can convert a non running ec2 instance into * a turbine instance. */ @Test public void convertsNonRunningInstances() { final String ip = "177.12.43.123"; final String cluster = "blah"; final Instance ec2 = new Instance() .withPrivateIpAddress(ip) .withState(new InstanceState().withName(InstanceStateName.Pending)); Assertions.assertThat(new EC2ToTurbineInstance(cluster).convert(ec2)) .isNotNull() .matches(instance -> instance.getHostname().equals(ip)) .matches(instance -> !instance.isUp()); }
/** * Fake instance. * @return Fake running instance. */ private Instance fakeInstance() { return new Instance() .withPrivateIpAddress(String.valueOf(System.currentTimeMillis())) .withPrivateDnsName("any") .withState(new InstanceState().withName("running")); }
/** * Maps the Aws machine state to {@link PowerState} * * @param state * @return the {@link PowerState} of the machine */ public static PowerState mapToPowerState(InstanceState state) { PowerState powerState = PowerState.UNKNOWN; switch (state.getCode()) { case 16: powerState = PowerState.ON; break; case 80: powerState = PowerState.OFF; break; default: break; } return powerState; }
public static void waitForTransitionCompletion(ServiceHost host, List<InstanceStateChange> stateChangeList, final String desiredState, AmazonEC2AsyncClient client, BiConsumer<InstanceState, Exception> callback) { InstanceStateChange stateChange = stateChangeList.get(0); try { DescribeInstancesRequest request = new DescribeInstancesRequest(); request.withInstanceIds(stateChange.getInstanceId()); DescribeInstancesResult result = client.describeInstances(request); Instance instance = result.getReservations() .stream() .flatMap(r -> r.getInstances().stream()) .filter(i -> i.getInstanceId() .equalsIgnoreCase(stateChange.getInstanceId())) .findFirst().orElseThrow(() -> new IllegalArgumentException( String.format("%s instance not found", stateChange.getInstanceId()))); String state = instance.getState().getName(); if (state.equals(desiredState)) { callback.accept(instance.getState(), null); } else { host.schedule(() -> waitForTransitionCompletion(host, stateChangeList, desiredState, client, callback), 5, TimeUnit.SECONDS); } } catch (AmazonServiceException | IllegalArgumentException ase) { callback.accept(null, ase); } }
public static void showStateChange(InstanceStateChange stateChange, String description) { String changedInstanceId = stateChange.getInstanceId(); InstanceState previousState = stateChange.getPreviousState(); InstanceState currentState = stateChange.getCurrentState(); System.out.println(description + " (" + changedInstanceId + ": " + previousState.getName() + "=>" + currentState.getName() + ")"); }
@Test public void createTurbineInstance_down() { ConfigurationManager.getConfigInstance().addProperty(HOST_FIELD_PROPERTY_NAME, "public_ip"); Instance instance = createEc2Instance(); instance.setState(new InstanceState().withName("stopped")); com.netflix.turbine.discovery.Instance turbineInstance = mapper.createTurbineInstance("test_cluster1", instance); assertNotNull(turbineInstance); assertEquals("test_cluster1", turbineInstance.getCluster()); assertEquals("public_ip", turbineInstance.getHostname()); assertFalse(turbineInstance.isUp()); }