@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; }
private static InstanceState createState(com.amazonaws.services.ec2.model.InstanceStateName instanceState) { switch (instanceState) { case Pending: return InstanceState.QUEUED; default: case Running: return InstanceState.LAUNCHED; case ShuttingDown: return InstanceState.SHUTTING_DOWN; case Terminated: return InstanceState.DELETING; case Stopping: return InstanceState.SUSPENDING; case Stopped: return InstanceState.SUSPENDED; } }
@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 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; }
/** * Conversion of request that has been cancelled but with an instance that * is still running. */ @Test public void testConversionOfCancelledRequestWithRunningInstance() { InstancePairedSpotRequest cancelledRequest = new InstancePairedSpotRequest( SpotTestUtil.spotRequest("sir-1", "cancelled", "i-1"), SpotTestUtil.instance("i-1", InstanceStateName.Running, "sir-1")); Machine machine = InstancePairedSpotRequestToMachine.convert(cancelledRequest); assertThat(machine.getId(), is("sir-1")); assertThat(machine.getMachineState(), is(MachineState.TERMINATED)); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_SPOT)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.medium")); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getLaunchTime(), is(FrozenTime.now())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps(), is(list())); assertThat(machine.getPrivateIps(), is(list())); assertThat(machine.getMetadata(), is(JsonUtils.toJson(cancelledRequest))); }
@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)); }
/** * Converts the ec2 instance to a turbine instance. * @param ec2 EC2 instance. * @return Turbine instance. */ public com.netflix.turbine.discovery.Instance convert(final Instance ec2) { final boolean state = InstanceStateName.fromValue( ec2.getState().getName() ) == InstanceStateName.Running; return new com.netflix.turbine.discovery.Instance( ec2.getPrivateIpAddress(), this.cluster, state ); }
/** * {@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()); }
/** * Waits until the instance has entered a running state. * * @param ec2InstanceId the EC2 instance id * @return true if the instance has entered a running state, false if the instance is shutting down/terminated or * the function has timed out waiting for the instance to enter one of these two states. */ private boolean waitUntilInstanceHasStarted(String ec2InstanceId) throws InterruptedException { // TODO: Add a timeout to this loop. while (true) { try { DescribeInstanceStatusResult result = client.describeInstanceStatus( new DescribeInstanceStatusRequest() .withIncludeAllInstances(true) .withInstanceIds(ec2InstanceId) ); for (InstanceStatus status : result.getInstanceStatuses()) { InstanceStateName currentState = InstanceStateName.fromValue(status.getInstanceState().getName()); if (ec2InstanceId.equals(status.getInstanceId())) { if (currentState.equals(InstanceStateName.Terminated) || currentState.equals(InstanceStateName.ShuttingDown)) { LOG.error("Instance {} has unexpectedly terminated", ec2InstanceId); return false; } else if (!currentState.equals(InstanceStateName.Pending)) { return true; } } } } catch (AmazonServiceException e) { if (!INVALID_INSTANCE_ID_NOT_FOUND.equals(e.getErrorCode())) { AWSExceptions.propagate(e); } } TimeUnit.SECONDS.sleep(5); } }
private Instance createInstance(Cloud cloud, String region, com.amazonaws.services.ec2.model.Instance rawInstance) { Instance instance = new Instance(); String realId = String.valueOf(rawInstance.getInstanceId()); String instanceId = idGenerator.getInstanceId(cloud, realId); instance.setId(instanceId); instance.setRealId(realId); instance.setName(rawInstance.getInstanceId()); //TODO: check this! instance.setFqdn(rawInstance.getPublicDnsName()); instance.setCloudId(cloud.getId()); instance.setCloudType(CloudType.AWS); ZonedDateTime created = ZonedDateTime.ofInstant( rawInstance.getLaunchTime().toInstant(), ZoneId.systemDefault() ); instance.setCreated(created); InstanceStateName instanceStateName = InstanceStateName.fromValue(rawInstance.getState().getName()); instance.setState(createState(instanceStateName)); instance.setTimestamp(created); instance.setIsLocked(false); MetadataMap metadata = new MetadataMap(); metadata.put(MetadataKey.REGION, region); //TODO: console output for AWS is a screenshot! // metadata.put(MetadataKey.CONSOLE_URL, getConsoleUrl(instance.getId())); instance.setMetadata(metadata); return instance; }
/** * Counts the number of instances in EC2 currently running that are using * the specifed image. * * @param ami If AMI is left null, then all instances are counted. * <p> * This includes those instances that may be started outside Hudson. */ public int countCurrentEC2Slaves(String ami) throws AmazonClientException { int n = 0; for (Reservation r : connect().describeInstances().getReservations()) { for (Instance i : r.getInstances()) { if (isEc2ProvisionedSlave(i, ami)) { InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName()); if (stateName == InstanceStateName.Pending || stateName == InstanceStateName.Running) { n++; } } } } return n; }
@Test public void testGetEnvironmentFromInstance() throws Exception { final Date launchTime = new Date(); final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge).withTags(new Tag(EC2Connector.DEFAULT_INSTANCE_NAME_TAG, "unknown")) .withState(new InstanceState().withName(InstanceStateName.Running)).withLaunchTime(launchTime).withPublicIpAddress("127.0.0.1"); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getInstanceId(), is("instance")); assertThat(serverEnv.getInstanceType(), is(InstanceType.C1Xlarge.toString())); assertThat(serverEnv.getType(), is(ENVIRONMENT_TYPES.TEST)); assertThat(serverEnv.getEnvironmentTag(), is("unknown")); assertThat(serverEnv.getState().getName(), is(InstanceStateName.Running.toString())); assertThat(serverEnv.getLaunchTime(), is(launchTime)); assertThat(serverEnv.getPublicIpAddress(), is("127.0.0.1")); }
/** * Check the instance status and order to start it if it's stopped. * * @param instanceId Instance du start */ public void startInstance(final String instanceId) { LOG.entry(); LOG.info("Starting instance {}", instanceId); // Check the instance state final InstanceStateName instanteState = getInstanceStatus(instanceId); if (InstanceStateName.Stopped != instanteState) { final String message = "Instance " + instanceId + " is not stopped, current state: " + instanteState; LOG.error(message); final AmazonClientException exception = new AmazonClientException(message); LOG.exit(exception); throw exception; } // Start instance order final StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId); final StartInstancesResult startInstancesResult = amazonEC2Client.startInstances(startInstancesRequest); final List<InstanceStateChange> instanceStateChangeList = startInstancesResult.getStartingInstances(); for (final InstanceStateChange instanceStateChange : instanceStateChangeList) { LOG.info("Instance {} has changing state: {} -> {}", instanceStateChange.getInstanceId(), instanceStateChange.getPreviousState(), instanceStateChange.getCurrentState()); } LOG.info("Instance {} is starting", instanceId); LOG.exit(); }
/** * Check the instance status and order to stop it if it's running. * * @param instanceId instance to stop */ public void stopInstance(final String instanceId) { LOG.entry(); LOG.info("Stoping instance {}", instanceId); // Check the instance state final InstanceStateName instanteState = getInstanceStatus(instanceId); if (InstanceStateName.Running != instanteState) { final String message = "Instance " + instanceId + " is not running, current status: " + instanteState; LOG.error(message); LOG.exit(message); throw new AmazonClientException(message); } // Stop instance order final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(instanceId); final StopInstancesResult stopInstancesResult = amazonEC2Client.stopInstances(stopInstancesRequest); final List<InstanceStateChange> instanceStateChangeList = stopInstancesResult.getStoppingInstances(); for (final InstanceStateChange instanceStateChange : instanceStateChangeList) { LOG.info("Instance {} has changing state: {} -> {}", instanceStateChange.getInstanceId(), instanceStateChange.getPreviousState(), instanceStateChange.getCurrentState()); } LOG.info("Instance {} is stoping", instanceId); LOG.exit(); }
@Test(expected = AmazonClientException.class) public void testStartInstanceAlreadyRunning() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); try { amazonEC2Service.startInstance(INSTANCE_ID); } finally { Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); } }
@Test(expected = AmazonClientException.class) public void testStopInstanceAlreadyStopped() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Stopped))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); try { amazonEC2Service.stopInstance(INSTANCE_ID); } finally { Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); } }
@Test(expected = AmazonClientException.class) public void testGetInstanceStatusMultipleInstances() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)), new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); try { amazonEC2Service.getInstanceStatus(INSTANCE_ID); } finally { Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); } }
@Test public void testProcessAllSectionsCheckStartOrderStoppedInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, true, false, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.START.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Stopped).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isFalse(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsCheckStartOrderRunningInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, true, false, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.START.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Running).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isTrue(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsCheckStopOrderRunningInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, true, false, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.STOP.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Running).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isFalse(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsCheckStopOrderStoppedInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, true, false, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.STOP.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Stopped).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isTrue(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsPostCheckStartOrderRunningInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, false, true, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.START.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Running).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isFalse(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsPostCheckStartOrderStoppedInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, false, true, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.START.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Stopped).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isTrue(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsPostCheckStopOrderStoppedInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, false, true, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.STOP.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Stopped).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isFalse(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
@Test public void testProcessAllSectionsPostCheckStopOrderRunningInstance() { final ProgramOptions programOptions = new ProgramOptions(false, false, false, true, Lists.newArrayList(SECTION_1)); Mockito.doReturn(Lists.newArrayList(new InstanceOrder(INSTANCE_ID_1, OrderType.STOP.toString()))).when(configurationService).getConfiguredSections(SECTION_1); Mockito.doReturn(InstanceStateName.Running).when(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isTrue(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); Mockito.verify(amazonEC2Service).getInstanceStatus(INSTANCE_ID_1); }
/** * <p> * Wait for the ec2 instances starting up and returns it up to date. * </p> * <p> * Note: some information are missing of the {@link Instance} returned by {@link AmazonEC2#describeInstances(DescribeInstancesRequest)} as long as * the instance is not "running" (e.g., {@link Instance#getPublicDnsName()}). * </p> * * @param instanceToWaitRunningState * @return up to date instances or <code>null</code> if the instance crashed at startup. */ private Instance waitForInstanceRunningState(final Instance instanceToWaitRunningState) { Instance instance = instanceToWaitRunningState; int counter = 0; while (InstanceStateName.Pending.name().equalsIgnoreCase(instance.getState().getName())) //|| (instance.getPublicIpAddress() == null) || (instance.getPublicDnsName() == null) { String description = String.format("Waiting running state of the instance [%s]: [%s]", instance.getInstanceId(), instance); backoffForAttempt(counter + 1, description); instance = describeEC2Instance(instance.getInstanceId()); counter++; if (counter >= MAX_RETRY_STATE) { LOG.warn("Timeout waiting for startup of [{}]: [{}]", instance.getInstanceId(), instanceToWaitRunningState); return instanceToWaitRunningState; } } if (InstanceStateName.ShuttingDown.equals(instance.getState()) || InstanceStateName.Terminated.equals(instance.getState())) { LOG.warn("Terminating and skipping dying instance [{}] (stateReason=[{}], stateTransitionReason=[{}]): [{}]", instance.getInstanceId(), instance.getStateReason(), instance.getStateTransitionReason(), instance); this.terminateInstances(instance.getInstanceId()); return null; } LOG.debug("Instance {} is running", instance.getInstanceId()); return instance; }
public Instance waitInstance(AwsProcessClient awsProcessClient, String instanceId) { // インスタンスの処理待ち Instance instance; while (true) { try { Thread.sleep(1000L * awsProcessClient.getDescribeInterval()); } catch (InterruptedException ignore) { } instance = describeInstance(awsProcessClient, instanceId); InstanceStateName state; try { state = InstanceStateName.fromValue(instance.getState().getName()); } catch (IllegalArgumentException e) { // 予期しないステータス AutoException exception = new AutoException("EPROCESS-000104", instanceId, instance.getState() .getName()); exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance)); throw exception; } // 安定状態のステータスになったら終了 if (state == InstanceStateName.Running || state == InstanceStateName.Terminated || state == InstanceStateName.Stopped) { break; } } return instance; }
public void waitRun(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // インスタンスの作成待ち com.amazonaws.services.ec2.model.Instance instance = awsCommonProcess .waitInstance(awsProcessClient, instanceId); if (!instance.getState().getName().equals(InstanceStateName.Running.toString())) { // インスタンス作成失敗時 AutoException exception = new AutoException("EPROCESS-000106", instanceId, instance.getState().getName()); exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance)); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100116", instanceId)); } // イベントログ出力 Instance instance2 = instanceDao.read(instanceNo); processLogger.debug(null, instance2, "AwsInstanceCreateFinish", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // データベース更新 awsInstance.setAvailabilityZone(instance.getPlacement().getAvailabilityZone()); awsInstance.setStatus(instance.getState().getName()); awsInstance.setDnsName(instance.getPublicDnsName()); awsInstance.setPrivateDnsName(instance.getPrivateDnsName()); awsInstance.setIpAddress(instance.getPublicIpAddress()); awsInstance.setPrivateIpAddress(instance.getPrivateIpAddress()); awsInstanceDao.update(awsInstance); }
public void waitStart(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // インスタンスの起動待ち com.amazonaws.services.ec2.model.Instance instance = awsCommonProcess .waitInstance(awsProcessClient, instanceId); if (!instance.getState().getName().equals(InstanceStateName.Running.toString())) { // インスタンス起動失敗時 AutoException exception = new AutoException("EPROCESS-000126", instanceId, instance.getState().getName()); exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance)); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100112", instanceId)); } // イベントログ出力 Instance instance2 = instanceDao.read(instanceNo); processLogger.debug(null, instance2, "AwsInstanceStartFinish", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // データベース更新 awsInstance.setAvailabilityZone(instance.getPlacement().getAvailabilityZone()); awsInstance.setStatus(instance.getState().getName()); awsInstance.setDnsName(instance.getPublicDnsName()); awsInstance.setPrivateDnsName(instance.getPrivateDnsName()); awsInstance.setIpAddress(instance.getPublicIpAddress()); awsInstance.setPrivateIpAddress(instance.getPrivateIpAddress()); awsInstanceDao.update(awsInstance); }
public void waitStop(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // インスタンスの停止待ち com.amazonaws.services.ec2.model.Instance instance = awsCommonProcess .waitInstance(awsProcessClient, instanceId); if (!instance.getState().getName().equals(InstanceStateName.Stopped.toString())) { // インスタンス停止失敗時 AutoException exception = new AutoException("EPROCESS-000129", instanceId, instance.getState().getName()); exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance)); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100114", instanceId)); } // イベントログ出力 Instance instance2 = instanceDao.read(instanceNo); processLogger.debug(null, instance2, "AwsInstanceStopFinish", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // データベース更新 awsInstance.setAvailabilityZone(instance.getPlacement().getAvailabilityZone()); awsInstance.setStatus(instance.getState().getName()); awsInstance.setDnsName(instance.getPublicDnsName()); awsInstance.setPrivateDnsName(instance.getPrivateDnsName()); awsInstance.setIpAddress(instance.getPublicIpAddress()); awsInstance.setPrivateIpAddress(instance.getPrivateIpAddress()); awsInstanceDao.update(awsInstance); }
@Override public TerminateInstancesResult terminateInstances(List<String> instanceIds) throws AmazonClientException { TerminateInstancesResult result = new TerminateInstancesResult(); for (String instanceId : instanceIds) { Instance instance = getInstanceMetadata(instanceId); this.instances.remove(instance); InstanceStateChange instanceStateChange = new InstanceStateChange().withInstanceId(instance.getInstanceId()) .withCurrentState(new InstanceState().withName(InstanceStateName.ShuttingDown)); result.withTerminatingInstances(instanceStateChange); } return result; }