List of usage examples for com.amazonaws.services.ec2.model DescribeInstancesRequest withFilters
public DescribeInstancesRequest withFilters(java.util.Collection<Filter> filters)
The filters.
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")); }// w w w . j a v a 2 s . co 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.ec2box.manage.action.SystemAction.java
License:Apache License
private void addTagsToDescribeInstanceRequest(Map<String, List<String>> profileTagMap, DescribeInstancesRequest describeInstancesRequest, List<String> tagList) { for (String tag : profileTagMap.keySet()) { if (profileTagMap.get(tag) != null) { Filter tagValueFilter = new Filter("tag:" + tag, profileTagMap.get(tag)); describeInstancesRequest.withFilters(tagValueFilter); } else {/*from w w w.jav a2 s .c o m*/ tagList.add(tag); } } }
From source file:com.hazelcast.simulator.provisioner.AwsProvisioner.java
License:Open Source License
private List<Instance> getInstancesByPublicIp(List<AgentData> agentDataList, boolean removeFromRegistry) { List<String> ips = new ArrayList<String>(); for (AgentData agentData : agentDataList) { ips.add(agentData.getPublicAddress()); if (removeFromRegistry) { componentRegistry.removeAgent(agentData); }// w w w . ja v a 2 s .c om } DescribeInstancesRequest request = new DescribeInstancesRequest(); Filter filter = new Filter(AWS_PUBLIC_IP_FILTER, ips); DescribeInstancesResult result = ec2.describeInstances(request.withFilters(filter)); List<Reservation> reservations = result.getReservations(); List<Instance> foundInstances = new ArrayList<Instance>(); for (Reservation reservation : reservations) { List<Instance> instances = reservation.getInstances(); foundInstances.addAll(instances); } return foundInstances; }
From source file:com.keybox.manage.db.ProfileSystemsDB.java
License:Apache License
/** * Update Profile and AWS Systems in DB//from ww w . ja v a 2s.c o m * <br><br> * Call first updateAWSSystem() to Update EC2 systems<br> * Clean SystemProfileEntries from EC2 systems<br> * Rebuild SystemProfileEntries for EC2 systems */ public static void updateProfileAWSSysteme() { SystemDB.updateAWSSystems(); deleteAWSSystemProfileEntries(); try { List<Profile> profileList = ProfileDB.getAllProfiles(); for (Profile profile : profileList) { if (profile.getTag().equals("")) { continue; } List<String> ec2RegionList = PrivateKeyDB.getEC2Regions(); //remove Formating Char String tags = profile.getTag().replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", ""); String[] tagArr1 = tags.split(","); Map<String, String> tagMap = new HashMap<>(); List<String> tagList = new ArrayList<>(); if (tagArr1.length > 0) { for (String tag1 : tagArr1) { String[] tagArr2 = tag1.split("="); if (tagArr2.length > 1) { tagMap.put(tag1.split("=")[0], tag1.split("=")[1]); } else { tagList.add(tag1); } } } //get AWS credentials from DB for (AWSCred awsCred : AWSCredDB.getAWSCredList()) { if (awsCred != null && awsCred.isValid()) { //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 (ApplicationKey ec2Key : PrivateKeyDB.getEC2KeyByRegion(ec2Region)) { if (ec2Key.isEnabled()) { keyValueList.add(ec2Key.getKeyname()); } } DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); Filter keyNmFilter = new Filter("key-name", keyValueList); describeInstancesRequest.withFilters(keyNmFilter); if (tagList.size() > 0) { Filter tagFilter = new Filter("tag-key", tagList); describeInstancesRequest.withFilters(tagFilter); } //set name value pair for tag filter for (String tag : tagMap.keySet()) { Filter tagValueFilter = new Filter("tag:" + tag, Arrays.asList(tagMap.get(tag))); describeInstancesRequest.withFilters(tagValueFilter); } DescribeInstancesResult describeInstancesResult = service .describeInstances(describeInstancesRequest); for (Reservation res : describeInstancesResult.getReservations()) { for (Instance instance : res.getInstances()) { HostSystem ec2System = SystemDB.getSystemByInstance(instance.getInstanceId()); addSystemToProfile(profile.getId(), ec2System.getId()); } } } } } } } catch (AmazonServiceException ex) { ex.printStackTrace(); } }
From source file:com.keybox.manage.db.SystemDB.java
License:Apache License
/** * Update AWS Systems/*from w ww .j a va2 s . com*/ * <br><br> * Update all EC2 System based on setting AWS Credentials and the EC2 Keys * and added new System */ public static void updateAWSSystems() { List<String> ec2RegionList = PrivateKeyDB.getEC2Regions(); try { //get AWS credentials from DB for (AWSCred awsCred : AWSCredDB.getAWSCredList()) { if (awsCred != null && awsCred.isValid()) { //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 (ApplicationKey ec2Key : PrivateKeyDB.getEC2KeyByRegion(ec2Region)) { if (ec2Key.isEnabled()) { keyValueList.add(ec2Key.getKeyname()); } } DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); Filter keyNmFilter = new Filter("key-name", keyValueList); describeInstancesRequest.withFilters(keyNmFilter); DescribeInstancesResult describeInstancesResult = service .describeInstances(describeInstancesRequest); for (Reservation res : describeInstancesResult.getReservations()) { for (Instance instance : res.getInstances()) { HostSystem hostSystem = transformerEC2InstanzToHostSystem(instance, ec2Region); setEC2System(hostSystem); } } } } } } catch (AmazonServiceException ex) { ex.printStackTrace(); } }
From source file:com.noctarius.hazelcast.aws.HazelcastAwsDiscoveryStrategy.java
License:Open Source License
private void configureFilter(DescribeInstancesRequest instancesRequest, String key, String... values) { instancesRequest.withFilters(new Filter(key).withValues(values)); }
From source file:datameer.awstasks.ant.ec2.Ec2ListRunningInstances.java
License:Apache License
private DescribeInstancesRequest createDescribeRequest() { DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); Multimap<String, String> keyToValuesMap = combineFiltersWithSameName(); Set<String> keySet = keyToValuesMap.keySet(); for (String key : keySet) { describeInstancesRequest.withFilters(new Filter(key, ImmutableList.copyOf(keyToValuesMap.get(key)))); }//from ww w . j av a 2s. c o m return describeInstancesRequest; }
From source file:n3phele.factory.ec2.VirtualServerResource.java
License:Open Source License
/** * Assimilating a VM is the process of looking for an instance in the Amazon cloud, * getting it's details and storing it in the factory database if it's not there yet. * This is used when instances are created from outside of the factory (e.g. using Juju) * and the factory needs to know about their existence to use them in other operations. * @param request/*from ww w . j a va2 s.co m*/ * information about the instance to be looked up in the cloud * @return * response code informing success or failure in the search and assimilation */ @POST @Produces("application/json") @RolesAllowed("authenticated") @Path("virtualServer/assimilate") public Response assimilate(ExecutionFactoryAssimilateRequest request) { final String TAG = "Assimilate VM: "; logger.info(TAG + "EC2 Assimilating VM Begin"); logger.info(TAG + "Looking for IP " + request.ipaddress + " on " + request.location); // Search for instance with the following ip address Filter ipFilter = new Filter(); ipFilter.setName("ip-address"); ipFilter.withValues(request.ipaddress); // This request searches in running instances for one instance that mathes the filters DescribeInstancesRequest amazonRequest = new DescribeInstancesRequest(); amazonRequest.withFilters(ipFilter); // Authenticate an Amazon connection AmazonEC2Client amazonClient = getEC2Client(request.accessKey, request.encryptedSecret, request.location); // Execute request DescribeInstancesResult amazonResponse = amazonClient.describeInstances(amazonRequest); // Reservations are "sessions" that start a list of instances if (amazonResponse.getReservations().size() == 0) { logger.warning(TAG + "IP not found on Amazon cloud"); return Response.status(Response.Status.NOT_FOUND).build(); } logger.info(TAG + "IP found on Amazon cloud, looking for instance id on Amazon factory"); // We're expecting one instance with the requested IP, getting index 0 should cover this Reservation foundReservation = amazonResponse.getReservations().get(0); List<Instance> reservationInstances = foundReservation.getInstances(); Instance foundInstance = reservationInstances.get(0); String instanceId = foundInstance.getInstanceId(); List<VirtualServer> listVS = getByInstanceId(instanceId); if (listVS.size() > 0) { logger.warning(TAG + "Instance already exists on Amazon factory"); return Response.status(Response.Status.CONFLICT).build(); } logger.info(TAG + "Instance not found on Amazon factory, adding VM to factory"); // Required data for VM creation below ArrayList<NameValue> paramsVM = new ArrayList<NameValue>(); NameValue paramLocation = new NameValue(); NameValue paramFlavor = new NameValue(); paramLocation.setKey("locationId"); paramLocation.setValue(request.locationId); paramsVM.add(paramLocation); paramFlavor.setKey("instanceType"); paramFlavor.setValue(foundInstance.getInstanceType()); paramsVM.add(paramFlavor); // Instance name is in tag key "Name", assuming first tag is the name List<Tag> instanceTags = foundInstance.getTags(); String instanceName = null; if (instanceTags.size() == 0) { instanceName = instanceId; } else { Tag tagName = instanceTags.get(0); instanceName = tagName.getValue(); } VirtualServer virtualServer = new VirtualServer(instanceName, request.description, request.location, paramsVM, request.notification, request.accessKey, request.encryptedSecret, request.owner, request.idempotencyKey); virtualServer.setCreated(foundInstance.getLaunchTime()); virtualServer.setInstanceId(instanceId); add(virtualServer); logger.info(TAG + "Succesfully added VM to factory"); List<URI> virtualMachinesRefs = new ArrayList<URI>(1); virtualMachinesRefs.add(virtualServer.getUri()); return Response.created(virtualServer.getUri()).entity(new CreateVirtualServerResponse(virtualMachinesRefs)) .build(); }
From source file:org.apache.usergrid.chop.api.store.amazon.EC2InstanceManager.java
License:Apache License
/** * @param name Causes the method to return instances with given Name tag, give null if you want to get * instances with all names * @param state Causes the method to return instances with given state, give null if you want to get instances in * all states// w w w. j a va 2 s . c o m * @return all instances that satisfy given parameters */ protected Collection<com.amazonaws.services.ec2.model.Instance> getEC2Instances(String name, InstanceStateName state) { Collection<com.amazonaws.services.ec2.model.Instance> instances = new LinkedList<com.amazonaws.services.ec2.model.Instance>(); DescribeInstancesRequest request = new DescribeInstancesRequest(); if (name != null) { List<String> valuesT1 = new ArrayList<String>(); valuesT1.add(name); Filter filter = new Filter("tag:Name", valuesT1); request = request.withFilters(filter); } if (state != null) { List<String> valuesT1 = new ArrayList<String>(); valuesT1.add(state.toString()); Filter filter = new Filter("instance-state-name", valuesT1); request = request.withFilters(filter); } DescribeInstancesResult result = null; try { result = client.describeInstances(request); } catch (Exception e) { LOG.error("Error while getting instance information from AWS.", e); return Collections.EMPTY_LIST; } for (Reservation reservation : result.getReservations()) { for (com.amazonaws.services.ec2.model.Instance in : reservation.getInstances()) { instances.add(in); } } return instances; }
From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java
License:Open Source License
@Override public boolean stopMachine(final String serverIp, final long duration, final TimeUnit unit) throws CloudProvisioningException, TimeoutException, InterruptedException { if (logger.isLoggable(Level.FINEST)) { logger.finest(/*from w w w. ja v a2 s. com*/ "Stopping new machine with the following thread: threadId=" + Thread.currentThread().getId() + " serviceName=" + this.serviceName + " serverIp=" + serverIp); } logger.info("Stopping instance server ip = " + serverIp + "..."); final DescribeInstancesRequest describeInstance = new DescribeInstancesRequest(); describeInstance.withFilters(new Filter("private-ip-address", Arrays.asList(serverIp))); final DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstance); final Reservation reservation = describeInstances.getReservations().get(0); if (reservation != null && reservation.getInstances().get(0) != null) { final TerminateInstancesRequest tir = new TerminateInstancesRequest(); tir.withInstanceIds(reservation.getInstances().get(0).getInstanceId()); final TerminateInstancesResult terminateInstances = ec2.terminateInstances(tir); final String instanceId = terminateInstances.getTerminatingInstances().get(0).getInstanceId(); try { this.waitStopInstanceStatus(instanceId, duration, unit); } finally { // FIXME By default, cloudify doesn't delete tags. So we should keep it that way. // Remove instance Tags // if (!terminateInstances.getTerminatingInstances().isEmpty()) { // logger.fine("Deleting tags for instance id=" + instanceId); // DeleteTagsRequest deleteTagsRequest = new DeleteTagsRequest(); // deleteTagsRequest.setResources(Arrays.asList(instanceId)); // ec2.deleteTags(deleteTagsRequest); // } } } else { logger.warning("No instance to stop: " + reservation); } return true; }