Search in sources :

Example 6 with StopInstancesRequest

use of software.amazon.awssdk.services.ec2.model.StopInstancesRequest in project photon-model by vmware.

the class AWSResetService method reset.

private void reset(AmazonEC2AsyncClient client, ResourceOperationRequest pr, DefaultAdapterContext c) {
    if (!c.child.powerState.equals(ComputeService.PowerState.ON)) {
        logWarning(() -> String.format("Cannot perform a reset on this EC2 instance. " + "The machine should be in powered on state"));
        c.taskManager.patchTaskToFailure(new IllegalStateException("Incorrect power state. Expected the machine " + "to be powered on "));
        return;
    }
    // The stop action for reset is a force stop. So we use the withForce method to set the force parameter to TRUE
    // This is similar to unplugging the machine from the power circuit.
    // The OS and the applications are forcefully stopped.
    StopInstancesRequest stopRequest = new StopInstancesRequest();
    stopRequest.withInstanceIds(c.child.id).withForce(Boolean.TRUE);
    client.stopInstancesAsync(stopRequest, new AWSAsyncHandler<StopInstancesRequest, StopInstancesResult>() {

        @Override
        protected void handleError(Exception e) {
            c.taskManager.patchTaskToFailure(e);
        }

        @Override
        protected void handleSuccess(StopInstancesRequest request, StopInstancesResult result) {
            AWSUtils.waitForTransitionCompletion(getHost(), result.getStoppingInstances(), "stopped", client, (is, e) -> {
                if (e != null) {
                    onError(e);
                    return;
                }
                // Instances will be started only if they're successfully stopped
                startInstance(client, c);
            });
        }
    });
}
Also used : Service(com.vmware.xenon.common.Service) ResourceOperationSpec(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationSpecService.ResourceOperationSpec) ResourceOperationUtils.handleAdapterResourceOperationRegistration(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationUtils.handleAdapterResourceOperationRegistration) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) AWSAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSAsyncHandler) StatelessService(com.vmware.xenon.common.StatelessService) Operation(com.vmware.xenon.common.Operation) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) ServiceDocument(com.vmware.xenon.common.ServiceDocument) BaseAdapterStage(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) ResourceOperationRequest(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationRequest) ResourceOperation(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperation) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) DefaultAdapterContext(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) EndpointType(com.vmware.photon.controller.model.constants.PhotonModelConstants.EndpointType) FactoryService(com.vmware.xenon.common.FactoryService) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) ResourceType(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationSpecService.ResourceType) ResourceOperationUtils(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationUtils) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest)

Example 7 with StopInstancesRequest

use of software.amazon.awssdk.services.ec2.model.StopInstancesRequest in project photon-model by vmware.

the class TestAWSSetupUtils method stopVMsUsingEC2Client.

/**
 * Stop instances on the AWS endpoint for the set of instance Ids that are passed in.
 *
 * @param client
 * @param host
 * @param instanceIdsToStop
 * @throws Throwable
 */
public static void stopVMsUsingEC2Client(AmazonEC2AsyncClient client, VerificationHost host, List<String> instanceIdsToStop) throws Throwable {
    StopInstancesRequest stopRequest = new StopInstancesRequest(instanceIdsToStop);
    AsyncHandler<StopInstancesRequest, StopInstancesResult> stopHandler = new AWSStopHandlerAsync(host);
    client.stopInstancesAsync(stopRequest, stopHandler);
    waitForInstancesToBeStopped(client, host, instanceIdsToStop);
}
Also used : StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest)

Example 8 with StopInstancesRequest

use of software.amazon.awssdk.services.ec2.model.StopInstancesRequest in project aws-doc-sdk-examples by awsdocs.

the class StartStopInstance method stopInstance.

public static void stopInstance(String instance_id) {
    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
    DryRunSupportedRequest<StopInstancesRequest> dry_request = () -> {
        StopInstancesRequest request = new StopInstancesRequest().withInstanceIds(instance_id);
        return request.getDryRunRequest();
    };
    DryRunResult dry_response = ec2.dryRun(dry_request);
    if (!dry_response.isSuccessful()) {
        System.out.printf("Failed dry run to stop instance %s", instance_id);
        throw dry_response.getDryRunResponse();
    }
    StopInstancesRequest request = new StopInstancesRequest().withInstanceIds(instance_id);
    ec2.stopInstances(request);
    System.out.printf("Successfully stop instance %s", instance_id);
}
Also used : StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DryRunResult(com.amazonaws.services.ec2.model.DryRunResult)

Example 9 with StopInstancesRequest

use of software.amazon.awssdk.services.ec2.model.StopInstancesRequest in project tutorials by eugenp.

the class EC2Application method main.

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();
    // See what key-pairs you've got
    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
    // Launch an Amazon Instance
    RunInstancesRequest runInstancesRequest = // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
    new RunInstancesRequest().withImageId("ami-97785bed").withInstanceType(// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
    "t2.micro").withMinCount(1).withMaxCount(1).withKeyName(// optional - if not present, can't connect to instance
    "baeldung-key-pair").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());
}
Also used : IpRange(com.amazonaws.services.ec2.model.IpRange) DescribeKeyPairsRequest(com.amazonaws.services.ec2.model.DescribeKeyPairsRequest) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) DescribeKeyPairsResult(com.amazonaws.services.ec2.model.DescribeKeyPairsResult) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest) CreateSecurityGroupRequest(com.amazonaws.services.ec2.model.CreateSecurityGroupRequest) CreateKeyPairRequest(com.amazonaws.services.ec2.model.CreateKeyPairRequest) MonitorInstancesRequest(com.amazonaws.services.ec2.model.MonitorInstancesRequest) RebootInstancesRequest(com.amazonaws.services.ec2.model.RebootInstancesRequest) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) CreateKeyPairResult(com.amazonaws.services.ec2.model.CreateKeyPairResult) AuthorizeSecurityGroupIngressRequest(com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) IpPermission(com.amazonaws.services.ec2.model.IpPermission) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest) UnmonitorInstancesRequest(com.amazonaws.services.ec2.model.UnmonitorInstancesRequest)

Example 10 with StopInstancesRequest

use of software.amazon.awssdk.services.ec2.model.StopInstancesRequest in project cloudbreak by hortonworks.

the class AwsInstanceConnector method stop.

@Override
public List<CloudVmInstanceStatus> stop(AuthenticatedContext ac, List<CloudResource> resources, List<CloudInstance> vms) {
    List<CloudVmInstanceStatus> statuses = new ArrayList<>();
    AmazonEC2Client amazonEC2Client = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()), ac.getCloudContext().getLocation().getRegion().value());
    for (String group : getGroups(vms)) {
        Collection<String> instances = new ArrayList<>();
        Collection<CloudInstance> cloudInstances = new ArrayList<>();
        for (CloudInstance vm : vms) {
            if (vm.getTemplate().getGroupName().equals(group)) {
                instances.add(vm.getInstanceId());
                cloudInstances.add(vm);
            }
        }
        try {
            instances = removeInstanceIdsWhichAreNotInCorrectState(instances, amazonEC2Client, "Stopped");
            if (!instances.isEmpty()) {
                amazonEC2Client.stopInstances(new StopInstancesRequest().withInstanceIds(instances));
            }
            for (CloudInstance cloudInstance : cloudInstances) {
                statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.IN_PROGRESS));
            }
        } catch (RuntimeException e) {
            LOGGER.error("Stop instances failed on AWS", e);
            String message = e instanceof AmazonEC2Exception ? ((AmazonEC2Exception) e).getErrorCode() : e.getMessage();
            for (CloudInstance cloudInstance : cloudInstances) {
                statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.FAILED, message));
            }
        }
    }
    return statuses;
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView) CloudVmInstanceStatus(com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus) ArrayList(java.util.ArrayList) CloudInstance(com.sequenceiq.cloudbreak.cloud.model.CloudInstance) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception)

Aggregations

StopInstancesRequest (com.amazonaws.services.ec2.model.StopInstancesRequest)10 StopInstancesResult (com.amazonaws.services.ec2.model.StopInstancesResult)6 StartInstancesRequest (com.amazonaws.services.ec2.model.StartInstancesRequest)4 AmazonEC2AsyncClient (com.amazonaws.services.ec2.AmazonEC2AsyncClient)3 StartInstancesResult (com.amazonaws.services.ec2.model.StartInstancesResult)3 AWSClientManager (com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager)3 AWSClientManagerFactory (com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory)3 BaseAdapterStage (com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage)3 DefaultAdapterContext (com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext)3 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)3 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)2 DescribeInstancesRequest (com.amazonaws.services.ec2.model.DescribeInstancesRequest)2 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)2 AWSAsyncHandler (com.vmware.photon.controller.model.adapters.awsadapter.util.AWSAsyncHandler)2 ResourceOperation (com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperation)2 Operation (com.vmware.xenon.common.Operation)2 StatelessService (com.vmware.xenon.common.StatelessService)2 ArrayList (java.util.ArrayList)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 AWSStaticCredentialsProvider (com.amazonaws.auth.AWSStaticCredentialsProvider)1