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

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

Introduction

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

Prototype

InstanceStateName Terminated

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

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.
 */// w w  w .j  a  v  a  2s  .  c om
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();//from   ww  w.  j  a  va 2 s. c o m
    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 List<VMProperties> queryServiceProperties(String serviceId) throws UnknownServiceException {

    List<VMProperties> list = null;

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

    List<String> sids = new ArrayList<String>();
    sids.add(serviceId);//from  ww w .ja v  a 2 s.com
    Filter filt = new Filter("tag:serviceid", sids);
    List<Filter> filters = new ArrayList<Filter>();
    filters.add(filt);
    DescribeInstancesRequest req = new DescribeInstancesRequest();
    req.setFilters(filters);
    try {
        DescribeInstancesResult res = ec2.describeInstances(req);

        List<Instance> instances = new ArrayList<Instance>();
        for (Reservation r : res.getReservations()) {
            instances.addAll(r.getInstances());
        }
        log.info("#VMs found: " + instances.size());
        list = new ArrayList<VMProperties>();
        for (Instance inst : instances) {
            String status = inst.getState().getName().toString();
            if (!status.equals(InstanceStateName.Terminated.toString())) {
                VMProperties prop = new VMProperties();
                prop.setId(inst.getInstanceId());
                prop.setStatus(inst.getState().getName().toString());
                prop.setHostname(inst.getPublicDnsName());
                prop.setIp(inst.getPublicIpAddress());
                prop.put(VMProperties.AWS_INSTANCE_TYPE, inst.getInstanceType());
                list.add(prop);
            }

        }
    } catch (AmazonServiceException e) {
        log.error("Service query has failed: ");
        log.error(printServiceException(e));
        throw new UnknownServiceException("Service query has failed: " + e.getMessage());
    }

    return list;
}

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());//from   w w w. ja  v a  2  s  .com
            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 ww  .ja  va 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>/*www  .  j a  v  a  2s.  c om*/
 * 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:hudson.plugins.ec2.EC2AbstractSlave.java

License:Open Source License

protected boolean isAlive(boolean force) {
    fetchLiveInstanceData(force);//from   ww w  .  j a v a2  s  . co m
    if (lastFetchInstance == null)
        return false;
    if (lastFetchInstance.getState().getName().equals(InstanceStateName.Terminated.toString()))
        return false;
    return true;
}

From source file:jp.primecloud.auto.process.aws.AwsCommonProcess.java

License:Open Source License

public Instance waitInstance(AwsProcessClient awsProcessClient, String instanceId) {
    // ???/*w w  w  .j a  v  a 2 s . c  o  m*/
    Instance instance;
    while (true) {
        try {
            Thread.sleep(1000L * awsProcessClient.getDescribeInterval());
        } catch (InterruptedException ignore) {
        }

        instance = describeInstance(awsProcessClient, instanceId);
        InstanceStateName state;
        try {
            state = InstanceStateName.fromValue(instance.getState().getName());
        } catch (IllegalArgumentException e) {
            // ???
            AutoException exception = new AutoException("EPROCESS-000104", instanceId,
                    instance.getState().getName());
            exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance));
            throw exception;
        }

        // ?????
        if (state == InstanceStateName.Running || state == InstanceStateName.Terminated
                || state == InstanceStateName.Stopped) {
            break;
        }
    }

    return instance;
}

From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java

License:Open Source License

public void waitTerminate(AwsProcessClient awsProcessClient, Long instanceNo) {
    AwsInstance awsInstance = awsInstanceDao.read(instanceNo);
    String instanceId = awsInstance.getInstanceId();

    // ??//from w ww.  jav  a  2s.com
    com.amazonaws.services.ec2.model.Instance instance;
    try {
        instance = awsCommonProcess.waitInstance(awsProcessClient, instanceId);

        if (!StringUtils.equals(instance.getState().getName(), InstanceStateName.Terminated.toString())) {
            // 
            AutoException exception = new AutoException("EPROCESS-000109", instanceId,
                    instance.getState().getName());
            exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance));
            throw exception;
        }
    } catch (AutoException e) {
        // ????????????????
        if ("EPROCESS-000101".equals(e.getCode())) {
            instance = null;
        } else {
            throw e;
        }
    }

    // 
    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100118", instanceId));
    }

    // 
    Instance instance2 = instanceDao.read(instanceNo);
    processLogger.debug(null, instance2, "AwsInstanceDeleteFinish",
            new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId });

    String status = null;
    if (instance != null) {
        status = instance.getState().getName();
    }

    // 
    awsInstance.setInstanceId(null);
    awsInstance.setStatus(status);
    awsInstance.setDnsName(null);
    awsInstance.setPrivateDnsName(null);
    awsInstance.setIpAddress(null);
    awsInstance.setPrivateIpAddress(null);
    awsInstanceDao.update(awsInstance);
}

From source file:jp.primecloud.auto.process.aws.AwsProcess.java

License:Open Source License

/**
 * TODO: /*from   ww w .  j  a v  a2s .c om*/
 * 
 * @param instanceNo
 */
public void start(Long instanceNo) {
    Instance instance = instanceDao.read(instanceNo);
    Farm farm = farmDao.read(instance.getFarmNo());

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100101", instanceNo, instance.getInstanceName()));
    }

    // AwsProcessClient??
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(farm.getUserNo(),
            instance.getPlatformNo());

    // ???
    int retryCount = 1; // ??
    for (int i = 0; i <= retryCount; i++) {
        try {
            awsInstanceProcess.startInstance(awsProcessClient, instanceNo);
            break;

        } catch (AutoException e) {
            if (i < retryCount) {
                // RunInstances??????????????????
                // TODO: ?ID???????????????
                if ("EPROCESS-000106".equals(e.getCode())) {
                    String instanceId = (String) e.getAdditions()[0];

                    try {
                        // ??
                        com.amazonaws.services.ec2.model.Instance instance2 = awsCommonProcess
                                .describeInstance(awsProcessClient, instanceId);

                        if (InstanceStateName.Terminated.toString().equals(instance2.getState().getName())
                                && "Server.InternalError".equals(instance2.getStateTransitionReason())) {
                            // ????
                            log.warn(e.getMessage());

                            // ?ID
                            AwsInstance awsInstance = awsInstanceDao.read(instanceNo);
                            awsInstance.setInstanceId(null);
                            awsInstanceDao.update(awsInstance);

                            continue;
                        }
                    } catch (Exception ignore) {
                    }
                }
            }

            throw e;
        }
    }

    // ???
    List<AwsVolume> awsVolumes = awsVolumeDao.readByInstanceNo(instanceNo);
    for (AwsVolume awsVolume : awsVolumes) {
        if (awsVolume.getComponentNo() != null) {
            // ???????
            continue;
        }
        awsVolumeProcess.startVolume(awsProcessClient, instanceNo, awsVolume.getVolumeNo());
    }

    // ???
    awsAddressProcess.startAddress(awsProcessClient, instanceNo);

    // DNS???
    awsDnsProcess.startDns(instanceNo);

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100102", instanceNo, instance.getInstanceName()));
    }
}