Example usage for com.amazonaws.services.cloudformation.model StackEvent getResourceStatus

List of usage examples for com.amazonaws.services.cloudformation.model StackEvent getResourceStatus

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudformation.model StackEvent getResourceStatus.

Prototype


public String getResourceStatus() 

Source Link

Document

Current status of the resource.

Usage

From source file:com.carrotgarden.maven.aws.cfn.CarrotCloudForm.java

License:BSD License

private void printStackEvents() {

    final DescribeStackEventsRequest request = new DescribeStackEventsRequest();

    request.withStackName(name);//ww  w  .  j ava2  s.  c o  m

    final DescribeStackEventsResult describeStackEvents = amazonClient.describeStackEvents(request);

    final List<StackEvent> stackEvents = describeStackEvents.getStackEvents();

    Collections.reverse(stackEvents);

    logger.info("stack events:");

    for (final StackEvent event : stackEvents) {

        final StringBuilder text = new StringBuilder(128);

        text.append("\n\t");
        text.append("time=");
        text.append(event.getTimestamp());

        text.append("\n\t");
        text.append("id=");
        text.append(event.getEventId());

        text.append("\n\t");
        text.append("type=");
        text.append(event.getResourceType());

        text.append("\n\t");
        text.append("status=");
        text.append(event.getResourceStatus());

        text.append("\n\t");
        text.append("reason=");
        text.append(event.getResourceStatusReason());

        logger.info("event {}", text);

    }

}

From source file:com.deploymentio.cfnstacker.CloudFormationClient.java

License:Apache License

/**
 * Gets all non-progress events for stack that were generated after a
 * certain time. This method will ignore any "throttling" error from AWS and
 * return empty results.//  w w  w  .  j  av  a  2  s  .c o  m
 * 
 * @param stackId unique ID for the stack
 * @param startDate only events after this time are considered
 * @return a list of stack events
 */
public List<StackEvent> getStackEvents(String stackId, Date startDate, OperationTracker tracker,
        int checkIntervalSeconds) {

    ArrayList<StackEvent> events = new ArrayList<StackEvent>();
    DescribeStackEventsResult result = null;
    String nextToken = null;

    doLoop: do {
        try {
            result = client.describeStackEvents(new DescribeStackEventsRequest().withStackName(stackId));
        } catch (AmazonServiceException ase) {
            if ("Throttling".equals(ase.getErrorCode())) {
                logger.warn("Got a throttling error from AWS while calling describeStackEvents()");
                break;
            } else {
                throw ase;
            }
        }
        nextToken = result.getNextToken();

        for (StackEvent evt : result.getStackEvents()) {

            // break out if we start seeing events older than our start date
            if (!evt.getTimestamp().after(startDate)) {
                if (logger.isTraceEnabled()) {
                    logger.trace(createStackEventLogMessage(evt, startDate, "Saw event older than startdate"));
                }
                break doLoop;
            }

            // mark that an event was generated
            if (tracker != null) {
                tracker.markEventsGenerated(stackId);
            }

            // ignore IN_PROGRESS events
            if (!evt.getResourceStatus().endsWith("_IN_PROGRESS")) {
                if (logger.isTraceEnabled()) {
                    logger.trace(createStackEventLogMessage(evt, startDate, "Adding event"));
                }
                events.add(evt);
            } else {
                if (logger.isTraceEnabled()) {
                    logger.trace(createStackEventLogMessage(evt, startDate, "Ignorning event"));
                }
            }

            // start tracking a sub-stack if we come across one
            if (tracker != null && evt.getResourceType().equals("AWS::CloudFormation::Stack")
                    && !evt.getPhysicalResourceId().equals(stackId)) {
                tracker.track(this, evt.getLogicalResourceId(), evt.getPhysicalResourceId(),
                        checkIntervalSeconds);
            }
        }

    } while (!StringUtils.isEmpty(nextToken));

    // sort the events
    Collections.sort(events, new Comparator<StackEvent>() {
        @Override
        public int compare(StackEvent e1, StackEvent e2) {
            return e1.getTimestamp().compareTo(e2.getTimestamp());
        }
    });

    return events;
}

From source file:com.deploymentio.cfnstacker.CloudFormationClient.java

License:Apache License

private String createStackEventLogMessage(StackEvent evt, Date startDate, String message) {
    return message + ": StartDate=" + DateUtils.formatISO8601Date(startDate) + " EventStatus="
            + evt.getResourceStatus() + " EventDate=" + DateUtils.formatISO8601Date(evt.getTimestamp())
            + " EventId=" + evt.getEventId() + " EventResourceId=" + evt.getLogicalResourceId()
            + " EventResourceType=" + evt.getResourceType();
}

From source file:com.deploymentio.cfnstacker.OperationTracker.java

License:Apache License

/**
 * Adds a new ongoing stack operation to track. If a task (based on
 * taskName) is already tracked, it is silently ignored.
 * // w  w w  .j a  v a2s . c o  m
 * @param client
 *            the CFN client
 * @param stackName
 *            stack name
 * @param stackId
 *            stack ID
 * @param checkIntervalSeconds
 *            how often to check the stack operation's progress
 */
public OperationTracker track(final CloudFormationClient client, final String stackName, final String stackId,
        final int checkIntervalSeconds) {

    if (stackNames.add(stackName)) {
        logger.debug("Tracking Stack: Name=" + stackName + " ID=" + stackId);
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // set the time to be a minute in the past - this is to account for any
                // time differences between the local clock and clock on CFN servers
                Date startTime = new Date(System.currentTimeMillis() - 60000);
                while (true) {

                    if (logger.isTraceEnabled()) {
                        logger.trace(
                                "Waiting for completion: StartDate=" + DateUtils.formatISO8601Date(startTime));
                    }

                    // display all events and look for the final event for the stack itself
                    boolean getOutLater = false;
                    for (StackEvent evt : client.getStackEvents(stackId, startTime, OperationTracker.this,
                            checkIntervalSeconds)) {

                        if (evt.getResourceType().equals("AWS::CloudFormation::Stack")) {

                            if (evt.getPhysicalResourceId().equals(stackId)) {
                                getOutLater = true;
                            }
                        }

                        // record the latest timestamp
                        if (evt.getTimestamp().after(startTime))
                            startTime = evt.getTimestamp();

                        if (logger.isDebugEnabled()) {
                            logger.info("EventDate=" + DateUtils.formatISO8601Date(evt.getTimestamp())
                                    + " Stack=" + stackName + " Type=" + evt.getResourceType() + " ID="
                                    + evt.getLogicalResourceId() + " Status=" + evt.getResourceStatus());
                        } else {
                            logger.info("Stack=" + stackName + " Type=" + evt.getResourceType() + " ID="
                                    + evt.getLogicalResourceId() + " Status=" + evt.getResourceStatus());
                        }
                    }

                    if (getOutLater) {
                        break;
                    } else {
                        Thread.sleep(checkIntervalSeconds * 1000);
                    }
                }

                return stackId;
            }
        });
        trackerRecords.put(stackId, new ProgressTrackerRecord(stackName, future));
    } else {
        logger.trace("Ignoring Stack: Name=" + stackName);
    }

    return this;
}

From source file:com.nike.cerberus.service.CloudFormationService.java

License:Apache License

/**
 * Blocking call that waits for a stack change to complete.  Times out if waiting more than 30 minutes.
 *
 * @param endStatuses Status to end on//  ww  w  .  j  av  a2 s . c  om
 * @return The final status
 */
public StackStatus waitForStatus(final String stackId, final HashSet<StackStatus> endStatuses) {
    DateTime now = DateTime.now(DateTimeZone.UTC).minusSeconds(10);
    DateTime timeoutDateTime = now.plusMinutes(90);
    Set<String> recordedStackEvents = Sets.newHashSet();
    boolean isRunning = true;
    StackStatus stackStatus = null;

    while (isRunning) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            logger.warn("Thread sleep interrupted. Continuing...", e);
        }
        stackStatus = getStackStatus(stackId);

        if (endStatuses.contains(stackStatus) || stackStatus == null) {
            isRunning = false;
        }

        if (stackStatus != null) {
            List<StackEvent> stackEvents = getStackEvents(stackId);
            stackEvents.sort((o1, o2) -> o1.getTimestamp().compareTo(o2.getTimestamp()));

            for (StackEvent stackEvent : stackEvents) {
                DateTime eventTime = new DateTime(stackEvent.getTimestamp());
                if (!recordedStackEvents.contains(stackEvent.getEventId()) && now.isBefore(eventTime)) {
                    logger.info(String.format("TS: %s, Status: %s, Type: %s, Reason: %s",
                            Chalk.on(stackEvent.getTimestamp().toString()).yellow(),
                            getStatusColor(stackEvent.getResourceStatus()),
                            Chalk.on(stackEvent.getResourceType()).yellow(),
                            Chalk.on(stackEvent.getResourceStatusReason()).yellow()));

                    recordedStackEvents.add(stackEvent.getEventId());
                }
            }
        }

        if (timeoutDateTime.isBeforeNow()) {
            logger.error("Timed out waiting for CloudFormation completion status.");
            isRunning = false;
        }
    }

    return stackStatus;
}

From source file:de.taimos.pipeline.aws.cloudformation.EventPrinter.java

License:Apache License

private void printEvent(SimpleDateFormat sdf, StackEvent event) {
    String time = this.padRight(sdf.format(event.getTimestamp()), 25);
    String logicalResourceId = this.padRight(event.getLogicalResourceId(), 20);
    String resourceStatus = this.padRight(event.getResourceStatus(), 36);
    String resourceStatusReason = this.padRight(event.getResourceStatusReason(), 140);
    this.listener.getLogger().format("| %s | %s | %s | %s |%n", time, logicalResourceId, resourceStatus,
            resourceStatusReason);/*from   w  w w . j  a  v  a 2 s. com*/
}

From source file:io.konig.maven.CreateCloudFormationStackAction.java

License:Apache License

private List<Output> getOutputForRequest(String stackName, AmazonCloudFormation client)
        throws InterruptedException, StackCreationException {
    int tried = 0;
    String maxTime = System.getProperty("stackMaxTime");
    while (tried < (maxTime == null ? 1800 : Integer.parseInt(maxTime))) {
        DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
        describeStacksRequest.withStackName(stackName);
        Stack resultStack = client.describeStacks(describeStacksRequest).getStacks().get(0);
        StackStatus stackStatus = StackStatus.valueOf(resultStack.getStackStatus());
        if (("CREATE_COMPLETE").equals(stackStatus.toString())) {
            return resultStack.getOutputs();
        } else if (stackStatus.toString().endsWith("IN_PROGRESS")) {
            Thread.sleep(10000);/* w ww  .  jav a 2s.  com*/
        } else {
            DescribeStackEventsRequest describeStackEventsRequest = new DescribeStackEventsRequest();
            describeStackEventsRequest.withStackName(stackName);
            List<StackEvent> stackEvents = client.describeStackEvents(describeStackEventsRequest)
                    .getStackEvents();
            List<StackEvent> errorEvents = new ArrayList<StackEvent>();
            for (StackEvent stackEvent : stackEvents) {
                if (stackEvent.getResourceStatus().equals("CREATE_FAILED")) {
                    errorEvents.add(stackEvent);
                }
            }
            throw new StackCreationException(errorEvents.toString());
        }
        tried++;
    }
    throw new RuntimeException("stack creation/deletion timed out");
}