com.amazonaws.services.ec2.model.TerminateInstancesRequest Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.TerminateInstancesRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EC2Api.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Auto handle instance not found exception if any and assume those instances as already terminated
 *
 * @param ec2
 * @param instanceIds
 */
public void terminateInstances(final AmazonEC2 ec2, final Set<String> instanceIds) {
    final List<String> temp = new ArrayList<>(instanceIds);
    while (temp.size() > 0) {
        // terminateInstances is idempotent so it can be called until it's successful
        try {
            ec2.terminateInstances(new TerminateInstancesRequest(temp));
            // clear as removed so we can finish
            temp.clear();
        } catch (AmazonEC2Exception exception) {
            // if we cannot find instance, that's fine assume them as terminated
            // remove from request and try again
            if (exception.getErrorCode().equals(NOT_FOUND_ERROR_CODE)) {
                final List<String> notFoundInstanceIds = parseInstanceIdsFromNotFoundException(exception.getMessage());
                if (notFoundInstanceIds.isEmpty()) {
                    // looks like we cannot parse correctly, rethrow
                    throw exception;
                }
                temp.removeAll(notFoundInstanceIds);
            }
        }
    }
}
 
Example #2
Source File: TerminateInstancesExample.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #3
Source File: AwsDownscaleService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void terminateInstances(List<String> instanceIds, AmazonEC2Client amazonEC2Client) {
    try {
        amazonEC2Client.terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceIds));
    } catch (AmazonServiceException e) {
        if (!INSTANCE_NOT_FOUND_ERROR_CODE.equals(e.getErrorCode())) {
            throw e;
        } else {
            List<String> runningInstances = instanceIds.stream()
                    .filter(instanceId -> !e.getMessage().contains(instanceId))
                    .collect(Collectors.toList());
            if (!runningInstances.isEmpty()) {
                amazonEC2Client.terminateInstances(new TerminateInstancesRequest().withInstanceIds(runningInstances));
            }
        }
        LOGGER.debug(e.getErrorMessage());
    }
}
 
Example #4
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Test
// Tests that the terminate code works when no matching results are returned by the client
public void testTerminateInstanceNoInstanceEmpty() {
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    String instanceId="foo";
    TerminateInstancesResult terminateInstancesResult = new TerminateInstancesResult();
    client.setTerminateInstancesResult(terminateInstancesResult);
    terminateInstancesResult.setTerminatingInstances(CollectionUtils.EMPTY_COLLECTION);
    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);
}
 
Example #5
Source File: Ec2IaasHandler.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {

	this.logger.fine( "Terminating machine '" + machineId + "'." );
	cancelMachineConfigurator( machineId );
	try {
		AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties());
		TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest();
		terminateInstancesRequest.withInstanceIds( machineId );
		ec2.terminateInstances( terminateInstancesRequest );

	} catch( Exception e ) {
		this.logger.severe( "An error occurred while terminating a machine on Amazon EC2. " + e.getMessage());
		throw new TargetException( e );
	}
}
 
Example #6
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example #10
Source File: AwsInstanceCloudConnector.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used internally by the connector itself for housekeeping.
 */
Completable terminateDetachedInstances(List<String> ids) {
    Observable<TerminateInstancesResult> observable = toObservable(
            new TerminateInstancesRequest(ids),
            ec2Client::terminateInstancesAsync
    );
    return observable.toCompletable();
}
 
Example #11
Source File: EC2InstanceManager.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * Terminates instances with given Ids
 *
 * @param instanceIds
 */
@Override
public void terminateInstances( final Collection<String> instanceIds ) {
    if( instanceIds == null || instanceIds.size() == 0 ) {
        return;
    }
    TerminateInstancesRequest request = ( new TerminateInstancesRequest() ).withInstanceIds( instanceIds );
    client.terminateInstances( request );
}
 
Example #12
Source File: Ec2Util.java    From s3-bucket-loader with Apache License 2.0 5 votes vote down vote up
public void terminateEc2Instance(AmazonEC2Client ec2Client, String instanceId) throws Exception {
	try {
		TerminateInstancesRequest termReq = new TerminateInstancesRequest();
		List<String> instanceIds = new ArrayList<String>();
		instanceIds.add(instanceId);
		termReq.setInstanceIds(instanceIds);
		logger.debug("Terminating EC2 instances...." + Arrays.toString(instanceIds.toArray(new String[]{})));
		ec2Client.terminateInstances(termReq);
		
	} catch(Exception e) {
		logger.error("Unexpected error terminating: " + instanceId + " "+ e.getMessage(),e);
	}
}
 
Example #13
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public TerminateInstancesResult terminate(
        ResultCapture<TerminateInstancesResult> extractor) {

    TerminateInstancesRequest request = new TerminateInstancesRequest();
    return terminate(request, extractor);
}
 
Example #14
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public TerminateInstancesResult terminate(TerminateInstancesRequest request,
        ResultCapture<TerminateInstancesResult> extractor) {

    ActionResult result = resource.performAction("Terminate", request,
            extractor);

    if (result == null) return null;
    return (TerminateInstancesResult) result.getData();
}
 
Example #15
Source File: AwsVmManager.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: AwsInstanceProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: AwsInfrastructure.java    From chaos-lemur with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(Member member) throws DestructionException {
    List<String> terminate = new ArrayList<>();
    terminate.add(member.getId());
    TerminateInstancesRequest tir = new TerminateInstancesRequest(terminate);
    this.amazonEC2.terminateInstances(tir);
}
 
Example #18
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testTerminateInstance() throws Exception {
    ec2comm.terminateInstance("instance1");
    ArgumentCaptor<TerminateInstancesRequest> arg1 = ArgumentCaptor
            .forClass(TerminateInstancesRequest.class);
    verify(ec2).terminateInstances(arg1.capture());
    TerminateInstancesRequest val = arg1.getValue();

    assertEquals(1, val.getInstanceIds().size());
    assertEquals("instance1", val.getInstanceIds().get(0));
}
 
Example #19
Source File: EC2ProcessorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void process_DELETION_REQUESTED() throws Exception {
    ph.setOperation(Operation.EC2_DELETION);
    ph.setState(FlowState.DELETION_REQUESTED);
    InstanceStatus result = ec2proc.process();
    assertFalse(result.isReady());
    assertEquals(FlowState.DELETING, ph.getState());

    verify(ec2).terminateInstances(any(TerminateInstancesRequest.class));
}
 
Example #20
Source File: AWSControllerIT.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteInstance() throws Exception {

    parameters.put(PropertyHandler.FLOW_STATE,
            new Setting(PropertyHandler.FLOW_STATE,
                    FlowState.DELETION_REQUESTED.name()));
    parameters.put(PropertyHandler.OPERATION, new Setting(
            PropertyHandler.OPERATION, Operation.EC2_DELETION.name()));

    ec2mock.createDescribeImagesResult(IMAGE_ID);
    ec2mock.createRunInstancesResult(INSTANCE_ID);

    ec2mock.addDescribeInstancesResult(INSTANCE_ID, "pending",
            "2aws-1-2-3-4");
    ec2mock.addDescribeInstanceStatusResult(INSTANCE_ID, "pending",
            "initializing", "initializing");

    ec2mock.addDescribeInstancesResult(INSTANCE_ID, "terminated",
            "2aws-1-2-3-4");
    ec2mock.addDescribeInstanceStatusResult(INSTANCE_ID, "terminated",
            "ok", "ok");

    ec2mock.addDescribeInstancesResult(INSTANCE_ID, "terminated", null);

    runUntilReady();

    ArgumentCaptor<TerminateInstancesRequest> argCapImages = ArgumentCaptor
            .forClass(TerminateInstancesRequest.class);
    verify(ec2).terminateInstances(argCapImages.capture());

}
 
Example #21
Source File: AwsInstanceCloudConnector.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private Completable doTerminate(List<String> instanceIds) {
    TerminateInstancesRequest request = new TerminateInstancesRequest().withInstanceIds(instanceIds);
    Observable<TerminateInstancesResult> observable = toObservable(request, ec2Client::terminateInstancesAsync);
    return observable
            .doOnCompleted(() -> logger.info("Terminated instances: {}", instanceIds))
            .doOnError(e -> logger.warn("Failed to terminate instances: {}, due to {}", instanceIds, e.getMessage()))
            .toCompletable();
}
 
Example #22
Source File: MockAmazonEc2Client.java    From SeleniumGridScaler with GNU General Public License v2.0 4 votes vote down vote up
public TerminateInstancesRequest getTerminateInstancesRequest() {
    return terminateInstancesRequest;
}
 
Example #23
Source File: MockAmazonEc2Client.java    From SeleniumGridScaler with GNU General Public License v2.0 4 votes vote down vote up
@Override
public TerminateInstancesResult terminateInstances(TerminateInstancesRequest terminateInstancesRequest) throws AmazonServiceException, AmazonClientException {
    this.terminateInstancesRequest = terminateInstancesRequest;
    return terminateInstancesResult;
}
 
Example #24
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public TerminateInstancesResult terminate(TerminateInstancesRequest request)
        {

    return terminate(request, null);
}
 
Example #25
Source File: AwsInfrastructureTest.java    From chaos-lemur with Apache License 2.0 4 votes vote down vote up
private TerminateInstancesRequest terminateInstancesRequest() {
    return new TerminateInstancesRequest().withInstanceIds(this.member.getId());
}
 
Example #26
Source File: EC2Communication.java    From development with Apache License 2.0 4 votes vote down vote up
public void terminateInstance(String instanceId) {
    getEC2().terminateInstances(
            new TerminateInstancesRequest().withInstanceIds(instanceId));
}
 
Example #27
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Terminate</code> action.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Instance</code> resource, and any conflicting parameter value set
 * in the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>InstanceIds.0</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The response of the low-level client operation associated with
 *         this resource action.
 * @see TerminateInstancesRequest
 */
TerminateInstancesResult terminate(TerminateInstancesRequest request);
 
Example #28
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Terminate</code> action and use a ResultCapture to
 * retrieve the low-level client response.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Instance</code> resource, and any conflicting parameter value set
 * in the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>InstanceIds.0</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The response of the low-level client operation associated with
 *         this resource action.
 * @see TerminateInstancesRequest
 */
TerminateInstancesResult terminate(TerminateInstancesRequest request,
        ResultCapture<TerminateInstancesResult> extractor);