List of usage examples for com.amazonaws.services.ec2 AmazonEC2 describeInstances
DescribeInstancesResult describeInstances(DescribeInstancesRequest describeInstancesRequest);
Describes the specified instances or all of AWS account's instances.
From source file:InstallYarn.java
License:Open Source License
public static void main(String[] args) throws JSchException, IOException, InterruptedException { /*/*from w w w .j a v a2 s . c om*/ * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (C:\\Users\\CH\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new BasicAWSCredentials("Your Access Key ID", "Your Secret Access Key"); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (C:\\Users\\CH\\.aws\\credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); ec2.setRegion(usWest2); /* // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest( "GettingStartedGroup", "Getting Started Security Group"); CreateSecurityGroupResult result = ec2 .createSecurityGroup(securityGroupRequest); System.out.println(String.format("Security group created: [%s]", result.getGroupId())); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { InetAddress addr = InetAddress.getLocalHost(); // Get IP Address ipAddr = addr.getHostAddress()+"/10"; } catch (UnknownHostException e) { } // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). IpPermission ipPermission = new IpPermission() .withIpProtocol("tcp") .withFromPort(new Integer(22)) .withToPort(new Integer(22)) .withIpRanges(ipRanges); List<IpPermission> ipPermissions = Collections.singletonList(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString())); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } */ //CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() //.withKeyName("CHENHAO"); //CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest); //KeyPair keyPair = new KeyPair(); //keyPair = createKeyPairResult.getKeyPair(); //String privateKey = keyPair.getKeyMaterial(); int cluster_size = Integer .parseInt(JOptionPane.showInputDialog("Enter number of machines you want to set")); String ami_name = JOptionPane.showInputDialog("Enter your ami name"); String key_name = JOptionPane.showInputDialog("Enter your key name"); String s_group_name = JOptionPane.showInputDialog("Enter your security group name"); RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId(ami_name).withInstanceType("t2.micro").withMinCount(cluster_size) .withMaxCount(cluster_size).withKeyName(key_name).withSecurityGroups(s_group_name); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); Thread.sleep(10000); Vector<String> instanceId = new Vector<String>(); for (Instance ins : runInstancesResult.getReservation().getInstances()) instanceId.add(ins.getInstanceId()); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(instanceId); DescribeInstancesResult result = ec2.describeInstances(request); List<Reservation> reservations = result.getReservations(); List<Instance> instances_list = new Vector<Instance>(); for (int i = 0; i < reservations.size(); i++) instances_list.addAll(reservations.get(i).getInstances()); System.out.println("Plan cluster size:" + cluster_size + " Real size:" + instances_list.size()); JSch jsch = new JSch(); JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Choose your privatekey"); chooser.setFileHidingEnabled(false); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose " + chooser.getSelectedFile().getAbsolutePath() + "."); jsch.addIdentity(chooser.getSelectedFile().getAbsolutePath()); } Session session; UserInfo ui = new MyUserInfo(); for (int i = 0; i < instances_list.size(); i++) { if (instances_list.get(i).getPublicIpAddress() == null) System.out.println("Error, public ip is null\n"); System.out.println("Connect to:" + instances_list.get(i).getPublicIpAddress() + "\n"); session = jsch.getSession("ubuntu", instances_list.get(i).getPublicIpAddress(), 22); session.setUserInfo(ui); session.connect(); // //if(i==0) //{ // transfer_file_to("/home/ubuntu","C:/Users/CH/Downloads/ch.pem",session); // exec("chmod 400 /home/ubuntu/ch.pem",session); //} //slaves file for (int j = 0; j < instances_list.size(); j++) { if (j != 0) exec("echo " + instances_list.get(j).getPrivateIpAddress() + "\n >> /usr/local/hadoop/etc/hadoop/slaves", session); } //core-site file String command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress() + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); //hdfs-size file command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress() + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); command = "sed -i 's#replication#" + Integer.toString(cluster_size - 1) + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); //yarn-size file command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress() + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); session.disconnect(); } //username and passphrase will be given via UserInfo interface. //slaves file }
From source file:aws.example.ec2.DescribeInstances.java
License:Open Source License
public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); boolean done = false; while (!done) { DescribeInstancesRequest request = new DescribeInstancesRequest(); DescribeInstancesResult response = ec2.describeInstances(request); for (Reservation reservation : response.getReservations()) { for (Instance instance : reservation.getInstances()) { System.out.printf( "Found reservation with id %s, " + "AMI %s, " + "type %s, " + "state %s " + "and monitoring state %s", instance.getInstanceId(), instance.getImageId(), instance.getInstanceType(), instance.getState().getName(), instance.getMonitoring().getState()); }/*from w ww .ja v a2 s. co m*/ } request.setNextToken(response.getNextToken()); if (response.getNextToken() == null) { done = true; } } }
From source file:br.com.ingenieux.mojo.beanstalk.env.DumpInstancesMojo.java
License:Apache License
@Override protected Object executeInternal() throws Exception { AmazonEC2 ec2 = clientFactory.getService(AmazonEC2Client.class); DescribeEnvironmentResourcesResult envResources = getService().describeEnvironmentResources( new DescribeEnvironmentResourcesRequest().withEnvironmentId(curEnv.getEnvironmentId()) .withEnvironmentName(curEnv.getEnvironmentName())); List<String> instanceIds = new ArrayList<String>(); for (Instance i : envResources.getEnvironmentResources().getInstances()) { instanceIds.add(i.getId());//from ww w. ja va 2s . c o m } DescribeInstancesResult ec2Instances = ec2 .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds)); PrintStream printStream = null; if (null != outputFile) { printStream = new PrintStream(outputFile); } for (Reservation r : ec2Instances.getReservations()) { for (com.amazonaws.services.ec2.model.Instance i : r.getInstances()) { String ipAddress = dumpPrivateAddresses ? i.getPrivateIpAddress() : StringUtils.defaultString(i.getPublicIpAddress(), i.getPrivateDnsName()); String instanceId = i.getInstanceId(); if (null != printStream) { printStream.println(ipAddress + " # " + instanceId); } else { getLog().info(" * " + instanceId + ": " + ipAddress); } } } if (null != printStream) { printStream.close(); } return null; }
From source file:c3.ops.priam.aws.AWSMembership.java
License:Apache License
public List<String> getRunningInstancesByTags(String tagName, List<String> values) { AmazonEC2 client = null; try {/*from w w w. j av a2s . c om*/ List<String> instanceIds = Lists.newArrayList(); List<String> states = new ArrayList<String>(); client = getEc2Client(); states.add("running"); DescribeInstancesRequest req = new DescribeInstancesRequest() .withFilters(new Filter("tag:" + tagName, values), new Filter("instance-state-name", states)); for (Reservation reservation : client.describeInstances(req).getReservations()) { for (Instance instance : reservation.getInstances()) { instanceIds.add(instance.getInstanceId()); logger.info(String.format("Querying Amazon returned following instance in the Ring: %s --> %s", config.getRac(), StringUtils.join(instanceIds, ","))); } } return instanceIds; } finally { if (client != null) client.shutdown(); } }
From source file:com.appdynamics.connectors.AWSConnector.java
License:Apache License
private Instance getEc2Instance(IMachine machine, AmazonEC2 connector) throws ConnectorException { DescribeInstancesResult describeInstancesResult = null; try {/*from w w w.j a v a2 s . c o m*/ DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); describeInstancesResult = connector .describeInstances(describeInstancesRequest.withInstanceIds(machine.getName())); List<Reservation> reservations = describeInstancesResult.getReservations(); if (reservations.size() == 0) { // machine not found MUST have been terminated return null; } // always it will be in the first reservation as the query is on // only one machine List<Instance> instances = reservations.get(0).getInstances(); for (Instance instance : instances) { if (instance.getInstanceId().equals(machine.getName())) { // found the machine return instance; } } } catch (Exception e) { throw new ConnectorException(e); } return null; }
From source file:com.axemblr.provisionr.amazon.activities.AllInstancesMatchPredicate.java
License:Apache License
@Override public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws Exception { @SuppressWarnings("unchecked") List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS); checkNotNull(instanceIds, "process variable '{}' not found", ProcessVariables.INSTANCE_IDS); try {/*w w w.j av a 2 s . c o m*/ DescribeInstancesResult result = client .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds)); checkState(result.getReservations().size() == 1, "the instance ids are part of multiple reservations"); List<Instance> instances = result.getReservations().get(0).getInstances(); if (Iterables.all(instances, predicate)) { LOG.info(">> All {} instances match predicate {} ", instanceIds, predicate); execution.setVariable(resultVariable, true); } else { LOG.info("<< Not all instances {} match predicate {}", instanceIds, predicate); execution.setVariable(resultVariable, false); } } catch (AmazonServiceException exception) { if (exception.getErrorCode().equalsIgnoreCase("InvalidInstanceID.NotFound")) { LOG.warn("<< Got error InvalidInstanceID.NotFound. Assuming predicate {} is false", predicate); execution.setVariable(resultVariable, false); } else { throw Throwables.propagate(exception); } } }
From source file:com.axemblr.provisionr.amazon.activities.PublishListOfMachines.java
License:Apache License
@Override public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws Exception { @SuppressWarnings("unchecked") List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS); checkNotNull(instanceIds, "%s not found as a process variable", ProcessVariables.INSTANCE_IDS); LOG.info(">> Describing instances {}", instanceIds); DescribeInstancesResult result = client .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds)); checkArgument(result.getReservations().size() == 1, "found more than one reservation"); Reservation reservation = result.getReservations().get(0); LOG.info("<< Got one reservation with {} running instances", reservation.getInstances().size()); List<Machine> machines = Lists.transform(reservation.getInstances(), new Function<Instance, Machine>() { @Override/* w w w .ja v a2 s .co m*/ public Machine apply(Instance instance) { return Machine.builder().externalId(instance.getInstanceId()) .publicDnsName(instance.getPublicDnsName()).publicIp(instance.getPublicIpAddress()) .privateDnsName(instance.getPrivateDnsName()).privateIp(instance.getPrivateIpAddress()) .createMachine(); } }); /* Create a new ArrayList to force evaluation for lazy collections */ execution.setVariable(CoreProcessVariables.MACHINES, Lists.newArrayList(machines)); }
From source file:com.bloomreach.bstore.highavailability.zookeeper.ZkClient.java
License:Apache License
/** * Fetch the public DNS names for the corresponding private Ips. SolrCloud defaults to private ips for all * interactions. If you want to run HAFT locally to copy data across 2 different zookeeper clusters, then we need * public IP translations to access the index. This method helps achieve that. * * @return {@link #getZkClusterData()} with private Ip to Public DNS Mapping based on EC2 api. *///w w w . j a va2s . c o m public ZkClusterData translatePrivateIpToPublicHostNames() { AWSCredentials credentials = new BasicAWSCredentials(AwsConfigReader.fetchAccessKey(), AwsConfigReader.fetchSecretyKey()); AmazonEC2 ec2 = new AmazonEC2Client(credentials); Set<String> publicDnsNameHosts = new HashSet<String>(); Map<String, String> privateIptoPublicHostNames = new HashMap<String, String>(); if (allSolrNodes.isEmpty()) { logger.info("No valid solr hosts are found. Cannot do any mapping"); return zkClusterData; } //Describe Filter with private-ips matching all solr nodes DescribeInstancesRequest request = new DescribeInstancesRequest() .withFilters(new Filter("private-ip-address").withValues(allSolrNodes)); DescribeInstancesResult describeInstancesResult = ec2.describeInstances(request); List<Reservation> reservations = describeInstancesResult.getReservations(); //Iterate over all instances and map their private Ip to Public Host Name logger.info("Fetching Public HostNames...."); for (Reservation reservation : reservations) { List<Instance> instances = reservation.getInstances(); for (Instance instance : instances) { logger.info("Private to Public Name of the Host is " + instance.getPrivateIpAddress() + " => " + instance.getPublicDnsName()); publicDnsNameHosts.add(instance.getPublicDnsName()); privateIptoPublicHostNames.put(instance.getPrivateIpAddress(), instance.getPublicDnsName()); } } //Point all zk data to point to the public dns names zkClusterData.updateSolrNodes(publicDnsNameHosts); //Set the data in a map so that it doesn't need to get recomputed by every function needing hostnames zkClusterData.setPrivateIpToPublicHostNameMap(privateIptoPublicHostNames); return zkClusterData; }
From source file:com.dowdandassociates.gentoo.bootstrap.InstanceUtils.java
License:Apache License
public static Optional<Instance> onDemandInstance(AmazonEC2 ec2Client, Optional<Image> image, Integer minCount, Integer maxCount, SecurityGroupInformation securityGroupInformation, KeyPairInformation keyPairInformation, Optional<String> instanceType, Optional<String> availabilityZone, Long sleep) {// w w w. j av a2 s . c o m if (!image.isPresent()) { return Optional.absent(); } RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(image.get().getImageId()) .withMinCount(minCount).withMaxCount(maxCount) .withSecurityGroups(securityGroupInformation.getGroupName()) .withKeyName(keyPairInformation.getName()); log.info("ImageId=" + image.get().getImageId()); log.info("MinCount=" + minCount); log.info("MaxCount=" + maxCount); log.info("SecurityGroups.1=" + securityGroupInformation.getGroupName()); log.info("KeyName=" + keyPairInformation.getName()); if (instanceType.isPresent()) { runInstancesRequest.setInstanceType(instanceType.get()); log.info("InstanceType=" + instanceType.get()); } if (availabilityZone.isPresent()) { runInstancesRequest.setPlacement(new Placement().withAvailabilityZone(availabilityZone.get())); log.info("Placement.AvailabilityZone=" + availabilityZone.get()); } RunInstancesResult runInstancesResult = ec2Client.runInstances(runInstancesRequest); DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest() .withInstanceIds(runInstancesResult.getReservation().getInstances().get(0).getInstanceId()); try { while (true) { log.info("Sleeping for " + sleep + " ms"); Thread.sleep(sleep); DescribeInstanceStatusResult describeInstanceStatusResult = ec2Client .describeInstanceStatus(describeInstanceStatusRequest); if (describeInstanceStatusResult.getInstanceStatuses().isEmpty()) { continue; } InstanceStatus instance = describeInstanceStatusResult.getInstanceStatuses().get(0); String instanceState = instance.getInstanceState().getName(); log.info("instanceState = " + instanceState); if ("pending".equals(instanceState)) { continue; } if (!"running".equals(instanceState)) { return Optional.absent(); } String instanceStatus = instance.getInstanceStatus().getStatus(); String systemStatus = instance.getSystemStatus().getStatus(); log.info("instanceStatus = " + instanceStatus); log.info("systemStatus = " + systemStatus); if ("impaired".equals(instanceStatus)) { return Optional.absent(); } if ("impaired".equals(systemStatus)) { return Optional.absent(); } if (!"ok".equals(instanceStatus)) { continue; } if (!"ok".equals(systemStatus)) { continue; } break; } } catch (InterruptedException e) { return Optional.absent(); } DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(new DescribeInstancesRequest() .withInstanceIds(runInstancesResult.getReservation().getInstances().get(0).getInstanceId())); return Optional.fromNullable(describeInstancesResult.getReservations().get(0).getInstances().get(0)); }
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 va 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; }