Example usage for com.amazonaws.services.ec2.model InstanceStateName ShuttingDown

List of usage examples for com.amazonaws.services.ec2.model InstanceStateName ShuttingDown

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model InstanceStateName ShuttingDown.

Prototype

InstanceStateName ShuttingDown

To view the source code for com.amazonaws.services.ec2.model InstanceStateName ShuttingDown.

Click Source Link

Usage

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Waits until the instance has entered a running state.
 *
 * @param ec2InstanceId the EC2 instance id
 * @return true if the instance has entered a running state, false if the instance is shutting down/terminated or
 *         the function has timed out waiting for the instance to enter one of these two states.
 *///from  w  w  w. java2  s . co m
private boolean waitUntilInstanceHasStarted(String ec2InstanceId) throws InterruptedException {
    // TODO: Add a timeout to this loop.
    while (true) {
        DescribeInstanceStatusResult result = client.describeInstanceStatus(new DescribeInstanceStatusRequest()
                .withIncludeAllInstances(true).withInstanceIds(ec2InstanceId));

        for (InstanceStatus status : result.getInstanceStatuses()) {
            InstanceStateName currentState = InstanceStateName.fromValue(status.getInstanceState().getName());

            if (ec2InstanceId.equals(status.getInstanceId())) {
                if (currentState.equals(InstanceStateName.Terminated)
                        || currentState.equals(InstanceStateName.ShuttingDown)) {
                    LOG.error("Instance {} has unexpectedly terminated", ec2InstanceId);
                    return false;
                } else if (!currentState.equals(InstanceStateName.Pending)) {
                    return true;
                }
            }
        }

        TimeUnit.SECONDS.sleep(5);
    }
}

From source file:com.lunabeat.dooper.HadoopCluster.java

License:Apache License

public RunInstancesResult launchSlaves(int howMany, String size) throws IOException, MasterTimeoutException {
    update();//w ww  .j a  v a 2s .  c om
    if (_master == null) {
        return null;
    }
    InstanceStateName masterState = InstanceStateName.fromValue(_master.getInstance().getState().getName());
    if ((InstanceStateName.Terminated == masterState) || (InstanceStateName.ShuttingDown == masterState)) {
        return null;
    }

    //wait for master to get internal ip field to pass in userinfo
    boolean success = false;
    if (InstanceStateName.Pending == InstanceStateName.fromValue(_master.getInstance().getState().getName())) {
        int attempts = 0;
        while ((attempts < WAIT_FOR_MASTER_MAX_TIMES) && !success) {
            update();
            String pDns = _master.getInstance().getPrivateDnsName();
            if (pDns == null || pDns.length() < 6) {
                try {
                    Thread.sleep(WAIT_FOR_MASTER_INTERVAL_SECONDS * 1000);
                } catch (InterruptedException ie) {
                    return null;
                }
                attempts++;
            } else {
                success = true;
            }
        }
        if (!success) {
            throw new MasterTimeoutException(_groupName, howMany, size, _master.getInstance().getInstanceId());
        }
    }

    String AMIImage = _config.get("AMI." + size + ".Image", _config.get(ClusterConfig.DEFAULT_AMI_KEY));
    RunInstancesRequest rir = new RunInstancesRequest().withImageId(AMIImage).withMinCount(howMany)
            .withMaxCount(howMany).withInstanceType(size).withSecurityGroups(_groupName)
            .withUserData(Base64.encodeBase64String(getUserData().getBytes()))
            .withKeyName(_config.get(ClusterConfig.KEYPAIR_NAME_KEY));
    return _ec2.runInstances(rir);
}

From source file:eu.optimis.interopt.provider.aws.AmazonClient.java

License:Apache License

@Override
public void terminate(String serviceId) throws UnknownServiceException {

    AmazonEC2 ec2 = getAmazonEC2Client();
    log.info("Terminating service...");

    List<VMProperties> vms = queryServiceProperties(serviceId);
    List<String> instances = new ArrayList<String>();
    for (VMProperties vm : vms) {
        if (!(vm.getStatus().equals(InstanceStateName.Terminated.toString())
                || vm.getStatus().equals(InstanceStateName.ShuttingDown.toString()))) {
            instances.add(vm.getId());/*w w  w. j a  v  a 2  s. c o  m*/
            log.debug("Instance to stop: " + vm.getId());
        }
    }

    if (instances.size() == 0) {
        log.info("There are no instances to be terminated!");
        return;
    }

    TerminateInstancesRequest req = new TerminateInstancesRequest(instances);
    try {
        ec2.terminateInstances(req);
    } catch (AmazonServiceException e) {
        log.error("Service termination has failed: ");
        log.error(printServiceException(e));
        throw new UnknownServiceException("Service termination has failed: " + e.getMessage());
    }
}

From source file:eu.optimis.interopt.provider.aws.AmazonClient.java

License:Apache License

public boolean isDeployed(String serviceId) {
    List<VMProperties> vms = new ArrayList<VMProperties>();
    try {//w w w.j av a 2  s.co  m
        vms = queryServiceProperties(serviceId);
    } catch (UnknownServiceException e) {
        return false;
    }
    for (VMProperties vm : vms) {
        //System.out.println(vm.getStatus() + " - " + InstanceStateName.Terminated.toString());
        if (!(vm.getStatus().equals(InstanceStateName.Terminated.toString())
                || vm.getStatus().equals(InstanceStateName.ShuttingDown.toString()))) {
            return true;
        }
    }
    return false;
}

From source file:fr.xebia.cloud.amazon.aws.tools.AmazonAwsUtils.java

License:Apache License

/**
 * <p>//w  ww  . j a  v a  2 s.c  o  m
 * Wait for the ec2 instance startup and returns it up to date
 * </p>
 * <p>
 * Note: some information are missing of the {@link Instance} returned by
 * {@link AmazonEC2#describeInstances(DescribeInstancesRequest)} as long as
 * the instance is not "running" (e.g. {@link Instance#getPublicDnsName()}).
 * </p>
 *
 * @param instance
 * @return up to date instances or <code>null</code> if the instance crashed
 *         at startup.
 */
@Nullable
public static Instance awaitForEc2Instance(@Nonnull Instance instance, @Nonnull AmazonEC2 ec2) {
    logger.trace("Wait for startup of {}: {}", instance.getInstanceId(), instance);

    try {
        // initially wait for 3 secs to prevent "InvalidInstanceID.NotFound, AWS Error Message: The instance ID 'i-2f79c967' does not exist"
        Thread.sleep(3 * 1000);
    } catch (InterruptedException e) {
        throw Throwables.propagate(e);
    }

    int counter = 0;
    while (InstanceStateName.Pending.equals(instance.getState()) || (instance.getPublicIpAddress() == null)
            || (instance.getPublicDnsName() == null)) {
        logger.trace("Wait for startup of {}: {}", instance.getInstanceId(), instance);
        try {
            // 3s because ec2 instance creation < 10 seconds
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            throw Throwables.propagate(e);
        }
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                .withInstanceIds(instance.getInstanceId());
        DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);

        instance = Iterables.getOnlyElement(toEc2Instances(describeInstances.getReservations()));
        counter++;
        if (counter >= 20) {
            logger.warn("Timeout waiting for startup of {}: {}", instance);
            return instance;
        }
    }

    if (InstanceStateName.ShuttingDown.equals(instance.getState())
            || InstanceStateName.Terminated.equals(instance.getState())) {
        // typically a "Server.InternalError: Internal error on launch"
        logger.warn("Terminate and skip dying instance {} (stateReason={}, stateTransitionReason={}): {}",
                new Object[] { instance.getInstanceId(), instance.getStateReason(),
                        instance.getStateTransitionReason(), instance });
        try {
            ec2.terminateInstances(new TerminateInstancesRequest(Lists.newArrayList(instance.getInstanceId())));
        } catch (Exception e) {
            logger.warn("Silently ignore exception terminating dying instance {}: {}",
                    new Object[] { instance.getInstanceId(), instance, e });
        }

        return null;
    }

    logger.debug("Instance {} is started: {}", instance.getInstanceId(), instance);
    return instance;
}

From source file:org.excalibur.service.aws.ec2.EC2.java

License:Open Source License

/**
 * <p>/*w  w  w .  j  av a2  s  .  com*/
 * Wait for the ec2 instances starting up and returns it up to date.
 * </p>
 * <p>
 * Note: some information are missing of the {@link Instance} returned by {@link AmazonEC2#describeInstances(DescribeInstancesRequest)} as long as
 * the instance is not "running" (e.g., {@link Instance#getPublicDnsName()}).
 * </p>
 * 
 * @param instanceToWaitRunningState
 * @return up to date instances or <code>null</code> if the instance crashed at startup.
 */
private Instance waitForInstanceRunningState(final Instance instanceToWaitRunningState) {
    Instance instance = instanceToWaitRunningState;

    int counter = 0;

    while (InstanceStateName.Pending.name().equalsIgnoreCase(instance.getState().getName())) //|| (instance.getPublicIpAddress() == null) || (instance.getPublicDnsName() == null)
    {
        String description = String.format("Waiting running state of the instance [%s]: [%s]",
                instance.getInstanceId(), instance);

        backoffForAttempt(counter + 1, description);

        instance = describeEC2Instance(instance.getInstanceId());
        counter++;

        if (counter >= MAX_RETRY_STATE) {
            LOG.warn("Timeout waiting for startup of [{}]: [{}]", instance.getInstanceId(),
                    instanceToWaitRunningState);
            return instanceToWaitRunningState;
        }
    }

    if (InstanceStateName.ShuttingDown.equals(instance.getState())
            || InstanceStateName.Terminated.equals(instance.getState())) {
        LOG.warn(
                "Terminating and skipping dying instance [{}] (stateReason=[{}], stateTransitionReason=[{}]): [{}]",
                instance.getInstanceId(), instance.getStateReason(), instance.getStateTransitionReason(),
                instance);

        this.terminateInstances(instance.getInstanceId());
        return null;
    }

    LOG.debug("Instance {} is running", instance.getInstanceId());
    return instance;
}