software.amazon.awssdk.services.cloudwatch.CloudWatchClient Java Examples

The following examples show how to use software.amazon.awssdk.services.cloudwatch.CloudWatchClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DisableAlarmActions.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
                "To run this example, supply an alarm name\n" +
                        "Ex: DisableAlarmActions <alarm-name>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String alarmName = args[0];

        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        disableActions(cw, alarmName) ;
    }
 
Example #2
Source File: DisableAlarmActions.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void disableActions(CloudWatchClient cw, String alarmName) {

        try {
             DisableAlarmActionsRequest request = DisableAlarmActionsRequest.builder()
                .alarmNames(alarmName).build();

            DisableAlarmActionsResponse response = cw.disableAlarmActions(request);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        System.out.printf(
                "Successfully disabled actions on alarm %s", alarmName);
    }
 
Example #3
Source File: DeleteAlarm.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
                "To run this example, supply an alarm name\n" +
                        "Ex: DeleteAlarm <alarm-name>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String alarmName = args[0];
        Region region = Region.US_EAST_2;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        deleteCWAlarm(cw, alarmName) ;
    }
 
Example #4
Source File: ListMetrics.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
                "To run this example, supply a metric namespace\n" +
                        "Ex: ListMetrics <metric-namespace>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String namespace = args[0];

        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        listMets(cw, namespace) ;

    }
 
Example #5
Source File: PutMetricData.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
                "To run this example, supply a data point:\n" +
                        "Example: PutMetricData <data_point>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        Double dataPoint = Double.parseDouble(args[0]);

        Region region = Region.US_WEST_2;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        putMetData(cw, dataPoint) ;
    }
 
Example #6
Source File: PutMetricData.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void putMetData(CloudWatchClient cw, Double dataPoint ) {

        try {
            Dimension dimension = Dimension.builder()
                .name("UNIQUE_PAGES")
                .value("URLS").build();

            MetricDatum datum = MetricDatum.builder()
                .metricName("PAGES_VISITED")
                .unit(StandardUnit.NONE)
                .value(dataPoint)
                .dimensions(dimension).build();

            PutMetricDataRequest request = PutMetricDataRequest.builder()
                .namespace("SITE/TRAFFIC")
                .metricData(datum).build();

            PutMetricDataResponse response = cw.putMetricData(request);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.printf("Successfully put data point %f", dataPoint);
        // snippet-end:[cloudwatch.java2.put_metric_data.main]
    }
 
Example #7
Source File: EnableAlarmActions.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void enableActions(CloudWatchClient cw, String alarm) {

        try {
            EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder()
                .alarmNames(alarm).build();

            EnableAlarmActionsResponse response = cw.enableAlarmActions(request);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        // snippet-end:[cloudwatch.java2.enable_alarm_actions.main]
        System.out.printf(
                "Successfully enabled actions on alarm %s", alarm);
    }
 
Example #8
Source File: PutMetricAlarm.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
                "To run this example, supply an alarm name and instance ID\n" +
                        "Example: PutMetricAlarm <alarm-name> <instance-id>\n";

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String alarmName = args[0];
        String instanceId = args[1];

        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        putMetricAlarm(cw, alarmName, instanceId) ;
    }
 
Example #9
Source File: StreamMetricManager.java    From amazon-kinesis-scaling-utils with Apache License 2.0 5 votes vote down vote up
public StreamMetricManager(String streamName, int cloudWatchPeriod, List<KinesisOperationType> types,
		CloudWatchClient cloudWatchClient, KinesisClient kinesisClient) {
	this.streamName = streamName;
	this.trackedOperations.addAll(types);
	this.cloudWatchClient = cloudWatchClient;
	this.kinesisClient = kinesisClient;
	this.cloudWatchPeriod = cloudWatchPeriod;

	for (KinesisOperationType op : this.trackedOperations) {
		// create CloudWatch request templates for the information we have
		// at this point
		for (String metricName : op.getMetricsToFetch()) {
			GetMetricStatisticsRequest.Builder cwRequestBuilder = GetMetricStatisticsRequest.builder();

			cwRequestBuilder.namespace(CW_NAMESPACE)
					.dimensions(Dimension.builder().name("StreamName").value(this.streamName).build())
					.period(cloudWatchPeriod).statistics(Statistic.SUM).metricName(metricName);

			if (!this.cloudwatchRequestTemplates.containsKey(op)) {
				this.cloudwatchRequestTemplates.put(op, new ArrayList<GetMetricStatisticsRequest.Builder>() {
					{
						add(cwRequestBuilder);
					}
				});
			} else {
				this.cloudwatchRequestTemplates.get(op).add(cwRequestBuilder);
			}
		}
	}
}
 
Example #10
Source File: CloudWatchService.java    From greenbot with Apache License 2.0 5 votes vote down vote up
/**
 * Max datapoint is 1440
 *
 * @param cloudWatchMetricStatisticsRequest
 * @return
 */
public Optional<Double> getMetricStatistics(CloudWatchMetricStatisticsRequest cloudWatchMetricStatisticsRequest) {
    Instant endTime = Instant.now();

    CloudWatchClient client = CloudWatchClient.builder().region(Region.of(cloudWatchMetricStatisticsRequest.getRegion())).build();
    Dimension dimension = Dimension.builder()
            .name(cloudWatchMetricStatisticsRequest.getDimensionKey())
            .value(cloudWatchMetricStatisticsRequest.getDimensionValue())
            .build();

    Instant startTime = endTime.minusSeconds(cloudWatchMetricStatisticsRequest.getDuration() * 60);
    GetMetricStatisticsRequest request = GetMetricStatisticsRequest.builder()
            .startTime(startTime)
            .endTime(endTime)
            .period(calculatePeriod(startTime, endTime))
            .statistics(Statistic.AVERAGE)
            .statisticsWithStrings("Average")
            .unit(StandardUnit.PERCENT)
            .namespace(cloudWatchMetricStatisticsRequest.getNamespace())
            .metricName(cloudWatchMetricStatisticsRequest.getMetricName())
            .dimensions(dimension)
            .build();

    GetMetricStatisticsResponse response = client.getMetricStatistics(request);
    if (response.hasDatapoints() && response.datapoints().size() > 0) {
        Optional<Double> sum = response.datapoints().stream().map(Datapoint::average).reduce(Double::sum);
        return Optional.of(sum.get() / response.datapoints().size());
    }
    return Optional.empty();
}
 
Example #11
Source File: StreamMonitor.java    From amazon-kinesis-scaling-utils with Apache License 2.0 5 votes vote down vote up
public StreamMonitor(AutoscalingConfiguration config) throws Exception {
	this.config = config;
	Region setRegion = Region.of(this.config.getRegion());

	// setup credential refresh
	this.credentials = DefaultCredentialsProvider.builder().asyncCredentialUpdateEnabled(true).build();

	// create scaler class and clients
	this.cloudWatchClient = CloudWatchClient.builder().credentialsProvider(this.credentials).region(setRegion).build();
	this.kinesisClient = KinesisClient.builder().credentialsProvider(this.credentials).region(setRegion).build();
	this.snsClient = SnsClient.builder().credentialsProvider(this.credentials).region(setRegion).build();
	
	this.scaler = new StreamScaler(this.kinesisClient);
}
 
Example #12
Source File: CloudWatchServiceIntegrationTest.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setUp() throws IOException {

    Region region = Region.US_WEST_2;;
    cw = CloudWatchClient.builder()
            .region(region)
            .build();
    cloudWatchLogsClient = CloudWatchLogsClient.builder().build();

    try (InputStream input = CloudWatchServiceIntegrationTest.class.getClassLoader().getResourceAsStream("config.properties")) {

        Properties prop = new Properties();

        if (input == null) {
            System.out.println("Sorry, unable to find config.properties");
            return;
        }

        //load a properties file from class path, inside static method
        prop.load(input);

        // Populate the data members required for all tests
        logGroup = prop.getProperty("logGroup");
        alarmName = prop.getProperty("alarmName");
        streamName = prop.getProperty("streamName");
        ruleResource = prop.getProperty("ruleResource");
        metricId = prop.getProperty("metricId");
        filterName = prop.getProperty("filterName");
        destinationArn = prop.getProperty("destinationArn");
        roleArn= prop.getProperty("roleArn");
        filterPattern= prop.getProperty("filterPattern");
        instanceId= prop.getProperty("instanceId");

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example #13
Source File: PutMetricAlarm.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void putMetricAlarm(CloudWatchClient cw, String alarmName, String instanceId) {

        try {
            Dimension dimension = Dimension.builder()
                .name("InstanceId")
                .value(instanceId).build();

            PutMetricAlarmRequest request = PutMetricAlarmRequest.builder()
                .alarmName(alarmName)
                .comparisonOperator(
                        ComparisonOperator.GREATER_THAN_THRESHOLD)
                .evaluationPeriods(1)
                .metricName("CPUUtilization")
                .namespace("AWS/EC2")
                .period(60)
                .statistic(Statistic.AVERAGE)
                .threshold(70.0)
                .actionsEnabled(false)
                .alarmDescription(
                        "Alarm when server CPU utilization exceeds 70%")
                .unit(StandardUnit.SECONDS)
                .dimensions(dimension)
                .build();

            PutMetricAlarmResponse response = cw.putMetricAlarm(request);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

       System.out.printf(
                "Successfully created alarm with name %s", alarmName);
        // snippet-end:[cloudwatch.java2.put_metric_alarm.main]
    }
 
Example #14
Source File: GetMetricData.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        getMetData(cw) ;
    }
 
Example #15
Source File: EnableAlarmActions.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
                "To run this example, supply an alarm name\n" +
                        "Ex: EnableAlarmActions <alarm-name>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String alarm = args[0];

        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        enableActions(cw, alarm) ;
    }
 
Example #16
Source File: DeleteAlarm.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void deleteCWAlarm(CloudWatchClient cw, String alarmName) {

        try {
            DeleteAlarmsRequest request = DeleteAlarmsRequest.builder()
                .alarmNames(alarmName).build();

            cw.deleteAlarms(request);
            System.out.printf("Successfully deleted alarm %s", alarmName);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        // snippet-end:[cloudwatch.java2.delete_metrics.main]
    }
 
Example #17
Source File: GetMetricData.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void getMetData( CloudWatchClient cw) {

        try {
            // Set the date
            Instant start = Instant.ofEpochMilli(new Date().getTime());
            start = Instant.parse("2019-10-23T10:12:35Z");

            Instant endDate = Instant.now();

            Metric met = Metric.builder()
                    .metricName("DiskReadBytes")
                    .namespace("AWS/EC2")
                     .build();

            MetricStat metStat = MetricStat.builder()
                    .stat("Minimum")
                    .period(60)
                    .metric(met)
                    .build();

            MetricDataQuery dataQUery = MetricDataQuery.builder()
                    .metricStat(metStat)
                    .id("foo2")
                    .returnData(true)
                    .build();

            List<MetricDataQuery> dq = new ArrayList();
            dq.add(dataQUery);

            GetMetricDataRequest getMetReq = GetMetricDataRequest.builder()
                .maxDatapoints(100)
                .startTime(start)
                .endTime(endDate)
                .metricDataQueries(dq)
                .build();

            GetMetricDataResponse response = cw.getMetricData(getMetReq);

            List<MetricDataResult> data = response.metricDataResults();

            for (int i = 0; i < data.size(); i++) {

                MetricDataResult item = (MetricDataResult) data.get(i);
             System.out.println("The label is "+item.label());
                System.out.println("The status code is "+item.statusCode().toString());
            }

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        // snippet-end:[cloudwatch.java2.get_metric_alarm.main]
    }
 
Example #18
Source File: StreamMetricManager.java    From amazon-kinesis-scaling-utils with Apache License 2.0 4 votes vote down vote up
public StreamMetricManager(String streamName, List<KinesisOperationType> types, CloudWatchClient cloudWatchClient,
		KinesisClient kinesisClient) {
	this(streamName, StreamMonitor.CLOUDWATCH_PERIOD, types, cloudWatchClient, kinesisClient);
}
 
Example #19
Source File: CloudWatchProvider.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
public CloudWatchClient get() {
    return defaultClient(CloudWatchClient.builder()).build();
}
 
Example #20
Source File: DescribeAlarms.java    From aws-doc-sdk-examples with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        deleteCWAlarms(cw) ;

    }