Example usage for com.amazonaws.services.elasticbeanstalk.model EnvironmentDescription getEnvironmentName

List of usage examples for com.amazonaws.services.elasticbeanstalk.model EnvironmentDescription getEnvironmentName

Introduction

In this page you can find the example usage for com.amazonaws.services.elasticbeanstalk.model EnvironmentDescription getEnvironmentName.

Prototype


public String getEnvironmentName() 

Source Link

Document

The name of this environment.

Usage

From source file:br.com.ingenieux.jenkins.plugins.awsebdeployment.cmd.ZeroDowntime.java

License:Apache License

private EnvironmentDescription lookupEnvironmentIds(List<String> environmentNames)
        throws InvalidEnvironmentsSizeException, InvalidDeploymentTypeException {
    DescribeEnvironmentsResult environments = getAwseb().describeEnvironments(new DescribeEnvironmentsRequest()
            .withApplicationName(getApplicationName()).withIncludeDeleted(false));

    for (EnvironmentDescription env : environments.getEnvironments()) {
        if (environmentNames.contains(env.getEnvironmentName())) {
            if (WORKER_ENVIRONMENT_TYPE.equals(env.getTier().getName())) {
                throw new InvalidDeploymentTypeException();
            }/*from w w  w  . ja  v a  2s  .  c om*/

            return env;
        }
    }

    throw new InvalidEnvironmentsSizeException(getApplicationName(), environmentNames.get(0),
            environments.getEnvironments().size());
}

From source file:br.com.ingenieux.mojo.beanstalk.bg.BluegreenDeploymentMojo.java

License:Apache License

@Override
protected Object executeInternal() throws Exception {
    versionLabel = lookupVersionLabel(applicationName, versionLabel);

    getLog().info(format("Using version %s", versionLabel));

    Collection<EnvironmentDescription> envs = new WaitForEnvironmentCommand(this)
            .lookupInternal(new WaitForEnvironmentContextBuilder().withApplicationName(applicationName)
                    .withEnvironmentRef(environmentNamePrefix + "*").build());

    if (envs.size() > 2) {
        final Collection<String> environmentList = Collections2.transform(envs,
                new Function<EnvironmentDescription, String>() {
                    @Override/*from  w ww.  j  a  va  2s  .c  o  m*/
                    public String apply(EnvironmentDescription input) {
                        return format("%s[%s]", input.getEnvironmentId(), input.getEnvironmentName());
                    }
                });

        String message = "Ooops. There are multiple environments matching the lookup spec: " + environmentList;

        getLog().warn(message);
        getLog().warn("Will pick one at random anyway as long as it uses WebServer tier name");
    }

    String otherEnvId = null;
    for (EnvironmentDescription e : envs) {
        if (!e.getEnvironmentId().equals(curEnv.getEnvironmentId())
                && "WebServer".equals(e.getTier().getName())) {
            otherEnvId = e.getEnvironmentId();
            break;
        }
    }

    getLog().info(
            format("(Green) Environment with environmentId['%s'] will be prepared once its ready to update",
                    curEnv.getEnvironmentId()));

    new WaitForEnvironmentCommand(this).execute(new WaitForEnvironmentContextBuilder()
            .withStatusToWaitFor("Ready").withApplicationName(applicationName)
            .withEnvironmentRef(curEnv.getEnvironmentId()).build());

    getLog().info(
            format("(Blue) Environment with environmentId['%s'] will be prepared once its ready to update",
                    otherEnvId));

    new WaitForEnvironmentCommand(this)
            .execute(new WaitForEnvironmentContextBuilder().withStatusToWaitFor("Ready")
                    .withApplicationName(applicationName).withEnvironmentRef(otherEnvId).build());

    getLog().info(format("(Blue) Updating environmentId to version %s", versionLabel));

    new UpdateEnvironmentCommand(this).execute(new UpdateEnvironmentContextBuilder()
            .withEnvironmentId(otherEnvId).withVersionLabel(versionLabel).build());

    getLog().info(format("(Blue) Waiting for environmentId['%s'] to get ready and green prior to switching",
            otherEnvId));

    new WaitForEnvironmentCommand(this).execute(new WaitForEnvironmentContextBuilder()
            .withStatusToWaitFor("Ready").withApplicationName(applicationName).withHealth("Green")
            .withEnvironmentRef(otherEnvId).build());

    getLog().info(format("Ok. Switching"));

    getService().swapEnvironmentCNAMEs(new SwapEnvironmentCNAMEsRequest()
            .withDestinationEnvironmentId(curEnv.getEnvironmentId()).withSourceEnvironmentId(otherEnvId));

    getLog().info(format("Done."));

    return null; //To change body of implemented methods use File | Settings | File Templates.
}

From source file:br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsCommand.java

License:Apache License

protected boolean isSingleInstance(EnvironmentDescription env) {
    Validate.isTrue("WebServer".equals(env.getTier().getName()), "Not a Web Server environment!");

    final DescribeConfigurationSettingsResult describeConfigurationSettingsResult = parentMojo.getService()
            .describeConfigurationSettings(
                    new DescribeConfigurationSettingsRequest().withApplicationName(env.getApplicationName())
                            .withEnvironmentName(env.getEnvironmentName()));

    Validate.isTrue(1 == describeConfigurationSettingsResult.getConfigurationSettings().size(),
            "There should be one environment");

    final List<ConfigurationOptionSetting> optionSettings = describeConfigurationSettingsResult
            .getConfigurationSettings().get(0).getOptionSettings();

    for (ConfigurationOptionSetting optionSetting : optionSettings) {
        if (ConfigUtil.optionSettingMatchesP(optionSetting, "aws:elasticbeanstalk:environment",
                "EnvironmentType")) {
            return "SingleInstance".equals(optionSetting.getValue());
        }/*from   w ww . j a  v  a 2s.  com*/
    }

    throw new IllegalStateException("Unreachable code!");
}

From source file:br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand.java

License:Apache License

protected List<Predicate<EnvironmentDescription>> getEnvironmentDescriptionPredicate(
        WaitForEnvironmentContext context) {
    // as well as those (which are used as predicate variables, thus being
    // final)/*from   w w w  .  java2 s  .  com*/
    final String environmentRef = context.getEnvironmentRef();
    final String statusToWaitFor = defaultString(context.getStatusToWaitFor(), "!Terminated");
    final String healthToWaitFor = context.getHealth();

    // Sanity Check
    Validate.isTrue(isNotBlank(environmentRef), "EnvironmentRef is blank or null", environmentRef);

    // some argument juggling

    final boolean negated = statusToWaitFor.startsWith("!");

    // argument juggling

    List<Predicate<EnvironmentDescription>> result = new ArrayList<Predicate<EnvironmentDescription>>();

    if (environmentRef.matches("e-\\p{Alnum}{10}")) {
        result.add(new Predicate<EnvironmentDescription>() {
            @Override
            public boolean apply(EnvironmentDescription t) {
                return t.getEnvironmentId().equals(environmentRef);
            }
        });

        info("... with environmentId equal to '%s'", environmentRef);
    } else if (environmentRef.matches(".*\\Q.elasticbeanstalk.com\\E")) {
        result.add(new Predicate<EnvironmentDescription>() {
            @Override
            public boolean apply(EnvironmentDescription t) {
                return defaultString(t.getCNAME()).equals(environmentRef);
            }
        });
        info("... with cname set to '%s'", environmentRef);
    } else {
        String tmpRE = Pattern.quote(environmentRef);

        if (environmentRef.endsWith("*")) {
            tmpRE = format("^\\Q%s\\E.*", environmentRef.substring(0, -1 + environmentRef.length()));
        }

        final String environmentRefNameRE = tmpRE;

        result.add(new Predicate<EnvironmentDescription>() {
            @Override
            public boolean apply(EnvironmentDescription t) {
                return t.getEnvironmentName().matches(environmentRefNameRE);
            }
        });

        info("... with environmentName matching re '%s'", environmentRefNameRE);
    }

    {
        // start building predicates with the status one - "![status]" must
        // be equal to status or not status
        final int offset = negated ? 1 : 0;
        final String vStatusToWaitFor = statusToWaitFor.substring(offset);

        result.add(new Predicate<EnvironmentDescription>() {
            public boolean apply(EnvironmentDescription t) {

                boolean result = vStatusToWaitFor.equals(t.getStatus());

                if (negated) {
                    result = !result;
                }

                debug("testing status '%s' as equal as '%s' (negated? %s, offset: %d): %s", vStatusToWaitFor,
                        t.getStatus(), negated, offset, result);

                return result;
            }
        });

        info("... with status %s set to '%s'", (negated ? "*NOT*" : " "), vStatusToWaitFor);
    }

    {
        if (isNotBlank(healthToWaitFor)) {
            result.add(new Predicate<EnvironmentDescription>() {
                @Override
                public boolean apply(EnvironmentDescription t) {
                    return t.getHealth().equals(healthToWaitFor);
                }
            });

            info("... with health equal to '%s'", healthToWaitFor);
        }
    }
    return result;
}

From source file:br.com.ingenieux.mojo.beanstalk.env.ReplaceEnvironmentMojo.java

License:Apache License

@Override
protected Object executeInternal() throws Exception {
    solutionStack = lookupSolutionStack(solutionStack);

    /*/*from w  ww. ja  va2 s  . com*/
     * Is the desired cname not being used by other environments? If so,
     * just launch the environment
     */
    if (!hasEnvironmentFor(applicationName, cnamePrefix)) {
        if (getLog().isInfoEnabled()) {
            getLog().info("Just launching a new environment.");
        }

        return super.executeInternal();
    }

    /*
       * Gets the current environment using this cname
     */
    EnvironmentDescription curEnv = getEnvironmentFor(applicationName, cnamePrefix);

    if (curEnv.getVersionLabel().equals(versionLabel) && skipIfSameVersion) {
        getLog().warn(format("Environment is running version %s and skipIfSameVersion is true. Returning",
                versionLabel));

        return null;
    }

    /*
         * Decides on a environmentRef, and launches a new environment
     */
    String cnamePrefixToCreate = getCNamePrefixToCreate();

    if (getLog().isInfoEnabled()) {
        getLog().info("Creating a new environment on " + cnamePrefixToCreate + ".elasticbeanstalk.com");
    }

    if (copyOptionSettings) {
        copyOptionSettings(curEnv);
    }

    if (!solutionStack.equals(curEnv.getSolutionStackName()) && copySolutionStack) {
        if (getLog().isWarnEnabled()) {
            getLog().warn(format(
                    "(btw, we're launching with solutionStack/ set to '%s' based on the existing env instead of the "
                            + "default ('%s'). If this is not the desired behavior please set the copySolutionStack property to"
                            + " false.",
                    curEnv.getSolutionStackName(), solutionStack));
        }

        solutionStack = curEnv.getSolutionStackName();
    }

    /**
     * TODO: Spend a comfy Saturday Afternoon in a Coffee Shop trying to figure out this nice boolean logic with Karnaugh Maps sponsored by Allogy
     */

    boolean userWantsHealthyExitStatus = mustBeHealthy;
    final boolean currentEnvironmentIsRed = "Red".equals(curEnv.getHealth());

    if (redToRedOkay) {
        //Side-effect: must be before createEnvironment() and waitForEnvironment() to effect superclass behavior.
        mustBeHealthy = !currentEnvironmentIsRed;
    }

    /**
     * // I really meant it.
     */

    String newEnvironmentName = getNewEnvironmentName(
            StringUtils.defaultString(this.environmentName, curEnv.getEnvironmentName()));

    if (getLog().isInfoEnabled()) {
        getLog().info("And it'll be named " + newEnvironmentName);
        getLog().info("And it will replace a '" + curEnv.getHealth() + "' enviroment");
    }

    CreateEnvironmentResult createEnvResult = createEnvironment(cnamePrefixToCreate, newEnvironmentName);

    /*
       * Waits for completion
     */
    EnvironmentDescription newEnvDesc = null;

    try {
        newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId());
    } catch (Exception exc) {
        /*
         * Terminates the failed launched environment
        */
        terminateEnvironment(createEnvResult.getEnvironmentId());

        handleException(exc);

        return null;
    }

    /*
       * Swaps. Due to beanstalker-25, we're doing some extra logic we
     * actually woudln't want to.
     */
    {
        boolean swapped = false;
        for (int i = 1; i <= maxAttempts; i++) {
            try {
                swapEnvironmentCNames(newEnvDesc.getEnvironmentId(), curEnv.getEnvironmentId(), cnamePrefix,
                        newEnvDesc);
                swapped = true;
                break;
            } catch (Throwable exc) {
                if (exc instanceof MojoFailureException) {
                    exc = Throwable.class.cast(MojoFailureException.class.cast(exc).getCause());
                }

                getLog().warn(format("Attempt #%d/%d failed. Sleeping and retrying. Reason: %s (type: %s)", i,
                        maxAttempts, exc.getMessage(), exc.getClass()));

                sleepInterval(attemptRetryInterval);
            }
        }

        if (!swapped) {
            getLog().info(
                    "Failed to properly Replace Environment. Finishing the new one. And throwing you a failure");

            terminateEnvironment(newEnvDesc.getEnvironmentId());

            String message = "Unable to swap cnames. btw, see https://github.com/ingenieux/beanstalker/issues/25 and help us improve beanstalker";

            getLog().warn(message);

            throw new MojoFailureException(message);
        }
    }

    /*
       * Terminates the previous environment
     */
    terminateEnvironment(curEnv.getEnvironmentId());

    /**
     * TODO: I really need a Saturday Afternoon in order to understand this ffs.
     */
    if (currentEnvironmentIsRed && userWantsHealthyExitStatus) {
        final String newHealth = newEnvDesc.getHealth();

        if (newHealth.equals("Green")) {
            getLog().info("Previous environment was 'Red', new environment is 'Green' (for the moment)");
        } else {
            getLog().warn(format("Previous environment was 'Red', replacement environment is currently '%s'",
                    newHealth));

            //NB: we have already switched from one broken service to another, so this is more for the build status indicator...
            newEnvDesc = waitForGreenEnvironment(createEnvResult.getEnvironmentId());
        }
    }

    return createEnvResult;
}

From source file:br.com.ingenieux.mojo.beanstalk.env.ReplaceEnvironmentMojo.java

License:Apache License

/**
 * Prior to Launching a New Environment, lets look and copy the most we can
 *
 * @param curEnv current environment/*from   ww w .jav  a2  s .c o m*/
 */
private void copyOptionSettings(EnvironmentDescription curEnv) throws Exception {
    /**
     * Skip if we don't have anything
     */
    if (null != this.optionSettings && this.optionSettings.length > 0) {
        return;
    }

    DescribeConfigurationSettingsResult configSettings = getService()
            .describeConfigurationSettings(new DescribeConfigurationSettingsRequest()
                    .withApplicationName(applicationName).withEnvironmentName(curEnv.getEnvironmentName()));

    List<ConfigurationOptionSetting> newOptionSettings = new ArrayList<ConfigurationOptionSetting>(
            configSettings.getConfigurationSettings().get(0).getOptionSettings());

    ListIterator<ConfigurationOptionSetting> listIterator = newOptionSettings.listIterator();

    while (listIterator.hasNext()) {
        ConfigurationOptionSetting curOptionSetting = listIterator.next();

        boolean bInvalid = harmfulOptionSettingP(curEnv.getEnvironmentId(), curOptionSetting);

        if (bInvalid) {
            getLog().info(format("Excluding Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(),
                    curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting.getValue())));
            listIterator.remove();
        } else {
            getLog().info(format("Including Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(),
                    curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting.getValue())));
        }
    }

    Object __secGroups = project.getProperties().get("beanstalk.securityGroups");

    if (null != __secGroups) {
        String securityGroups = StringUtils.defaultString(__secGroups.toString());

        if (!StringUtils.isBlank(securityGroups)) {
            ConfigurationOptionSetting newOptionSetting = new ConfigurationOptionSetting(
                    "aws:autoscaling:launchconfiguration", "SecurityGroups", securityGroups);
            newOptionSettings.add(newOptionSetting);
            getLog().info(format("Including Option Setting: %s:%s['%s']", newOptionSetting.getNamespace(),
                    newOptionSetting.getOptionName(), newOptionSetting.getValue()));
        }
    }

    /*
       * Then copy it back
     */
    this.optionSettings = newOptionSettings.toArray(new ConfigurationOptionSetting[newOptionSettings.size()]);
}

From source file:br.com.ingenieux.mojo.beanstalk.env.ReplaceEnvironmentMojo.java

License:Apache License

/**
 * Boolean predicate for named environment
 *
 * @param environmentName environment name
 * @return true if environment name exists
 *///www  .j  av a  2 s  .  c  o m
protected boolean containsNamedEnvironment(String environmentName) {
    for (EnvironmentDescription envDesc : getEnvironmentsFor(applicationName)) {
        if (envDesc.getEnvironmentName().equals(environmentName)) {
            return true;
        }
    }

    return false;
}

From source file:br.com.ingenieux.mojo.beanstalk.env.SwapEnvironmentCnamesMojo.java

License:Apache License

@Override
protected Object executeInternal() throws AbstractMojoExecutionException {
    EnvironmentDescription sourceEnvironment = lookupEnvironment(applicationName,
            ensureSuffix(sourceEnvironmentCNamePrefix));
    EnvironmentDescription targetEnvironment = lookupEnvironment(applicationName,
            ensureSuffix(targetEnvironmentCNamePrefix));

    SwapCNamesContext context = SwapCNamesContextBuilder.swapCNamesContext()//
            .withSourceEnvironmentId(sourceEnvironment.getEnvironmentId())//
            .withSourceEnvironmentName(sourceEnvironment.getEnvironmentName())//
            .withDestinationEnvironmentId(targetEnvironment.getEnvironmentId())//
            .withDestinationEnvironmentName(targetEnvironment.getEnvironmentName())//
            .build();// w w w .j  a  va 2s .com

    SwapCNamesCommand command = new SwapCNamesCommand(this);

    return command.execute(context);

}

From source file:br.com.ingenieux.mojo.beanstalk.version.CleanPreviousVersionsMojo.java

License:Apache License

@Override
protected Object executeInternal() throws MojoExecutionException, MojoFailureException {
    boolean bVersionsToKeepDefined = (null != versionsToKeep);
    boolean bDaysToKeepDefined = (null != daysToKeep);

    if (!(bVersionsToKeepDefined ^ bDaysToKeepDefined)) {
        throw new MojoFailureException("Declare either versionsToKeep or daysToKeep, but not both nor none!");
    }//ww w .  ja  v  a  2  s  .c  o  m

    DescribeApplicationVersionsRequest describeApplicationVersionsRequest = new DescribeApplicationVersionsRequest()
            .withApplicationName(applicationName);

    DescribeApplicationVersionsResult appVersions = getService()
            .describeApplicationVersions(describeApplicationVersionsRequest);

    DescribeEnvironmentsResult environments = getService().describeEnvironments();

    List<ApplicationVersionDescription> appVersionList = new ArrayList<ApplicationVersionDescription>(
            appVersions.getApplicationVersions());

    deletedVersionsCount = 0;

    for (EnvironmentDescription d : environments.getEnvironments()) {
        boolean bActiveEnvironment = (d.getStatus().equals("Running") || d.getStatus().equals("Launching")
                || d.getStatus().equals("Ready"));

        for (ListIterator<ApplicationVersionDescription> appVersionIterator = appVersionList
                .listIterator(); appVersionIterator.hasNext();) {
            ApplicationVersionDescription appVersion = appVersionIterator.next();

            boolean bMatchesVersion = appVersion.getVersionLabel().equals(d.getVersionLabel());

            if (bActiveEnvironment && bMatchesVersion) {
                getLog().info("VersionLabel " + appVersion.getVersionLabel() + " is bound to environment "
                        + d.getEnvironmentName() + " - Skipping it");

                appVersionIterator.remove();
            }
        }
    }

    filterAppVersionListByVersionLabelPattern(appVersionList, cleanFilter);

    Collections.sort(appVersionList, new Comparator<ApplicationVersionDescription>() {
        @Override
        public int compare(ApplicationVersionDescription o1, ApplicationVersionDescription o2) {
            return new CompareToBuilder().append(o1.getDateUpdated(), o2.getDateUpdated()).toComparison();
        }
    });

    if (bDaysToKeepDefined) {
        Date now = new Date();

        for (ApplicationVersionDescription d : appVersionList) {
            long delta = now.getTime() - d.getDateUpdated().getTime();

            delta /= 1000;
            delta /= 86400;

            boolean shouldDeleteP = (delta > daysToKeep);

            if (getLog().isDebugEnabled()) {
                getLog().debug("Version " + d.getVersionLabel() + " was from " + delta
                        + " days ago. Should we delete? " + shouldDeleteP);
            }

            if (shouldDeleteP) {
                deleteVersion(d);
            }
        }
    } else {
        while (appVersionList.size() > versionsToKeep) {
            deleteVersion(appVersionList.remove(0));
        }
    }

    getLog().info("Deleted " + deletedVersionsCount + " versions.");

    return null;
}

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

License:Apache License

public static void synchronousTerminateEnvironments(@Nonnull String applicationName,
        @Nonnull AWSElasticBeanstalk beanstalk) {
    Set<String> statusToTerminate = Sets.newHashSet("Launching", "Updating", "Ready");
    Set<String> statusTerminating = Sets.newHashSet("Terminating");

    List<EnvironmentDescription> environments = beanstalk
            .describeEnvironments(new DescribeEnvironmentsRequest().withApplicationName(applicationName))
            .getEnvironments();/*  ww  w . j  a  va2s .  com*/
    List<EnvironmentDescription> environmentsToWaitFor = Collections.emptyList();

    int counter = 0;
    while (counter < 1 * 60) {
        environmentsToWaitFor = Lists.newArrayList();
        for (EnvironmentDescription environment : environments) {
            if (statusToTerminate.contains(environment.getStatus())) {
                TerminateEnvironmentResult terminateEnvironmentResult = beanstalk.terminateEnvironment(
                        new TerminateEnvironmentRequest().withEnvironmentId(environment.getEnvironmentId()));
                logger.debug("Terminate environment {}, status:{} - ",
                        new Object[] { environment.getEnvironmentName(), environment.getStatus(),
                                terminateEnvironmentResult });
                environmentsToWaitFor.add(environment);
            } else if (statusTerminating.contains(environment.getStatus())) {
                environmentsToWaitFor.add(environment);
                logger.debug("Skip termination of not running environment {}", environment);
            } else {
                logger.trace("skip terminated environment {}", environment);
            }
        }
        if (environmentsToWaitFor.isEmpty()) {
            break;
        } else {
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
            environments = beanstalk
                    .describeEnvironments(
                            new DescribeEnvironmentsRequest().withApplicationName(applicationName))
                    .getEnvironments();
        }
    }

    if (!environmentsToWaitFor.isEmpty()) {
        logger.warn("Failure to terminate {}", environmentsToWaitFor);
    }
}