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

The following examples show how to use com.amazonaws.services.ec2.model.StopInstancesRequest. 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: AWSControllerIT.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void deactivateInstance() throws Exception {

    parameters.put(PropertyHandler.FLOW_STATE,
            new Setting(PropertyHandler.FLOW_STATE,
                    FlowState.DEACTIVATION_REQUESTED.name()));
    parameters.put(PropertyHandler.OPERATION, new Setting(
            PropertyHandler.OPERATION, Operation.EC2_ACTIVATION.name()));

    ec2mock.createDescribeInstancesResult("instance1", "stopped", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ec2mock.createDescribeImagesResult(IMAGE_ID);
    ec2mock.createRunInstancesResult(INSTANCE_ID);

    runUntilReady();

    verify(ec2).stopInstances(any(StopInstancesRequest.class));

}
 
Example #2
Source File: AWSControllerIT.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void executeServiceOperation_Stop() throws Exception {

    parameters.put(PropertyHandler.FLOW_STATE, new Setting(
            PropertyHandler.FLOW_STATE, FlowState.STOP_REQUESTED.name()));
    parameters.put(PropertyHandler.OPERATION, new Setting(
            PropertyHandler.OPERATION, Operation.EC2_OPERATION.name()));

    ec2mock.createDescribeInstancesResult("instance1", "stopped", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ec2mock.createDescribeImagesResult(IMAGE_ID);
    ec2mock.createRunInstancesResult(INSTANCE_ID);

    runUntilReady();

    verify(ec2).stopInstances(any(StopInstancesRequest.class));

}
 
Example #3
Source File: StopInstancesExample.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testStopPollingWithSuccess() {
    String status = "Stopped";
    InstanceStatus stopped1 = AwsInstanceStatusMapper.getInstanceStatusByAwsStatus(status);
    int lastStatusCode = 16;
    //given
    mockDescribeInstances(POLLING_LIMIT - 2, status, lastStatusCode);
    ArgumentCaptor<StopInstancesRequest> captorStop = ArgumentCaptor.forClass(StopInstancesRequest.class);

    //then
    List<CloudVmInstanceStatus> result = underTest.stop(authenticatedContext, List.of(), inputList);

    //then
    verify(amazonEC2Client, times(1)).stopInstances(captorStop.capture());
    Assertions.assertTrue(captorStop.getValue().getInstanceIds().size() == inputList.size());
    Assert.assertThat(result, hasItem(allOf(hasProperty("status", is(stopped1)))));
}
 
Example #5
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void awsClientSetup() {
    when(awsClient.getAmazonEC2Client(any(AwsSessionCredentialProvider.class))).thenReturn(amazonEC2Client);
    when(awsClient.getAmazonEC2Client(any(BasicAWSCredentials.class))).thenReturn(amazonEC2Client);
    when(awsClient.getInstanceProfileProvider()).thenReturn(instanceProfileCredentialsProvider);

    CloudContext context = new CloudContext(1L, "context", "AWS", "AWS",
            Location.location(Region.region("region")), "user", "account");
    CloudCredential credential = new CloudCredential("id", "alma",
            Map.of("accessKey", "ac", "secretKey", "secret"), false);
    authenticatedContext = awsAuthenticator.authenticate(context, credential);

    StopInstancesResult stopInstancesResult = new StopInstancesResult();
    StartInstancesResult startInstanceResult = new StartInstancesResult();
    when(amazonEC2Client.stopInstances(any(StopInstancesRequest.class))).thenReturn(stopInstancesResult);
    when(amazonEC2Client.startInstances(any(StartInstancesRequest.class))).thenReturn(startInstanceResult);

    inputList = getCloudInstances();
}
 
Example #6
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example #7
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStopPollingWithFail() {
    mockDescribeInstances(POLLING_LIMIT + 2, "Stopped", 41);
    ArgumentCaptor<StopInstancesRequest> captor = ArgumentCaptor.forClass(StopInstancesRequest.class);

    Assertions.assertThrows(PollerStoppedException.class, () -> underTest.stop(authenticatedContext, List.of(), inputList));
    verify(amazonEC2Client, times(1)).stopInstances(captor.capture());
    Assertions.assertTrue(captor.getValue().getInstanceIds().size() == inputList.size());
}
 
Example #8
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStopSomeInstancesStopped() {
    mockDescribeInstancesOneIsStoppedLastSuccess(POLLING_LIMIT - 2);
    ArgumentCaptor<StopInstancesRequest> captor = ArgumentCaptor.forClass(StopInstancesRequest.class);

    List<CloudVmInstanceStatus> result = underTest.stop(authenticatedContext, List.of(), inputList);
    verify(amazonEC2Client, times(1)).stopInstances(captor.capture());
    Assertions.assertTrue(captor.getValue().getInstanceIds().size() < inputList.size());
    Assert.assertThat(result, hasItem(allOf(hasProperty("status", is(InstanceStatus.STOPPED)))));
}
 
Example #9
Source File: AwsInstanceConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(
        value = SdkClientException.class,
        maxAttemptsExpression = "#{${cb.vm.retry.attempt:15}}",
        backoff = @Backoff(delayExpression = "#{${cb.vm.retry.backoff.delay:1000}}",
                multiplierExpression = "#{${cb.vm.retry.backoff.multiplier:2}}",
                maxDelayExpression = "#{${cb.vm.retry.backoff.maxdelay:10000}}")
)
@Override
public List<CloudVmInstanceStatus> stop(AuthenticatedContext ac, List<CloudResource> resources, List<CloudInstance> vms) {
    return setCloudVmInstanceStatuses(ac, vms, "Stopped",
            (ec2Client, instances) -> ec2Client.stopInstances(new StopInstancesRequest().withInstanceIds(instances)),
            "Failed to send stop request to AWS: ");
}
 
Example #10
Source File: Ec2Util.java    From s3-bucket-loader with Apache License 2.0 5 votes vote down vote up
public void stopInstance(AmazonEC2Client ec2Client, String instanceId) throws Exception {
	StopInstancesRequest stopReq = new StopInstancesRequest();
	List<String> instanceIds = new ArrayList<String>();
	instanceIds.add(instanceId);
	stopReq.setInstanceIds(instanceIds);
	logger.debug("Stopping EC2 instance...." + Arrays.toString(instanceIds.toArray(new String[]{})));
	ec2Client.stopInstances(stopReq);
}
 
Example #11
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public StopInstancesResult stop(ResultCapture<StopInstancesResult> extractor
        ) {

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

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

    if (result == null) return null;
    return (StopInstancesResult) result.getData();
}
 
Example #13
Source File: AwsInstanceProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #14
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testStopInstance() throws Exception {
    ec2comm.stopInstance("instance1");
    ArgumentCaptor<StopInstancesRequest> arg1 = ArgumentCaptor
            .forClass(StopInstancesRequest.class);
    verify(ec2).stopInstances(arg1.capture());
    StopInstancesRequest val = arg1.getValue();

    assertEquals(1, val.getInstanceIds().size());
    assertEquals("instance1", val.getInstanceIds().get(0));
}
 
Example #15
Source File: EC2ProcessorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void process_STOP_REQUESTED() throws Exception {
    // given
    ph.setOperation(Operation.EC2_OPERATION);
    ph.setState(FlowState.STOP_REQUESTED);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertFalse(result.isReady());
    assertEquals(FlowState.STOPPING, ph.getState());
    verify(ec2).stopInstances(any(StopInstancesRequest.class));
}
 
Example #16
Source File: EC2ProcessorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void process_DEACTIVATION_REQUESTED() throws Exception {
    // given
    ph.setOperation(Operation.EC2_ACTIVATION);
    ph.setState(FlowState.DEACTIVATION_REQUESTED);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertFalse(result.isReady());
    assertEquals(FlowState.STOPPING, ph.getState());
    verify(ec2).stopInstances(any(StopInstancesRequest.class));
}
 
Example #17
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public StopInstancesResult stop(StopInstancesRequest request) {
    return stop(request, null);
}
 
Example #18
Source File: EC2Application.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {
   
    // Set up the client
    AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion(Regions.US_EAST_1)
        .build();

    // Create a security group
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
        .withDescription("Baeldung Security Group");
    ec2Client.createSecurityGroup(createSecurityGroupRequest);

    // Allow HTTP and SSH traffic
    IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");

    IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(80)
        .withToPort(80);

    IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(22)
        .withToPort(22);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
        .withGroupName("BaeldungSecurityGroup")
        .withIpPermissions(ipPermission1, ipPermission2);

    ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    // Create KeyPair
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
        .withKeyName("baeldung-key-pair");
    CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
    String privateKey = createKeyPairResult
        .getKeyPair()
        .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key

    // See what key-pairs you've got
    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);

    // Launch an Amazon Instance
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
        .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
        .withSecurityGroups("BaeldungSecurityGroup");

    String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();

    // Start an Instance
    StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.startInstances(startInstancesRequest);

    // Monitor Instances
    MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.monitorInstances(monitorInstancesRequest);

    UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.unmonitorInstances(unmonitorInstancesRequest);

    // Reboot an Instance

    RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.rebootInstances(rebootInstancesRequest);

    // Stop an Instance
    StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.stopInstances(stopInstancesRequest)
        .getStoppingInstances()
        .get(0)
        .getPreviousState()
        .getName();

    // Describe an Instance
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
    System.out.println(response.getReservations()
        .get(0)
        .getInstances()
        .get(0)
        .getKernelId());
}
 
Example #19
Source File: EC2Communication.java    From development with Apache License 2.0 4 votes vote down vote up
public void stopInstance(String instanceId) {
    getEC2().stopInstances(
            new StopInstancesRequest().withInstanceIds(instanceId));
}
 
Example #20
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Stop</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 StopInstancesRequest
 */
StopInstancesResult stop(StopInstancesRequest request,
        ResultCapture<StopInstancesResult> extractor);
 
Example #21
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Stop</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 StopInstancesRequest
 */
StopInstancesResult stop(StopInstancesRequest request);