Example usage for com.amazonaws.services.ec2.model Tag getValue

List of usage examples for com.amazonaws.services.ec2.model Tag getValue

Introduction

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

Prototype


public String getValue() 

Source Link

Document

The value of the tag.

Usage

From source file:EC2.java

License:Apache License

public int getInstanceNumWithTag(Tag t) {
    assert (t != null);
    int num = 0;/*from www . j  av  a  2  s  . c o m*/
    List<Reservation> reservations = ec2.describeInstances().getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            if (!instance.getState().getName().equals("pending")
                    && !instance.getState().getName().equals("running"))
                continue;
            List<Tag> tags = instance.getTags();
            for (Tag tag : tags) {
                if (tag.getKey().equals(t.getKey()) && tag.getValue().equals(t.getValue())) {
                    num++;
                    break;
                }
            }
        }
    }
    return num;
}

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

License:Apache License

/**
 * Determines the virtual instance ID from the specified list of tags.
 *
 * @param tags the tags/*from w  w  w  .j a v  a2  s. c om*/
 * @param type the type of tagged object
 * @return the virtual instance ID
 * @throws IllegalStateException if the tags do not contain the virtual instance ID
 */
private String getVirtualInstanceId(List<Tag> tags, String type) {
    for (Tag tag : tags) {
        if (tag.getKey().equals(ResourceTags.CLOUDERA_DIRECTOR_ID.getTagKey())) {
            return tag.getValue();
        }
    }

    throw new IllegalStateException(
            String.format("Any %s managed by " + "Cloudera Director should have a %s tag.", type,
                    ResourceTags.CLOUDERA_DIRECTOR_ID.getTagKey()));
}

From source file:com.dtolabs.rundeck.ec2.NodeGenerator.java

License:Apache License

public static INodeEntry instanceToNode(final Instance inst, final Properties mapping)
        throws GeneratorException {
    String hostSel = mapping.getProperty("hostname.selector");
    String host = applySelector(inst, hostSel, mapping.getProperty("hostname.default"));
    if (null == host) {
        System.err.println("Unable to determine hostname for instance: " + inst.getInstanceId());
        return null;
    }/*from w  w w  . j  a  v  a 2 s . co m*/
    String nameSel = mapping.getProperty("name.selector");
    String name = applySelector(inst, nameSel, mapping.getProperty("name.default"));
    if (null == name) {
        name = host;
    }
    NodeEntryImpl node = new NodeEntryImpl(host, name);
    String descSel = mapping.getProperty("description.selector");
    String desc = applySelector(inst, descSel, mapping.getProperty("description.default"));
    node.setDescription(desc);

    for (final String prop : ResourceXMLConstants.nodeProps) {
        final String value = applySelector(inst, mapping.getProperty(prop + ".selector"),
                mapping.getProperty(prop + ".default"));
        if (null != value) {
            try {
                BeanUtils.setProperty(node, prop, value);
            } catch (Exception e) {
                throw new GeneratorException(e);
            }
        }
    }
    String[] attrProps = new String[] { ResourceXMLConstants.NODE_REMOTE_URL,
            ResourceXMLConstants.NODE_EDIT_URL };
    for (final String attrProp : attrProps) {
        final String value = applySelector(inst, mapping.getProperty(attrProp + ".selector"),
                mapping.getProperty(attrProp + ".default"));
        if (null != value) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(attrProp, value);
        }
    }

    Pattern settingPat = Pattern.compile("^setting\\.(.+?)\\.selector$");
    //evaluate setting selectors
    for (final Object o : mapping.keySet()) {
        String key = (String) o;
        String selector = mapping.getProperty(key);
        Matcher m = settingPat.matcher(key);
        if (m.matches()) {
            String setName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selector,
                    mapping.getProperty("setting." + setName + ".default"));
            if (null != value) {
                //use nodename-settingname to make the setting unique to the node
                node.getAttributes().put(setName, value);
            }
        }
    }
    //evaluate single settings.selector=tags/* mapping
    if ("tags/*".equals(mapping.getProperty("settings.selector"))) {
        //iterate through instance tags and generate settings
        for (final Tag tag : inst.getTags()) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(tag.getKey(), tag.getValue());
        }
    }
    //evaluate single settings.selector=tags/* mapping
    if ("tags/*".equals(mapping.getProperty("attributes.selector"))) {
        //iterate through instance tags and generate settings
        for (final Tag tag : inst.getTags()) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(tag.getKey(), tag.getValue());
        }
    }
    if (null != mapping.getProperty("tags.selector")) {
        final String selector = mapping.getProperty("tags.selector");
        final String value = applySelector(inst, selector, mapping.getProperty("tags.default"));
        if (null != value) {
            final String[] values = value.split(",");
            final HashSet<String> tagset = new HashSet<String>();
            for (final String s : values) {
                tagset.add(s.trim());
            }
            if (null == node.getTags()) {
                node.setTags(tagset);
            } else {
                node.getTags().addAll(tagset);
            }
        }
    }

    //apply specific tag selectors
    Pattern tagPat = Pattern.compile("^tag\\.(.+?)\\.selector$");
    //evaluate tag selectors
    for (final Object o : mapping.keySet()) {
        String key = (String) o;
        String selector = mapping.getProperty(key);
        //split selector by = if present
        String[] selparts = selector.split("=");
        Matcher m = tagPat.matcher(key);
        if (m.matches()) {
            String tagName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selparts[0], null);
            if (null != value) {
                if (selparts.length > 1 && !value.equals(selparts[1])) {
                    continue;
                }
                //use add the tag if the value is not null
                if (null == node.getTags()) {
                    node.setTags(new HashSet());
                }
                node.getTags().add(tagName);
            }
        }
    }

    //apply attribute selectors

    Pattern attribPat = Pattern.compile("^attribute\\.(.+?)\\.selector$");
    //evaluate setting selectors
    for (final Object o : mapping.keySet()) {
        String key = (String) o;
        String selector = mapping.getProperty(key);
        Matcher m = attribPat.matcher(key);
        if (m.matches()) {
            String attrName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selector,
                    mapping.getProperty("attribute." + attrName + ".default"));
            if (null != value) {
                //use nodename-settingname to make the setting unique to the node
                node.getAttributes().put(attrName, value);
            }
        }
    }
    return node;
}

From source file:com.dtolabs.rundeck.ec2.NodeGenerator.java

License:Apache License

public static String applySelector(Instance inst, String selector, String defaultValue)
        throws GeneratorException {
    if (null != selector && selector.startsWith("tags/")) {
        String tag = selector.substring("tags/".length());
        final List<Tag> tags = inst.getTags();
        for (final Tag tag1 : tags) {
            if (tag.equals(tag1.getKey())) {
                return tag1.getValue();
            }//from   w w w  .j a v  a  2s .c  o m
        }
    } else if (null != selector) {
        try {
            final String value = BeanUtils.getProperty(inst, selector);
            if (null != value) {
                return value;
            }
        } catch (Exception e) {
            throw new GeneratorException(e);
        }
    }

    return defaultValue;
}

From source file:com.dtolabs.rundeck.plugin.resources.ec2.InstanceToNodeMapper.java

License:Apache License

/**
 * Convert an AWS EC2 Instance to a RunDeck INodeEntry based on the mapping input
 *///from   w  w w  .j  a  va2  s . co  m
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final Instance inst, final Properties mapping) throws GeneratorException {
    final NodeEntryImpl node = new NodeEntryImpl();

    //evaluate single settings.selector=tags/* mapping
    if ("tags/*".equals(mapping.getProperty("attributes.selector"))) {
        //iterate through instance tags and generate settings
        for (final Tag tag : inst.getTags()) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(tag.getKey(), tag.getValue());
        }
    }
    if (null != mapping.getProperty("tags.selector")) {
        final String selector = mapping.getProperty("tags.selector");
        final String value = applySelector(inst, selector, mapping.getProperty("tags.default"), true);
        if (null != value) {
            final String[] values = value.split(",");
            final HashSet<String> tagset = new HashSet<String>();
            for (final String s : values) {
                tagset.add(s.trim());
            }
            if (null == node.getTags()) {
                node.setTags(tagset);
            } else {
                final HashSet orig = new HashSet(node.getTags());
                orig.addAll(tagset);
                node.setTags(orig);
            }
        }
    }
    if (null == node.getTags()) {
        node.setTags(new HashSet());
    }
    final HashSet orig = new HashSet(node.getTags());
    //apply specific tag selectors
    final Pattern tagPat = Pattern.compile("^tag\\.(.+?)\\.selector$");
    //evaluate tag selectors
    for (final Object o : mapping.keySet()) {
        final String key = (String) o;
        final String selector = mapping.getProperty(key);
        //split selector by = if present
        final String[] selparts = selector.split("=");
        final Matcher m = tagPat.matcher(key);
        if (m.matches()) {
            final String tagName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selparts[0], null);
            if (null != value) {
                if (selparts.length > 1 && !value.equals(selparts[1])) {
                    continue;
                }
                //use add the tag if the value is not null
                orig.add(tagName);
            }
        }
    }
    node.setTags(orig);

    //apply default values which do not have corresponding selector
    final Pattern attribDefPat = Pattern.compile("^([^.]+?)\\.default$");
    //evaluate selectors
    for (final Object o : mapping.keySet()) {
        final String key = (String) o;
        final String value = mapping.getProperty(key);
        final Matcher m = attribDefPat.matcher(key);
        if (m.matches() && (!mapping.containsKey(key + ".selector")
                || "".equals(mapping.getProperty(key + ".selector")))) {
            final String attrName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            if (null != value) {
                node.getAttributes().put(attrName, value);
            }
        }
    }

    final Pattern attribPat = Pattern.compile("^([^.]+?)\\.selector$");
    //evaluate selectors
    for (final Object o : mapping.keySet()) {
        final String key = (String) o;
        final String selector = mapping.getProperty(key);
        final Matcher m = attribPat.matcher(key);
        if (m.matches()) {
            final String attrName = m.group(1);
            if (attrName.equals("tags")) {
                //already handled
                continue;
            }
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selector, mapping.getProperty(attrName + ".default"));
            if (null != value) {
                //use nodename-settingname to make the setting unique to the node
                node.getAttributes().put(attrName, value);
            }
        }
    }
    //        String hostSel = mapping.getProperty("hostname.selector");
    //        String host = applySelector(inst, hostSel, mapping.getProperty("hostname.default"));
    //        if (null == node.getHostname()) {
    //            System.err.println("Unable to determine hostname for instance: " + inst.getInstanceId());
    //            return null;
    //        }
    String name = node.getNodename();
    if (null == name || "".equals(name)) {
        name = node.getHostname();
    }
    if (null == name || "".equals(name)) {
        name = inst.getInstanceId();
    }
    node.setNodename(name);

    // Set ssh port on hostname if not 22
    String sshport = node.getAttributes().get("sshport");
    if (sshport != null && !sshport.equals("") && !sshport.equals("22")) {
        node.setHostname(node.getHostname() + ":" + sshport);
    }

    return node;
}

From source file:com.dtolabs.rundeck.plugin.resources.ec2.InstanceToNodeMapper.java

License:Apache License

private static String applySingleSelector(final Instance inst, final String selector)
        throws GeneratorException {
    if (null != selector && !"".equals(selector) && selector.startsWith("tags/")) {
        final String tag = selector.substring("tags/".length());
        final List<Tag> tags = inst.getTags();
        for (final Tag tag1 : tags) {
            if (tag.equals(tag1.getKey())) {
                return tag1.getValue();
            }/*from www .  j a v  a 2  s. co  m*/
        }
    } else if (null != selector && !"".equals(selector)) {
        try {
            final String value = BeanUtils.getProperty(inst, selector);
            if (null != value) {
                return value;
            }
        } catch (Exception e) {
            throw new GeneratorException(e);
        }
    }

    return null;
}

From source file:com.ec2box.manage.action.SystemAction.java

License:Apache License

@Action(value = "/admin/viewSystems", results = {
        @Result(name = "success", location = "/admin/view_systems.jsp") })
public String viewSystems() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    String userType = AuthUtil.getUserType(servletRequest.getSession());

    List<String> ec2RegionList = EC2KeyDB.getEC2Regions();
    List<String> instanceIdList = new ArrayList<String>();

    //default instance state
    if (sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE) == null) {
        sortedSet.getFilterMap().put(FILTER_BY_INSTANCE_STATE, AppConfig.getProperty("defaultInstanceState"));
    }/*from w w  w.j  av  a 2 s .c o m*/

    try {
        Map<String, HostSystem> hostSystemList = new HashMap<String, HostSystem>();

        //if user profile has been set or user is a manager
        List<Profile> profileList = UserProfileDB.getProfilesByUser(userId);
        if (profileList.size() > 0 || Auth.MANAGER.equals(userType)) {
            //set tags for profile
            List<String> profileTags = new ArrayList<>();
            for (Profile profile : profileList) {
                profileTags.add(profile.getTag());
            }
            Map<String, List<String>> profileTagMap = parseTags(profileTags);

            //set tags from input filters
            Map<String, List<String>> filterTags = fetchInputFilterTags(userType, profileTagMap);

            //parse out security group list in format group[,group]
            List<String> securityGroupList = new ArrayList<>();
            if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SECURITY_GROUP))) {
                securityGroupList = Arrays
                        .asList(sortedSet.getFilterMap().get(FILTER_BY_SECURITY_GROUP).split(","));
            }

            //get AWS credentials from DB
            for (AWSCred awsCred : AWSCredDB.getAWSCredList()) {

                if (awsCred != null) {
                    //set  AWS credentials for service
                    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(),
                            awsCred.getSecretKey());

                    for (String ec2Region : ec2RegionList) {
                        //create service

                        AmazonEC2 service = new AmazonEC2Client(awsCredentials,
                                AWSClientConfig.getClientConfig());
                        service.setEndpoint(ec2Region);

                        //only return systems that have keys set
                        List<String> keyValueList = new ArrayList<String>();
                        for (EC2Key ec2Key : EC2KeyDB.getEC2KeyByRegion(ec2Region, awsCred.getId())) {
                            keyValueList.add(ec2Key.getKeyNm());
                        }

                        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();

                        Filter keyNmFilter = new Filter("key-name", keyValueList);
                        describeInstancesRequest.withFilters(keyNmFilter);

                        //instance state filter
                        if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE))) {
                            List<String> instanceStateList = new ArrayList<String>();
                            instanceStateList.add(sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE));
                            Filter instanceStateFilter = new Filter("instance-state-name", instanceStateList);
                            describeInstancesRequest.withFilters(instanceStateFilter);
                        }

                        if (securityGroupList.size() > 0) {
                            Filter groupFilter = new Filter("group-name", securityGroupList);
                            describeInstancesRequest.withFilters(groupFilter);
                        }
                        //set name value pair for tag filter
                        List<String> tagList = new ArrayList<String>();

                        //always add all profile tags to filter list
                        addTagsToDescribeInstanceRequest(profileTagMap, describeInstancesRequest, tagList);

                        //add all additional filter tags provided by the user
                        addTagsToDescribeInstanceRequest(filterTags, describeInstancesRequest, tagList);

                        if (tagList.size() > 0) {
                            Filter tagFilter = new Filter("tag-key", tagList);
                            describeInstancesRequest.withFilters(tagFilter);
                        }

                        DescribeInstancesResult describeInstancesResult = service
                                .describeInstances(describeInstancesRequest);

                        for (Reservation res : describeInstancesResult.getReservations()) {
                            for (Instance instance : res.getInstances()) {

                                HostSystem hostSystem = new HostSystem();
                                hostSystem.setInstance(instance.getInstanceId());

                                //check for public dns if doesn't exist set to ip or pvt dns
                                if (!"true".equals(AppConfig.getProperty("useEC2PvtDNS"))
                                        && StringUtils.isNotEmpty(instance.getPublicDnsName())) {
                                    hostSystem.setHost(instance.getPublicDnsName());
                                } else if (!"true".equals(AppConfig.getProperty("useEC2PvtDNS"))
                                        && StringUtils.isNotEmpty(instance.getPublicIpAddress())) {
                                    hostSystem.setHost(instance.getPublicIpAddress());
                                } else if (StringUtils.isNotEmpty(instance.getPrivateDnsName())) {
                                    hostSystem.setHost(instance.getPrivateDnsName());
                                } else {
                                    hostSystem.setHost(instance.getPrivateIpAddress());
                                }

                                hostSystem.setKeyId(EC2KeyDB
                                        .getEC2KeyByNmRegion(instance.getKeyName(), ec2Region, awsCred.getId())
                                        .getId());
                                hostSystem.setEc2Region(ec2Region);
                                hostSystem.setState(instance.getState().getName());
                                for (Tag tag : instance.getTags()) {
                                    if ("Name".equals(tag.getKey())) {
                                        hostSystem.setDisplayNm(tag.getValue());
                                    }
                                }
                                instanceIdList.add(hostSystem.getInstance());
                                hostSystemList.put(hostSystem.getInstance(), hostSystem);
                            }
                        }

                        if (instanceIdList.size() > 0) {
                            //set instance id list to check permissions when creating sessions
                            servletRequest.getSession().setAttribute("instanceIdList",
                                    new ArrayList<String>(instanceIdList));
                            if (showStatus) {
                                //make service call 100 instances at a time b/c of AWS limitation
                                int i = 0;
                                List<String> idCallList = new ArrayList<String>();
                                while (!instanceIdList.isEmpty()) {
                                    idCallList.add(instanceIdList.remove(0));
                                    i++;
                                    //when i eq 100 make call
                                    if (i >= 100 || instanceIdList.isEmpty()) {

                                        //get status for host systems
                                        DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest();
                                        describeInstanceStatusRequest.withInstanceIds(idCallList);
                                        DescribeInstanceStatusResult describeInstanceStatusResult = service
                                                .describeInstanceStatus(describeInstanceStatusRequest);

                                        for (InstanceStatus instanceStatus : describeInstanceStatusResult
                                                .getInstanceStatuses()) {

                                            HostSystem hostSystem = hostSystemList
                                                    .remove(instanceStatus.getInstanceId());
                                            hostSystem.setSystemStatus(
                                                    instanceStatus.getSystemStatus().getStatus());
                                            hostSystem.setInstanceStatus(
                                                    instanceStatus.getInstanceStatus().getStatus());

                                            //check and filter by instance or system status
                                            if ((StringUtils.isEmpty(
                                                    sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATUS))
                                                    && StringUtils.isEmpty(sortedSet.getFilterMap()
                                                            .get(FILTER_BY_SYSTEM_STATUS)))
                                                    || (hostSystem.getInstanceStatus()
                                                            .equals(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_INSTANCE_STATUS))
                                                            && StringUtils.isEmpty(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_SYSTEM_STATUS)))
                                                    || (hostSystem.getInstanceStatus()
                                                            .equals(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_SYSTEM_STATUS))
                                                            && StringUtils.isEmpty(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_INSTANCE_STATUS)))
                                                    || (hostSystem.getInstanceStatus()
                                                            .equals(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_SYSTEM_STATUS))
                                                            && hostSystem.getInstanceStatus()
                                                                    .equals(sortedSet.getFilterMap()
                                                                            .get(FILTER_BY_INSTANCE_STATUS)))) {
                                                hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                            }
                                        }

                                        //start over
                                        i = 0;
                                        //clear list
                                        idCallList.clear();
                                    }

                                }

                                //check alarms for ec2 instances
                                AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(
                                        awsCredentials, AWSClientConfig.getClientConfig());
                                cloudWatchClient.setEndpoint(ec2Region.replace("ec2", "monitoring"));

                                DescribeAlarmsResult describeAlarmsResult = cloudWatchClient.describeAlarms();

                                for (MetricAlarm metricAlarm : describeAlarmsResult.getMetricAlarms()) {

                                    for (Dimension dim : metricAlarm.getDimensions()) {

                                        if (dim.getName().equals("InstanceId")) {
                                            HostSystem hostSystem = hostSystemList.remove(dim.getValue());
                                            if (hostSystem != null) {
                                                if ("ALARM".equals(metricAlarm.getStateValue())) {
                                                    hostSystem
                                                            .setMonitorAlarm(hostSystem.getMonitorAlarm() + 1);
                                                } else if ("INSUFFICIENT_DATA"
                                                        .equals(metricAlarm.getStateValue())) {
                                                    hostSystem.setMonitorInsufficientData(
                                                            hostSystem.getMonitorInsufficientData() + 1);
                                                } else {
                                                    hostSystem.setMonitorOk(hostSystem.getMonitorOk() + 1);
                                                }
                                                //check and filter by alarm state
                                                if (StringUtils.isEmpty(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                } else if ("ALARM".equals(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))
                                                        && hostSystem.getMonitorAlarm() > 0) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                } else if ("INSUFFICIENT_DATA".equals(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))
                                                        && hostSystem.getMonitorInsufficientData() > 0) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                } else if ("OK".equals(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))
                                                        && hostSystem.getMonitorOk() > 0
                                                        && hostSystem.getMonitorInsufficientData() <= 0
                                                        && hostSystem.getMonitorAlarm() <= 0) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //set ec2 systems
            SystemDB.setSystems(hostSystemList.values());
            sortedSet = SystemDB.getSystemSet(sortedSet, new ArrayList<String>(hostSystemList.keySet()));

        }
    } catch (AmazonServiceException ex) {
        log.error(ex.toString(), ex);
    }

    if (script != null && script.getId() != null) {
        script = ScriptDB.getScript(script.getId(), userId);
    }

    return SUCCESS;
}

From source file:com.epam.dlab.automation.helper.CloudHelper.java

License:Apache License

static String getInstanceNameByCondition(String name, boolean restrictionMode) throws IOException {
    switch (ConfigPropertyValue.getCloudProvider()) {
    case CloudProvider.AWS_PROVIDER:
        Instance instance = AmazonHelper.getInstance(name);
        for (Tag tag : instance.getTags()) {
            if (tag.getKey().equals("Name")) {
                return tag.getValue();
            }//from w  w w  .j  a va 2 s .co  m
        }
        throw new CloudException("Could not detect name for instance " + name);
    case CloudProvider.AZURE_PROVIDER:
        if (AzureHelper.getVirtualMachinesByName(name, restrictionMode) != null) {
            return AzureHelper.getVirtualMachinesByName(name, restrictionMode).get(0).name();
        } else
            return null;
    case CloudProvider.GCP_PROVIDER:
        if (GcpHelper.getInstancesByName(name, ConfigPropertyValue.getGcpDlabProjectId(), restrictionMode,
                GcpHelper.getAvailableZonesForProject(ConfigPropertyValue.getGcpDlabProjectId())) != null) {
            return GcpHelper
                    .getInstancesByName(name, ConfigPropertyValue.getGcpDlabProjectId(), restrictionMode,
                            GcpHelper.getAvailableZonesForProject(ConfigPropertyValue.getGcpDlabProjectId()))
                    .get(0).getName();
        } else
            return null;
    default:
        return null;
    }
}

From source file:com.github.trask.sandbox.ec2.Ec2Service.java

License:Apache License

public Instance getInstanceForName(String name) {
    List<Instance> foundInstances = new ArrayList<Instance>();
    logger.debug("getInstanceForName(): calling ec2.describeInstances()");
    DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesRequest.getReservations();
    Set<Instance> instances = new HashSet<Instance>();

    for (Reservation reservation : reservations) {
        for (Instance instance : reservation.getInstances()) {
            String state = instance.getState().getName();
            if ("shutting-down".equals(state) || "terminated".equals(state)) {
                continue;
            }/*from   w  ww .ja va  2  s.  c om*/
            for (Tag tag : instance.getTags()) {
                if (tag.getKey().equals("Name") && tag.getValue().equals(name)) {
                    foundInstances.add(instance);
                }
            }
            instances.add(instance);
        }
    }
    if (foundInstances.size() == 0) {
        return null;
    } else if (foundInstances.size() == 1) {
        return foundInstances.get(0);
    } else {
        throw new IllegalStateException("found more than one instance with name '" + name + "'");
    }
}

From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.EC2InstanceDetail.java

License:Open Source License

private void buildUI(DescribeInstancesResult detail) {

    JTabbedPane tabs = new JTabbedPane();
    tabs.add("Instance", primaryScrollPane);
    tabs.add("Tags", tagsScrollPane);

    this.add(tabs, BorderLayout.CENTER);

    List<Reservation> reservations = detail.getReservations();
    if (!reservations.isEmpty()) {

        Reservation reservation = reservations.get(0);
        List<Instance> instances = reservation.getInstances();
        if (!instances.isEmpty()) {

            Instance instance = instances.get(0);

            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "AMI Launch Index", instance.getAmiLaunchIndex() });
            }//  w w  w. j av a2  s  .com
            if (instance.getArchitecture() != null) {
                primaryTableModel.addRow(new Object[] { "Architecture", instance.getArchitecture() });
            }
            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "Block Mapping Device", "" });
            }
            if (instance.getClientToken() != null) {
                primaryTableModel.addRow(new Object[] { "Client Token", instance.getClientToken() });
            }
            primaryTableModel.addRow(new Object[] { "EBS Optimised", instance.isEbsOptimized() });
            if (instance.getHypervisor() != null) {
                primaryTableModel.addRow(new Object[] { "Hypervisor", instance.getHypervisor() });
            }
            if (instance.getIamInstanceProfile() != null) {
                primaryTableModel.addRow(
                        new Object[] { "Instance Profile", instance.getIamInstanceProfile().toString() });
            }
            if (instance.getImageId() != null) {
                primaryTableModel.addRow(new Object[] { "Image Id", instance.getImageId() });
            }
            if (instance.getInstanceId() != null) {
                primaryTableModel.addRow(new Object[] { "Instance Id", instance.getInstanceId() });
            }
            if (instance.getInstanceLifecycle() != null) {
                primaryTableModel.addRow(new Object[] { "Instance Lifecyle", instance.getInstanceLifecycle() });
            }
            if (instance.getInstanceType() != null) {
                primaryTableModel.addRow(new Object[] { "Instance Type", instance.getInstanceType() });
            }
            if (instance.getKernelId() != null) {
                primaryTableModel.addRow(new Object[] { "Kernel Id", instance.getKernelId() });
            }
            if (instance.getKeyName() != null) {
                primaryTableModel.addRow(new Object[] { "Key Name", instance.getKeyName() });
            }
            if (instance.getLaunchTime() != null) {
                primaryTableModel.addRow(new Object[] { "Launch Time", instance.getLaunchTime() });
            }
            if (instance.getMonitoring() != null) {
                primaryTableModel.addRow(new Object[] { "Monitoring", instance.getMonitoring().toString() });
            }
            if (instance.getPlacement() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Placement", instance.getPlacement().getAvailabilityZone() });
            }
            if (instance.getPlatform() != null) {
                primaryTableModel.addRow(new Object[] { "Platform", instance.getPlatform() });
            }
            if (instance.getPrivateDnsName() != null) {
                primaryTableModel.addRow(new Object[] { "Private DNS Name", instance.getPrivateDnsName() });
            }
            if (instance.getPrivateIpAddress() != null) {
                primaryTableModel.addRow(new Object[] { "Private IP Address", instance.getPrivateIpAddress() });
            }
            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "Product Codes", "" });
            }
            if (instance.getPublicDnsName() != null) {
                primaryTableModel.addRow(new Object[] { "Public DNS Name", instance.getPublicDnsName() });
            }
            if (instance.getPublicIpAddress() != null) {
                primaryTableModel.addRow(new Object[] { "Public IP Address", instance.getPublicIpAddress() });
            }
            if (instance.getRamdiskId() != null) {
                primaryTableModel.addRow(new Object[] { "Ram Disk Id", instance.getRamdiskId() });
            }
            if (instance.getRootDeviceName() != null) {
                primaryTableModel.addRow(new Object[] { "Root Device Name", instance.getRootDeviceName() });
            }
            if (instance.getRootDeviceType() != null) {
                primaryTableModel.addRow(new Object[] { "Root Device Type", instance.getRootDeviceType() });
            }
            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "Security Groups", "" });
            }
            if (instance.getSourceDestCheck() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Source Destination Check", instance.getSourceDestCheck() });
            }
            if (instance.getSpotInstanceRequestId() != null) {
                primaryTableModel.addRow(
                        new Object[] { "Spot Instance Request Id", instance.getSpotInstanceRequestId() });
            }
            if (instance.getSriovNetSupport() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Sriov network Support", instance.getSriovNetSupport() });
            }
            if (instance.getState() != null) {
                primaryTableModel.addRow(new Object[] { "State", instance.getState().getName() });
            }
            if (instance.getStateReason() != null) {
                primaryTableModel
                        .addRow(new Object[] { "State Reason", instance.getStateReason().getMessage() });
            }
            if (instance.getSubnetId() != null) {
                primaryTableModel.addRow(new Object[] { "Subnet Id", instance.getSubnetId() });
            }
            if (instance.getVirtualizationType() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Virtualisation Type", instance.getVirtualizationType() });
            }
            if (instance.getVpcId() != null) {
                primaryTableModel.addRow(new Object[] { "Vpc Id", instance.getVpcId() });
            }

            List<Tag> tags = instance.getTags();
            for (Tag tag : tags) {
                tagsTableModel.addRow(new Object[] { tag.getKey(), tag.getValue() });
            }
        }
    }
}