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

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

Introduction

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

Prototype

InstanceStateName Pending

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

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   ww w.ja  v a2 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 launchMaster(String size) throws IOException {
    update();/*from  w  w  w.ja  va  2 s . co  m*/
    if ((_master != null) && ((InstanceStateName.Running == InstanceStateName
            .fromValue(_master.getInstance().getState().getName()))
            || (InstanceStateName.Pending == InstanceStateName
                    .fromValue(_master.getInstance().getState().getName())))) {
        Reservation masterReservation = _ec2
                .describeInstances(
                        new DescribeInstancesRequest().withInstanceIds(_master.getInstance().getInstanceId()))
                .getReservations().get(0);
        return new RunInstancesResult().withReservation(masterReservation);
    }
    //make the groups
    createSecurityGroups();
    String AMIImage = _config.get("AMI." + size + ".Image", _config.get(ClusterConfig.DEFAULT_AMI_KEY));
    LOGGER.info("AMIImage = [" + AMIImage + "]");
    RunInstancesRequest rir = new RunInstancesRequest().withImageId(AMIImage).withMinCount(1).withMaxCount(1)
            .withInstanceType(size).withSecurityGroups(_masterGroupName)
            .withUserData(Base64.encodeBase64String(getUserData().getBytes()))
            .withKeyName(_config.get(ClusterConfig.KEYPAIR_NAME_KEY));
    return _ec2.runInstances(rir);
}

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

License:Apache License

public RunInstancesResult launchSlaves(int howMany, String size) throws IOException, MasterTimeoutException {
    update();//from w  w  w . j a v a  2  s. co  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:com.lunabeat.dooper.HadoopCluster.java

License:Apache License

/**
 *
 * @param howMany/*w  ww  . j a v a 2  s .co m*/
 * @return result of aws call to terminate
 */
public TerminateInstancesResult terminateSlaves(int howMany) {
    update();
    int terminated = 0;
    ArrayList<String> iids = new ArrayList<String>();
    for (ClusterInstance slave : _slaves) {
        InstanceStateName state = InstanceStateName.fromValue(slave.getInstance().getState().getName());
        if (terminated < howMany
                && (state == InstanceStateName.Running || state == InstanceStateName.Pending)) {
            iids.add(slave.getInstance().getInstanceId());
            terminated++;
        }

    }
    if (iids.size() < 1) {
        return null;
    }
    TerminateInstancesRequest tir = new TerminateInstancesRequest().withInstanceIds(iids);
    return _ec2.terminateInstances(tir);
}

From source file:datameer.awstasks.ant.ec2.Ec2LaunchTask.java

License:Apache License

@Override
public void doExecute(AmazonEC2 ec2) throws BuildException {
    LOG.info("executing " + getClass().getSimpleName() + " with groupName '" + _groupName + "'");
    try {/*from  www  .j  av  a  2s.  c o m*/
        boolean instancesRunning = Ec2Util.findByGroup(ec2, _groupName, false, InstanceStateName.Pending,
                InstanceStateName.Running) != null;
        if (!isReuseRunningInstances() && instancesRunning) {
            throw new IllegalStateException("found already running instances for group '" + _groupName + "'");
        }
        if (!Ec2Util.groupExists(ec2, _groupName)) {
            LOG.info("group '" + _groupName + "' does not exists - creating it");
            String groupDescription = getGroupDescription();
            if (groupDescription == null) {
                throw new BuildException("must specify groupDescription");
            }
            ec2.createSecurityGroup(new CreateSecurityGroupRequest(_groupName, groupDescription));
        }

        List<String> securityGroups = Arrays.asList("default", _groupName);
        List<IpPermission> existingPermissions = Ec2Util.getPermissions(ec2, securityGroups);
        for (GroupPermission groupPermission : _groupPermissions) {
            if (groupPermission.getToPort() == -1) {
                groupPermission.setToPort(groupPermission.getFromPort());
            }
            if (!permissionExists(groupPermission, existingPermissions)) {
                LOG.info("did not found permission '" + groupPermission + "' - creating it...");
                ec2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest()
                        .withGroupName(_groupName).withIpPermissions(groupPermission.toIpPermission()));
            }
        }

        InstanceGroup instanceGroup = new InstanceGroupImpl(ec2);
        RunInstancesRequest launchConfiguration = new RunInstancesRequest(_ami, _instanceCount, _instanceCount);
        if (_kernelId != null) {
            launchConfiguration.setKernelId(_kernelId);
        }
        if (_ramDiskId != null) {
            launchConfiguration.setKernelId(_ramDiskId);
        }
        launchConfiguration.setKeyName(_privateKeyName);
        launchConfiguration.setSecurityGroups(securityGroups);
        if (_userData != null) {
            launchConfiguration.setUserData(Base64.encodeBase64String(_userData.getBytes()));
        }
        if (_instanceType != null) {
            launchConfiguration.setInstanceType(_instanceType);
        }
        launchConfiguration.setPlacement(new Placement(_availabilityZone));
        if (instancesRunning) {
            instanceGroup.connectTo(_groupName);
        } else {
            instanceGroup.launch(launchConfiguration, TimeUnit.MINUTES, _maxStartTime);
            if (_instanceName != null) {
                LOG.info("tagging instances with name '" + _instanceName + " [<idx>]'");
                int idx = 1;
                for (Instance instance : instanceGroup.getInstances(false)) {
                    CreateTagsRequest createTagsRequest = new CreateTagsRequest();
                    createTagsRequest.withResources(instance.getInstanceId()) //
                            .withTags(new Tag("Name", _instanceName + " [" + idx + "]"));
                    ec2.createTags(createTagsRequest);
                    idx++;
                }
            }
        }
    } catch (Exception e) {
        LOG.error("execution " + getClass().getSimpleName() + " with groupName '" + _groupName + "' failed: "
                + e.getMessage());
        throw new BuildException(e);
    }
}

From source file:datameer.awstasks.ant.ec2.Ec2StartTask.java

License:Apache License

@Override
public void execute() throws BuildException {
    System.out.println("executing " + getClass().getSimpleName() + " with groupName '" + _groupName + "'");
    Jec2 ec2 = new Jec2(_accessKey, _accessSecret);
    try {//from  ww w .j  a  va 2 s  . co  m
        boolean instancesRunning = Ec2Util.findByGroup(ec2, _groupName, InstanceStateName.Pending,
                InstanceStateName.Running) != null;
        if (!isReuseRunningInstances() && instancesRunning) {
            throw new IllegalStateException("found already running instances for group '" + _groupName + "'");
        }
        if (!Ec2Util.groupExists(ec2, _groupName)) {
            System.out.println("group '" + _groupName + "' does not exists - creating it");
            String groupDescription = getGroupDescription();
            if (groupDescription == null) {
                throw new BuildException("must specify groupDescription");
            }
            ec2.createSecurityGroup(_groupName, groupDescription);
        }

        List<String> securityGroups = Arrays.asList("default", _groupName);
        List<IpPermission> existingPermissions = Ec2Util.getPermissions(ec2, securityGroups);
        for (GroupPermission groupPermission : _groupPermissions) {
            if (groupPermission.getToPort() == -1) {
                groupPermission.setToPort(groupPermission.getFromPort());
            }
            if (!permissionExists(groupPermission, existingPermissions)) {
                System.out.println("did not found permission '" + groupPermission + "' - creating it...");
                ec2.authorizeSecurityGroupIngress(_groupName, groupPermission.getProtocol(),
                        groupPermission.getFromPort(), groupPermission.getToPort(),
                        groupPermission.getSourceIpOrGroup());
            }
        }

        InstanceGroup instanceGroup = new InstanceGroupImpl(ec2);
        LaunchConfiguration launchConfiguration = new LaunchConfiguration(_ami, _instanceCount, _instanceCount);
        if (_kernelId != null) {
            launchConfiguration.setKernelId(_kernelId);
        }
        if (_ramDiskId != null) {
            launchConfiguration.setKernelId(_ramDiskId);
        }
        launchConfiguration.setKeyName(_privateKeyName);
        launchConfiguration.setSecurityGroup(securityGroups);
        if (_userData != null) {
            launchConfiguration.setUserData(_userData.getBytes());
        }
        if (_instanceType != null) {
            InstanceType instanceType = InstanceType.valueOf(_instanceType.toUpperCase());
            launchConfiguration.setInstanceType(instanceType);
        }
        launchConfiguration.setAvailabilityZone(_availabilityZone);
        if (instancesRunning) {
            instanceGroup.connectTo(_groupName);
        } else {
            instanceGroup.startup(launchConfiguration, TimeUnit.MINUTES, _maxStartTime);
        }
    } catch (Exception e) {
        throw new BuildException(e);
    }
}

From source file:datameer.awstasks.aws.ec2.InstanceGroupImpl.java

License:Apache License

@Override
public void connectTo(String groupName) throws EC2Exception {
    checkEc2Association(false);/*from w w  w . java 2s. co m*/
    LOG.info(String.format("connecting to instances of group '%s'", groupName));
    _reservationDescription = Ec2Util.findByGroup(_ec2, groupName, InstanceStateName.Pending,
            InstanceStateName.Running);
    if (_reservationDescription == null) {
        throw new EC2Exception("no instances of group '" + groupName + "' running");
    }
}

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

License:Apache License

/**
 * <p>/*from  ww  w . ja va 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:fr.xebia.demo.amazon.aws.PetclinicInfrastructureEnforcer.java

License:Apache License

/**
 * <p>/*  ww  w . j av  a  2 s  .  c  o  m*/
 * Wait for the ec2 instances creation and returns a list of
 * {@link Instance} with up to date values.
 * </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 instances
 * @return up to date instances
 */
@Nonnull
public List<Instance> awaitForEc2Instances(@Nonnull Iterable<Instance> instances) {

    List<Instance> result = Lists.newArrayList();
    for (Instance instance : instances) {
        while (InstanceStateName.Pending.equals(instance.getState())) {
            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.getImageId());
            DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);

            instance = Iterables.getOnlyElement(toEc2Instances(describeInstances.getReservations()));
        }
        result.add(instance);
    }
    return result;
}

From source file:fr.xebia.workshop.infrastructureascode.AmazonAwsPetclinicInfrastructureEnforcer.java

License:Apache License

/**
 * <p>/*from  ww w .  java2s. c  o  m*/
 * Wait for the ec2 instances creation and returns a list of
 * {@link Instance} with up to date values.
 * </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 instances
 * @return up to date instances
 */
@Nonnull
public List<Instance> awaitForEc2Instances(@Nonnull Iterable<Instance> instances) {

    List<Instance> result = Lists.newArrayList();
    for (Instance instance : instances) {
        while (InstanceStateName.Pending.equals(instance.getState())) {
            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()));
        }
        result.add(instance);
    }
    return result;
}