Example usage for com.amazonaws.services.ec2.model Instance getTags

List of usage examples for com.amazonaws.services.ec2.model Instance getTags

Introduction

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

Prototype


public java.util.List<Tag> getTags() 

Source Link

Document

Any tags assigned to the instance.

Usage

From source file:EC2.java

License:Apache License

public int getInstanceNumWithTag(Tag t) {
    assert (t != null);
    int num = 0;/*from   w  w w.  j  a  v a2 s.  co 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:Aws.Instances.java

public void DescribeInstances(AmazonEC2Client ec2) {
    DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesRequest.getReservations();
    Set<Instance> instances = new HashSet<>();

    for (Iterator<Reservation> it = reservations.iterator(); it.hasNext();) {
        Reservation reservationId = it.next();
        instances.addAll(reservationId.getInstances());
    }//  w w w. j  a  v  a2s  .  c om

    Set<String> InstancesIds = new HashSet<>();
    for (Iterator<Instance> Iteratore = instances.iterator(); Iteratore.hasNext();) {
        Instance instanceId = Iteratore.next();
        List<Tag> tags = instanceId.getTags();
        InstancesIds.add(instanceId.getInstanceId());
        System.out.println("Instance ID " + instanceId.getInstanceId() + " ; Instance Tags " + tags);
        for (Iterator<Tag> tag = tags.iterator(); tag.hasNext();) {
            Tag tagkey = tag.next();
            System.out.println(tagkey.withKey("Name").getValue());
        }

    }
}

From source file:com.clouck.model.aws.ec2.Ec2Instance.java

@Override
@SuppressWarnings("rawtypes")
protected boolean isEqual(AbstractResource newResource) {
    Instance oldInstance = this.getResource();
    Ec2Instance newEc2Instance = (Ec2Instance) newResource;
    Instance newInstance = newEc2Instance.getResource();

    if (notEqual(oldInstance.getInstanceId(), newInstance.getInstanceId()))
        return false;
    if (notEqual(oldInstance.getImageId(), newInstance.getImageId()))
        return false;
    if (notEqual(oldInstance.getState(), newInstance.getState()))
        return false;
    if (notEqual(oldInstance.getPrivateDnsName(), newInstance.getPrivateDnsName()))
        return false;
    if (notEqual(oldInstance.getPublicDnsName(), newInstance.getPublicDnsName()))
        return false;
    if (notEqual(oldInstance.getStateTransitionReason(), newInstance.getStateTransitionReason()))
        return false;
    if (notEqual(oldInstance.getKeyName(), newInstance.getKeyName()))
        return false;
    if (notEqual(oldInstance.getAmiLaunchIndex(), newInstance.getAmiLaunchIndex()))
        return false;
    if (notEqualCollection(oldInstance.getProductCodes(), newInstance.getProductCodes()))
        return false;
    if (notEqual(oldInstance.getInstanceType(), newInstance.getInstanceType()))
        return false;
    if (notEqual(oldInstance.getLaunchTime(), newInstance.getLaunchTime()))
        return false;
    if (notEqual(oldInstance.getPlacement(), newInstance.getPlacement()))
        return false;
    if (notEqual(oldInstance.getKernelId(), newInstance.getKernelId()))
        return false;
    if (notEqual(oldInstance.getRamdiskId(), newInstance.getRamdiskId()))
        return false;
    if (notEqual(oldInstance.getPlatform(), newInstance.getPlatform()))
        return false;
    if (notEqual(oldInstance.getMonitoring(), newInstance.getMonitoring()))
        return false;
    if (notEqual(oldInstance.getSubnetId(), newInstance.getSubnetId()))
        return false;
    if (notEqual(oldInstance.getVpcId(), newInstance.getVpcId()))
        return false;
    if (notEqual(oldInstance.getPrivateIpAddress(), newInstance.getPrivateIpAddress()))
        return false;
    if (notEqual(oldInstance.getPublicIpAddress(), newInstance.getPublicIpAddress()))
        return false;
    if (notEqual(oldInstance.getStateReason(), newInstance.getStateReason()))
        return false;
    if (notEqual(oldInstance.getArchitecture(), newInstance.getArchitecture()))
        return false;
    if (notEqual(oldInstance.getRootDeviceType(), newInstance.getRootDeviceType()))
        return false;
    if (notEqual(oldInstance.getRootDeviceName(), newInstance.getRootDeviceName()))
        return false;
    if (notEqualCollection(oldInstance.getBlockDeviceMappings(), newInstance.getBlockDeviceMappings()))
        return false;
    if (notEqual(oldInstance.getVirtualizationType(), newInstance.getVirtualizationType()))
        return false;
    if (notEqual(oldInstance.getInstanceLifecycle(), newInstance.getInstanceLifecycle()))
        return false;
    if (notEqual(oldInstance.getSpotInstanceRequestId(), newInstance.getSpotInstanceRequestId()))
        return false;
    if (notEqual(oldInstance.getLicense(), newInstance.getLicense()))
        return false;
    if (notEqual(oldInstance.getClientToken(), newInstance.getClientToken()))
        return false;
    if (notEqualCollection(oldInstance.getTags(), newInstance.getTags()))
        return false;
    if (notEqualCollection(oldInstance.getSecurityGroups(), newInstance.getSecurityGroups()))
        return false;
    if (notEqual(oldInstance.getSourceDestCheck(), newInstance.getSourceDestCheck()))
        return false;
    if (notEqual(oldInstance.getHypervisor(), newInstance.getHypervisor()))
        return false;
    if (notEqualNetworkInterfaces(oldInstance.getNetworkInterfaces(), newInstance.getNetworkInterfaces()))
        return false;
    if (notEqual(oldInstance.getIamInstanceProfile(), newInstance.getIamInstanceProfile()))
        return false;
    if (notEqual(oldInstance.getEbsOptimized(), newInstance.getEbsOptimized()))
        return false;
    if (notEqual(this.getTerminationProtection(), newEc2Instance.getTerminationProtection()))
        return false;
    if (notEqual(this.getShutdownBehavior(), newEc2Instance.getShutdownBehavior()))
        return false;
    if (notEqual(this.getUserData(), newEc2Instance.getUserData()))
        return false;

    return true;/*from   w  w  w  . ja v a 2  s .co  m*/
}

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

License:Apache License

/**
 * Performs a sequence of strict instance ownership checks to avoid any potential harmful
 * accidents./*w  w  w.  java2  s  .c  o  m*/
 *
 * @param instance the instance
 * @param template the template from which the instance was created, or <code>null</code>
 *                 if it is unknown (such as during a delete call)
 * @return the virtual instance ID
 * @throws IllegalStateException if the instance fails an ownership check
 */
private String checkInstanceIsManagedByDirector(Instance instance, EC2InstanceTemplate template) {
    String virtualInstanceId = getVirtualInstanceId(instance.getTags(), "instance");
    String instanceIds = instance.getInstanceId() + " / " + virtualInstanceId;
    String instanceKeyName = instance.getKeyName();

    if (template != null) {
        if (!template.getKeyName().equals(Optional.fromNullable(instanceKeyName))) {
            throw new IllegalStateException(
                    "Found unexpected key name: " + instanceKeyName + " for instance: " + instanceIds);
        }
        String instanceType = instance.getInstanceType();
        if (!template.getType().equals(instanceType)) {
            throw new IllegalStateException(
                    "Found unexpected type: " + instanceType + " for instance: " + instanceIds);
        }
        String instanceImageId = instance.getImageId();
        if (!template.getImage().equals(instanceImageId)) {
            throw new IllegalStateException(
                    "Found unexpected image type: " + instanceImageId + " for instance: " + instanceIds);
        }
    }
    return virtualInstanceId;
}

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 av a 2s.  c  om
    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 .ja  v a 2 s. 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 v a2 s  .  c om
@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();
            }//w  w  w  . ja  v a2 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  ww.j  a v 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();
            }/*w ww .  j a  v  a 2s. c  o  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;
    }
}