Example usage for com.amazonaws.services.cloudwatch AmazonCloudWatchClient AmazonCloudWatchClient

List of usage examples for com.amazonaws.services.cloudwatch AmazonCloudWatchClient AmazonCloudWatchClient

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudwatch AmazonCloudWatchClient AmazonCloudWatchClient.

Prototype

AmazonCloudWatchClient(AwsSyncClientParams clientParams) 

Source Link

Document

Constructs a new client to invoke service methods on CloudWatch using the specified parameters.

Usage

From source file:imperial.modaclouds.monitoring.datacollectors.monitors.CostMonitor.java

License:BSD License

@Override
public void run() {

    String accessKeyId = null;/*from  ww  w. j a v  a  2s .c  o  m*/

    String secretKey = null;

    ArrayList<String> measureNames = null;

    long startTime = 0;

    while (!cwmt.isInterrupted()) {

        if (System.currentTimeMillis() - startTime > 10000) {

            measureNames = new ArrayList<String>();

            for (String metric : getProvidedMetrics()) {
                try {
                    VM resource = new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId());
                    if (dcAgent.shouldMonitor(resource, metric)) {
                        Map<String, String> parameters = dcAgent.getParameters(resource, metric);

                        measureNames.add("EstimatedCharges");

                        accessKeyId = parameters.get("accessKey");
                        secretKey = parameters.get("secretKey");
                        period = Integer.valueOf(parameters.get("samplingTime")) * 1000;
                        samplingProb = Double.valueOf(parameters.get("samplingProbability"));
                    }
                } catch (NumberFormatException | ConfigurationException e) {
                    e.printStackTrace();
                }
            }

            cloudWatchClient = new AmazonCloudWatchClient(new BasicAWSCredentials(accessKeyId, secretKey));
            cloudWatchClient.setEndpoint("monitoring.us-east-1.amazonaws.com");

            startTime = System.currentTimeMillis();
        }

        MeasureSet measureSet = null;
        try {
            measureSet = this.retrieveMeasureSet(measureNames);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (measureSet != null) {
            for (String measureName : measureSet.getMeasureNames()) {
                try {
                    if (Math.random() < samplingProb) {
                        logger.info("Sending datum: {} {} {}", measureSet.getMeasure(measureName), "Cost",
                                monitoredTarget);
                        dcAgent.send(new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()),
                                "Cost", measureSet.getMeasure(measureName));
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //System.out.println(measureName+"  "+String.valueOf(measureSet.getMeasure(measureName)));
                //measure.push(measureName, String.valueOf(measureSet.getMeasure(measureName)),"EC2");
            }
        }
        try {
            Thread.sleep(period);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            break;
        }

    }
}

From source file:org.alfresco.provision.CloudWatchMonitor.java

License:Open Source License

public CloudWatchMonitor(String instanceId, String accessKeyId, String secretAccesskey) {
    AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, secretAccesskey);
    cloudWatchClient = new AmazonCloudWatchClient(awsCredentials);
    cloudWatchClient.setRegion(Region.getRegion(Regions.EU_WEST_1));
    this.instanceId = instanceId;
}

From source file:org.apache.airavata.gfac.ec2.AmazonInstanceScheduler.java

License:Apache License

/**
 * Monitors the CPU Utilization using Amazon Cloud Watch. In order to monitor the instance, Cloud Watch Monitoring
 * should be enabled for the running instance.
 *
 * @param credential EC2 credentials/*ww  w . java2 s . co m*/
 * @param instanceId instance id
 * @return average CPU utilization of the instance
 */
public static double monitorInstance(AWSCredentials credential, String instanceId) {
    try {
        AmazonCloudWatchClient cw = new AmazonCloudWatchClient(credential);

        long offsetInMilliseconds = 1000 * 60 * 60 * 24;
        GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
                .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds)).withNamespace("AWS/EC2")
                .withPeriod(60 * 60)
                .withDimensions(new Dimension().withName("InstanceId").withValue(instanceId))
                .withMetricName("CPUUtilization").withStatistics("Average", "Maximum").withEndTime(new Date());
        GetMetricStatisticsResult getMetricStatisticsResult = cw.getMetricStatistics(request);

        double avgCPUUtilization = 0;
        List dataPoint = getMetricStatisticsResult.getDatapoints();
        for (Object aDataPoint : dataPoint) {
            Datapoint dp = (Datapoint) aDataPoint;
            avgCPUUtilization = dp.getAverage();
            log.info(instanceId + " instance's average CPU utilization : " + dp.getAverage());
        }

        return avgCPUUtilization;

    } catch (AmazonServiceException ase) {
        log.error("Caught an AmazonServiceException, which means the request was made  "
                + "to Amazon EC2, but was rejected with an error response for some reason.");
        log.error("Error Message:    " + ase.getMessage());
        log.error("HTTP Status Code: " + ase.getStatusCode());
        log.error("AWS Error Code:   " + ase.getErrorCode());
        log.error("Error Type:       " + ase.getErrorType());
        log.error("Request ID:       " + ase.getRequestId());

    }
    return 0;
}

From source file:org.apache.camel.component.aws.cw.CwEndpoint.java

License:Apache License

AmazonCloudWatch createCloudWatchClient() {
    AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(),
            configuration.getSecretKey());
    AmazonCloudWatch client = new AmazonCloudWatchClient(credentials);
    if (configuration.getAmazonCwEndpoint() != null) {
        client.setEndpoint(configuration.getAmazonCwEndpoint());
    }/*w ww. j  a  v a 2s  .  co  m*/
    return client;
}

From source file:org.apache.hadoop.metrics.cloudwatch.CloudWatchContext.java

License:Apache License

@Override
public void init(String contextName, ContextFactory factory) {
    super.init(contextName, factory);

    String accessKey = getAttribute("accesskey");
    String secretKey = getAttribute("secretkey");
    String region = getAttribute("region");
    String namespace = getAttribute("namespace");

    try {/*from  ww  w. j  a v  a2  s .c  o m*/
        _namespace = (null == namespace ? "Custom" : namespace);

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        _client = new AmazonCloudWatchClient(awsCredentials);
        _client.setRegion(Region.getRegion(Regions.fromName(region)));
    } catch (Exception e) {
        throw new MetricsException(e.getMessage());
    }
}

From source file:org.apache.hadoop.metrics2.cloudwatch.CloudWatchSink.java

License:Apache License

@Override
public void init(SubsetConfiguration conf) {
    String accessKey = conf.getString("accesskey");
    String secretKey = conf.getString("secretkey");
    String region = conf.getString("region");
    String namespace = conf.getString("namespace");
    String batch = conf.getString("batch");

    try {//from  w ww  . j  a  v a 2s.c o  m
        _namespace = (null == namespace ? "Custom" : namespace);
        _batch = (null == batch ? 5 : Integer.valueOf(batch));

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        _client = new AmazonCloudWatchClient(awsCredentials);
        _client.setRegion(Region.getRegion(Regions.fromName(region)));
    } catch (Exception e) {
        throw new MetricsException(e.getMessage());
    }
}

From source file:org.elasticdroid.model.CloudWatchMetricsModel.java

License:Open Source License

/**
 * Retrieve the list of metrics// w  w  w .  j av a 2  s .  co m
 * 
 * @return Either
 * <ul>
 *    <li>AmazonServiceException</li>
 *  <li>AmazonClientException</li>
 *  <li>List\<Metric\></li>
 * </ul>
 */
public Object retrieveMetricsList(Dimension... dimensions) {
    //the cloudwatch client to use
    AmazonCloudWatchClient cloudWatchClient = null;
    List<Metric> returnedMetrics = null;
    ArrayList<String> measureNames = new ArrayList<String>();
    ListMetricsRequest request = new ListMetricsRequest();

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));

    //create a cloudwatch client
    try {
        cloudWatchClient = new AmazonCloudWatchClient(credentials);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    cloudWatchClient.setEndpoint(cloudWatchEndpoint);

    //create the request
    request = new ListMetricsRequest();
    //request.setNextToken(nextToken)
    try {
        returnedMetrics = cloudWatchClient.listMetrics().getMetrics();
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //my own disgusting O(mnp) filter. This is REALLY CRAP!
    //remove all that does not fit into the dimension
    //for some reason, there isn't a way to provide dimensions using ListMetricsRequest in Java
    //you can do it in the C# API though :P
    List<Dimension> returnedDimensions;
    boolean added;
    for (Metric metric : returnedMetrics) {
        returnedDimensions = metric.getDimensions();
        added = false;
        for (Dimension returnedDimension : returnedDimensions) {
            //check if any of the dimensions passed in to the model are equal to this.
            for (Dimension dimension : dimensions) {
                if (returnedDimension.getValue().equals(dimension.getValue())) {
                    measureNames.add(metric.getMeasureName());
                    added = true;
                    break;
                }
            }

            if (added) {
                break;
            }
        }
    }

    return measureNames;
}

From source file:org.elasticdroid.model.MonitorInstanceModel.java

License:Open Source License

/** 
 * Perform the actual work of retrieving the metrics
 *//*  w  w  w. j  a  va  2 s  . c om*/
public Object retrieveMetrics(Dimension... dimensions) {
    //the cloudwatch client to use
    AmazonCloudWatchClient cloudWatchClient = null;
    //the request to send to cloudwatch
    GetMetricStatisticsRequest request;
    //the metric stats result.
    GetMetricStatisticsResult result;

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create a cloudwatch client
    try {
        cloudWatchClient = new AmazonCloudWatchClient(credentials);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //prepare request
    request = new GetMetricStatisticsRequest();
    request.setStartTime(new Date(cloudWatchInput.getStartTime()));
    request.setEndTime(new Date(cloudWatchInput.getEndTime()));
    request.setPeriod(cloudWatchInput.getPeriod());
    request.setMeasureName(cloudWatchInput.getMeasureName());
    request.setNamespace(cloudWatchInput.getNamespace());
    request.setStatistics(cloudWatchInput.getStatistics());
    request.setDimensions(Arrays.asList(dimensions));
    //tell the cloudwatch client where to look!
    cloudWatchClient.setEndpoint(AWSConstants.getCloudWatchEndpoint(cloudWatchInput.getRegion()));

    //get the monitoring result!
    try {
        result = cloudWatchClient.getMetricStatistics(request);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //get the data and print it out.
    List<Datapoint> data = result.getDatapoints();
    for (Datapoint datum : data) {
        Log.v(TAG, "Datum:" + datum.getAverage());
    }

    //sort the data in ascending order of timestamps
    Collections.sort(data, new CloudWatchDataSorter());

    //return the sorted data
    return data;
}

From source file:org.onebusaway.aws.cloudwatch.impl.CloudwatchServiceImpl.java

License:Apache License

public void setup() {
    String accessKey = _configurationService.getConfigurationValueAsString("aws.accessKey", "");
    String secretKey = _configurationService.getConfigurationValueAsString("aws.secretKey", "");

    endPoint = _configurationService.getConfigurationValueAsString("aws.endPoint",
            "monitoring.us-east-1.amazonaws.com");
    environmentName = _configurationService.getConfigurationValueAsString("oba.env", "dev");

    AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(
            new BasicAWSCredentials(accessKey, secretKey));
    cloudWatch.setEndpoint(endPoint);/*from w  w w  . j  av a 2 s  .c o m*/
    this.cloudWatch = cloudWatch;
}