@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 List<VMInformation> stopForRegion(VMRegion region, List<String> instanceIds) { List<VMInformation> result = new ArrayList<VMInformation>(); try { asynchEc2Client.setEndpoint(region.getEndpoint()); List<VMInformation> instances = describeInstances(instanceIds.toArray(new String[instanceIds.size()])); List<String> ids = new ArrayList<String>(); for (VMInformation info : instances) { ids.add(info.getInstanceId()); } if (ids.size() > 0) { StopInstancesRequest stopInstancesRequest = new StopInstancesRequest(ids); StopInstancesResult stopResult = asynchEc2Client.stopInstances(stopInstancesRequest); List<InstanceStateChange> stoppingInstances = stopResult.getStoppingInstances(); result = new AmazonDataConverter().processStateChange(stoppingInstances); } } catch (Exception ex) { LOG.error(ex.getMessage(), ex); throw new RuntimeException(ex); } return result; }
public List<VMInformation> processStateChange(List<InstanceStateChange> changes) { List<VMInformation> output = new ArrayList<VMInformation>(); try { for (InstanceStateChange instance : changes) { VMInformation info = new VMInformation(); info.setInstanceId(instance.getInstanceId()); info.setState(instance.getCurrentState().getName()); output.add(info); } return output; } catch (Exception ex) { LOG.error(ex.getMessage(), ex); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } }
@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; }
@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 // 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); }
/** * Start specified instances (power-on the instances). * * @param instanceIDs * IDs of the instances start * @return a list of state changes for the instances */ public static List<InstanceStateChange> startInstances(final List<String> instanceIDs) { // pass any credentials as aws-mock does not authenticate them at all AWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials); // the mock endpoint for ec2 which runs on your computer String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/"; amazonEC2Client.setEndpoint(ec2Endpoint); // send the start request with args as instance IDs to start existing instances StartInstancesRequest request = new StartInstancesRequest(); request.withInstanceIds(instanceIDs); StartInstancesResult result = amazonEC2Client.startInstances(request); return result.getStartingInstances(); }
/** * Main method for command line use. * * @param args * parameters from command line - IDs of the instances to start */ public static void main(final String[] args) { List<InstanceStateChange> iscs = startInstances(Arrays.asList(args)); if (null != iscs && iscs.size() > 0) { System.out.println("Instance state changes: "); for (InstanceStateChange isc : iscs) { System.out.println(isc.getInstanceId() + ": " + isc.getPreviousState().getName() + " -> " + isc.getCurrentState().getName()); } } else { System.out.println("Nothing happened! Make sure you input the right instance IDs."); System.out.println("usage: java StartInstancesExample <instanceID-1> [instanceID-2] [instanceID-3] ..."); } }
/** * Terminate specified instances (power-on the instances). * * @param instanceIDs * IDs of the instances to terminate * @return a list of state changes for the instances */ public static List<InstanceStateChange> terminateInstances(final List<String> instanceIDs) { // pass any credentials as aws-mock does not authenticate them at all AWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials); // the mock endpoint for ec2 which runs on your computer String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/"; amazonEC2Client.setEndpoint(ec2Endpoint); // send the terminate request with args as instance IDs TerminateInstancesRequest request = new TerminateInstancesRequest(); request.withInstanceIds(instanceIDs); TerminateInstancesResult result = amazonEC2Client.terminateInstances(request); return result.getTerminatingInstances(); }
/** * Main method for command line use. * * @param args * parameters from command line - IDs of the instances to terminate */ public static void main(final String[] args) { List<InstanceStateChange> iscs = terminateInstances(Arrays.asList(args)); if (null != iscs && iscs.size() > 0) { System.out.println("Instance state changes: "); for (InstanceStateChange isc : iscs) { System.out.println(isc.getInstanceId() + ": " + isc.getPreviousState().getName() + " -> " + isc.getCurrentState().getName()); } } else { System.out.println("Nothing happened! Make sure you input the right instance IDs."); System.out .println("usage: java TerminateInstancesExample <instanceID-1> [instanceID-2] [instanceID-3] ..."); } }
/** * Stop specified instances (power-on the instances). * * @param instanceIDs * IDs of the instances to stop * @return a list of state changes for the instances */ public static List<InstanceStateChange> stopInstances(final List<String> instanceIDs) { // pass any credentials as aws-mock does not authenticate them at all AWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials); // the mock endpoint for ec2 which runs on your computer String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/"; amazonEC2Client.setEndpoint(ec2Endpoint); // send the stop request with args as instance IDs to stop running instances StopInstancesRequest request = new StopInstancesRequest(); request.withInstanceIds(instanceIDs); StopInstancesResult result = amazonEC2Client.stopInstances(request); return result.getStoppingInstances(); }
/** * Main method for command line use. * * @param args * parameters from command line - IDs of the instances to stop */ public static void main(final String[] args) { List<InstanceStateChange> iscs = stopInstances(Arrays.asList(args)); if (null != iscs && iscs.size() > 0) { System.out.println("Instance state changes: "); for (InstanceStateChange isc : iscs) { System.out.println(isc.getInstanceId() + ": " + isc.getPreviousState().getName() + " -> " + isc.getCurrentState().getName()); } } else { System.out.println("Nothing happened! Make sure you input the right instance IDs."); System.out.println("usage: java StopInstancesExample <instanceID-1> [instanceID-2] [instanceID-3] ..."); } }
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); } }
/** * Run the List<VMInformation> processStateChange(List<InstanceStateChange>) method test. * * @throws Exception * * @generatedBy CodePro at 12/16/14 6:30 PM */ @Test public void testProcessStateChange_1() throws Exception { AmazonDataConverter fixture = new AmazonDataConverter(); List<InstanceStateChange> changes = new LinkedList(); List<VMInformation> result = fixture.processStateChange(changes); assertNotNull(result); assertEquals(0, result.size()); }
/** * Run the List<VMInformation> processStateChange(List<InstanceStateChange>) method test. * * @throws Exception * * @generatedBy CodePro at 12/16/14 6:30 PM */ @Test public void testProcessStateChange_2() throws Exception { AmazonDataConverter fixture = new AmazonDataConverter(); List<InstanceStateChange> changes = new LinkedList(); List<VMInformation> result = fixture.processStateChange(changes); assertNotNull(result); assertEquals(0, result.size()); }
public static InstanceStateChange stopInstance(AmazonEC2 ec2, String instanceId) { StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(instanceId); StopInstancesResult stopInstancesResult = ec2.stopInstances(stopInstancesRequest); List<InstanceStateChange> instanceStateChange = stopInstancesResult.getStoppingInstances(); for (InstanceStateChange stateChange : instanceStateChange) { return stateChange; } return null; }
public static InstanceStateChange startInstance(AmazonEC2 ec2, String instanceId) { StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId); StartInstancesResult startInstancesResult = ec2.startInstances(startInstancesRequest); List<InstanceStateChange> instanceStateChange = startInstancesResult.getStartingInstances(); for (InstanceStateChange stateChange : instanceStateChange) { return stateChange; } return null; }
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() + ")"); }
/** * Stop Ec2 Instance. Realease EIP for Ec2 Instance. Disassociate EIP. */ public int execute(Ec2CommandOptions options) throws FileNotFoundException { System.out.println(getClass().getName()); String name = options.getName(); InputStream inputStream = new FileInputStream(new File(options.getCredentialsPath())); ConfigProvider.loadConfigure(inputStream); AmazonEC2 ec2 = AwsEc2Client.getEc2(); // Check Exists Instance Instance instance = AwsEc2Client.findInstanceByName(ec2, name); if (instance == null) { System.err.println("Not exists instance (name = " + name + ")."); return 2; } String instanceId = instance.getInstanceId(); String publicIp = instance.getPublicIpAddress(); System.out.println("Exists instance (id = " + instanceId + ")"); // Stop Ec2 Instance InstanceStateChange stateChange = AwsEc2Client.stopInstance(ec2, instanceId); AwsEc2Client.showStateChange(stateChange, "Stopping Instance"); // Disassociate and Release Address if (publicIp != null) { Address address = AwsEc2Client.checkExistsAddress(ec2, publicIp); if (address != null) { AwsEc2Client.disassociateAddress(ec2, address); System.out.println("Disassociated Address (" + publicIp + ")"); AwsEc2Client.releaseAddress(ec2, address); System.out.println("Released Address (" + publicIp + ")"); } } else { System.out.println("No EIP."); } return 0; }
/** * 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(); }
public void startInstances(String ... instanceIds) { LOG.info("Starting up the instances [{}]", Arrays.toString(instanceIds)); List<InstanceStateChange> startingInstances = ec2_.startInstances(new StartInstancesRequest().withInstanceIds(instanceIds)).getStartingInstances(); for (InstanceStateChange state: startingInstances) { LOG.info("The state of the instance [{}] changed from [{}] to [{}]", state.getInstanceId(), state.getPreviousState().getName(), state.getCurrentState().getName()); } // waitForEc2Instance(instanceToWaitRunningState); }
public void start(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // イベントログ出力 Instance instance = instanceDao.read(instanceNo); processLogger.debug(null, instance, "AwsInstanceStart", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // インスタンスの起動 StartInstancesRequest request = new StartInstancesRequest(); request.withInstanceIds(instanceId); StartInstancesResult result = awsProcessClient.getEc2Client().startInstances(request); List<InstanceStateChange> startingInstances = result.getStartingInstances(); // API実行結果チェック if (startingInstances.size() == 0) { // インスタンス起動失敗時 throw new AutoException("EPROCESS-000125", instanceId); } else if (startingInstances.size() > 1) { // 複数のインスタンスが起動した場合 AutoException exception = new AutoException("EPROCESS-000127", instanceId); exception.addDetailInfo("result=" + startingInstances); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100111", instanceId)); } // データベース更新 awsInstance.setStatus(startingInstances.get(0).getCurrentState().getName()); awsInstanceDao.update(awsInstance); }
public void stop(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // イベントログ出力 Instance instance = instanceDao.read(instanceNo); processLogger.debug(null, instance, "AwsInstanceStop", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // インスタンスの停止 StopInstancesRequest request = new StopInstancesRequest(); request.withInstanceIds(instanceId); StopInstancesResult result = awsProcessClient.getEc2Client().stopInstances(request); List<InstanceStateChange> stoppingInstances = result.getStoppingInstances(); // API実行結果チェック if (stoppingInstances.size() == 0) { // インスタンス停止失敗時 throw new AutoException("EPROCESS-000128", instanceId); } else if (stoppingInstances.size() > 1) { // 複数のインスタンスが停止した場合 AutoException exception = new AutoException("EPROCESS-000130", instanceId); exception.addDetailInfo("result=" + stoppingInstances); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100113", instanceId)); } // データベース更新 awsInstance.setStatus(stoppingInstances.get(0).getCurrentState().getName()); awsInstanceDao.update(awsInstance); }
public void terminate(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // イベントログ出力 Instance instance = instanceDao.read(instanceNo); processLogger.debug(null, instance, "AwsInstanceDelete", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // インスタンスの削除 TerminateInstancesRequest request = new TerminateInstancesRequest(); request.withInstanceIds(instanceId); TerminateInstancesResult result = awsProcessClient.getEc2Client().terminateInstances(request); List<InstanceStateChange> terminatingInstances = result.getTerminatingInstances(); // API実行結果チェック if (terminatingInstances.size() == 0) { // インスタンス削除失敗時 throw new AutoException("EPROCESS-000107", instanceId); } else if (terminatingInstances.size() > 1) { // 複数のインスタンスが削除された場合 AutoException exception = new AutoException("EPROCESS-000108", instanceId); exception.addDetailInfo("result=" + terminatingInstances); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100117", instanceId)); } // データベース更新 awsInstance.setStatus(terminatingInstances.get(0).getCurrentState().getName()); 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; }
/** * Terminates the specified instance. * * @param instanceId Id of the instance to terminate */ public boolean terminateInstance(final String instanceId) { TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(); terminateRequest.withInstanceIds(instanceId); if(client == null){ throw new RuntimeException("The client is not initialized"); } TerminateInstancesResult result = client.terminateInstances(terminateRequest); List<InstanceStateChange> stateChanges = result.getTerminatingInstances(); boolean terminatedInstance = false; for (InstanceStateChange stateChange : stateChanges) { if (instanceId.equals(stateChange.getInstanceId())) { terminatedInstance = true; InstanceState currentState = stateChange.getCurrentState(); if (currentState.getCode() != 32 && currentState.getCode() != 48) { log.error(String.format( "Machine state for id %s should be terminated (48) or shutting down (32) but was %s instead", instanceId, currentState.getCode())); return false; } } } if (!terminatedInstance) { log.error("Matching terminated instance was not found for instance " + instanceId); return false; } return true; }
/** * Test one instance by run->stop. */ @Test(timeout = TIMEOUT_LEVEL1) public final void sequenceRunStopTest() { log.info("Start simple run -> stop test"); // run List<Instance> instances = runInstances( AbstractMockEc2Instance.InstanceType.M1_SMALL, 1, 1); Assert.assertTrue("fail to start instances", instances.size() == 1); instances = describeInstances(instances); Assert.assertTrue("fail to describe instances", instances.size() == 1); Assert.assertEquals("pending", instances.get(0).getState().getName()); // wait for running waitForState(instances.get(0).getInstanceId(), AbstractMockEc2Instance.InstanceState.RUNNING); // stop List<InstanceStateChange> stateChanges = stopInstances(instances); Assert.assertTrue("fail to stop instances", stateChanges.size() == 1); Assert.assertEquals("stopping", stateChanges.get(0).getCurrentState() .getName()); // wait for stopped waitForState(instances.get(0).getInstanceId(), AbstractMockEc2Instance.InstanceState.STOPPED); }
/** * Test one instance by run->stop->start->terminate. */ @Test(timeout = TIMEOUT_LEVEL2) public final void sequenceRunStopStartTerminateTest() { log.info("Start simple run->stop->start->terminate test"); // run List<Instance> instances = runInstances( AbstractMockEc2Instance.InstanceType.M1_SMALL, 1, 1); Assert.assertTrue("fail to start instances", instances.size() == 1); // wait for running waitForState(instances.get(0).getInstanceId(), AbstractMockEc2Instance.InstanceState.RUNNING); // stop List<InstanceStateChange> stateChanges = stopInstances(instances); Assert.assertTrue("fail to stop instances", stateChanges.size() == 1); // wait for stopped waitForState(instances.get(0).getInstanceId(), AbstractMockEc2Instance.InstanceState.STOPPED); // re-start stateChanges = startInstances(instances); Assert.assertTrue("fail to re-start instances", stateChanges.size() == 1); // wait for running waitForState(instances.get(0).getInstanceId(), AbstractMockEc2Instance.InstanceState.RUNNING); // terminate stateChanges = terminateInstances(instances); Assert.assertTrue("fail to terminate instances", stateChanges.size() == 1); // wait for terminated waitForState(instances.get(0).getInstanceId(), AbstractMockEc2Instance.InstanceState.TERMINATED); }
/** * Start instances. * * @param instanceIds * instances' IDs * @return list of instances change */ protected final List<InstanceStateChange> startInstances( final Collection<String> instanceIds) { log.info("Start instances:" + toString(instanceIds)); StartInstancesRequest request = new StartInstancesRequest(); request.setInstanceIds(instanceIds); StartInstancesResult result = amazonEC2Client.startInstances(request); return result.getStartingInstances(); }
/** * Stop instances. * * @param instanceIds * instances' IDs * @return list of instances change */ protected final List<InstanceStateChange> stopInstances( final Collection<String> instanceIds) { log.info("Stop instances:" + toString(instanceIds)); StopInstancesRequest request = new StopInstancesRequest(); request.setInstanceIds(instanceIds); StopInstancesResult result = amazonEC2Client.stopInstances(request); return result.getStoppingInstances(); }
/** * Terminate instances. * * @param instanceIds * instances' IDs * @return list of instances change */ protected final List<InstanceStateChange> terminateInstances( final Collection<String> instanceIds) { log.info("Terminate instances:" + toString(instanceIds)); TerminateInstancesRequest request = new TerminateInstancesRequest(); request.setInstanceIds(instanceIds); TerminateInstancesResult result = amazonEC2Client .terminateInstances(request); return result.getTerminatingInstances(); }
@Override public void startInstance(String ec2InstanceId) throws InterruptedException { Instance instance = getSingleEc2InstanceById(ec2InstanceId); InstanceState state = instance.getState(); // different possible states: pending, running, shutting-down, // terminated, stopping, stopped String stateName = state.getName(); if (stateName.equalsIgnoreCase("pending")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is pending, no action was taken."); } else if (stateName.equalsIgnoreCase("running")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is running, no action was taken."); } else if (stateName.equalsIgnoreCase("shutting-down")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is shutting-down, no action was taken."); // TODO maybe we should wait for the instance to shutdown before // starting it again.. ? } else if (stateName.equalsIgnoreCase("terminated")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is terminated, no action was taken."); // TODO throw error ? } else if (stateName.equalsIgnoreCase("stopping")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is stopping, no action was taken."); // TODO maybe we should wait for the instance to stop before // starting it again.. ? what is the difference between // shutting-down and stopping ?? } else if (stateName.equalsIgnoreCase("stopped")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is stopped, the instance has been asked to start..."); StartInstancesRequest startRequest = new StartInstancesRequest() .withInstanceIds(ec2InstanceId); StartInstancesResult startResult = config.getAmazonEC2Client() .startInstances(startRequest); List<InstanceStateChange> stateChangeList = startResult .getStartingInstances(); waitForTransitionCompletion(stateChangeList, "running", ec2InstanceId); } }