com.amazonaws.services.cloudwatch.AmazonCloudWatchClient Java Examples

The following examples show how to use com.amazonaws.services.cloudwatch.AmazonCloudWatchClient. 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: CachingClientProviderTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testCachingClientProvider() {
    final AmazonEC2Client client = provider.getClient(AmazonEC2Client.class, ACCOUNT_ID1, REGION1);
    assertThat(client).isNotNull();

    assertThat(provider.getClient(AmazonEC2Client.class, ACCOUNT_ID1, REGION1))
            .isNotNull()
            .isSameAs(client);
    assertThat(provider.getClient(AmazonEC2Client.class, ACCOUNT_ID2, REGION1))
            .isNotNull()
            .isNotSameAs(client);
    assertThat(provider.getClient(AmazonEC2Client.class, ACCOUNT_ID1, REGION2))
            .isNotNull()
            .isNotSameAs(client);
    assertThat(provider.getClient(AmazonCloudWatchClient.class, ACCOUNT_ID1, REGION1))
            .isNotNull()
            .isNotSameAs(client);
}
 
Example #2
Source File: AwsCloudWatchService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public void addCloudWatchAlarmsForSystemFailures(List<CloudResource> instances, CloudStack stack, String regionName, AwsCredentialView credentialView) {
    if (isCloudwatchEnabled(stack)) {
        instances.stream().forEach(instance -> {
            try {
                PutMetricAlarmRequest metricAlarmRequest = new PutMetricAlarmRequest();
                metricAlarmRequest.setAlarmActions(Arrays.asList("arn:aws:automate:" + regionName + ":ec2:recover"));
                metricAlarmRequest.setAlarmName(instance.getInstanceId() + alarmSuffix);
                metricAlarmRequest.setMetricName("StatusCheckFailed_System");
                metricAlarmRequest.setStatistic("Maximum");
                metricAlarmRequest.setNamespace("AWS/EC2");
                metricAlarmRequest.setDimensions(Arrays.asList(new Dimension().withName("InstanceId").withValue(instance.getInstanceId())));
                metricAlarmRequest.setPeriod(cloudwatchPeriod);
                metricAlarmRequest.setEvaluationPeriods(cloudwatchEvaluationPeriods);
                metricAlarmRequest.setThreshold(cloudwatchThreshhold);
                metricAlarmRequest.setComparisonOperator("GreaterThanOrEqualToThreshold");
                AmazonCloudWatchClient amazonCloudWatchClient = awsClient.createCloudWatchClient(credentialView, regionName);
                amazonCloudWatchClient.putMetricAlarm(metricAlarmRequest);
                LOGGER.debug("Created cloudwatch alarm for instanceId {}.", instance.getInstanceId());
            } catch (AmazonCloudWatchException acwe) {
                LOGGER.error("Unable to create cloudwatch alarm for instanceId {}: {}", instance.getInstanceId(), acwe.getLocalizedMessage());
            }
        });
    }
}
 
Example #3
Source File: AwsCloudWatchService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private Stream<List<String>> getExistingCloudWatchAlarms(String regionName, AwsCredentialView credentialView, List<String> alarmNames) {
    Stream<List<String>> filteredAlarmNamesStream;
    try {
        DescribeAlarmsRequest request = new DescribeAlarmsRequest().withAlarmNames(alarmNames).withMaxRecords(maxBatchsize);
        AmazonCloudWatchClient amazonCloudWatchClient = awsClient.createCloudWatchClient(credentialView, regionName);
        List<String> filteredAlarmNames = amazonCloudWatchClient.describeAlarms(request).getMetricAlarms().stream()
                .map(MetricAlarm::getAlarmName)
                .collect(Collectors.toList());
        filteredAlarmNamesStream = Stream.of(filteredAlarmNames);
        LOGGER.debug("Checking cloudwatch alarms [{}] for existence and found [{}]", alarmNames, filteredAlarmNames);
    } catch (AmazonCloudWatchException acwe) {
        LOGGER.error("Unable to describe cloudwatch alarms falling back to delete all alarms indivdually [{}]: {}", alarmNames, acwe.getLocalizedMessage());
        filteredAlarmNamesStream = alarmNames.stream()
                .map(alarmName -> List.of(alarmName));
    }
    return filteredAlarmNamesStream;
}
 
Example #4
Source File: PutCloudWatchMetric.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using aws credentials provider. This is the preferred way for creating clients
 */

@Override
protected AmazonCloudWatchClient createClient(ProcessContext processContext, AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) {
    getLogger().info("Creating client using aws credentials provider");
    return new AmazonCloudWatchClient(awsCredentialsProvider, clientConfiguration);
}
 
Example #5
Source File: CloudWatchUtils.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public static AmazonCloudWatchClient createCloudWatchClient() {
    BasicCredentialsProvider credentials = BasicCredentialsProvider.standard();
    AmazonCloudWatchClient client = !credentials.isValid() ? null : (AmazonCloudWatchClient)
            AmazonCloudWatchClientBuilder.standard()
            .withCredentials(credentials)
            .withRegion("eu-west-1")
            .build();
    return client;
}
 
Example #6
Source File: PutCloudWatchMetric.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using aws credentials provider. This is the preferred way for creating clients
 */

@Override
protected AmazonCloudWatchClient createClient(ProcessContext processContext, AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) {
    getLogger().info("Creating client using aws credentials provider");
    return new AmazonCloudWatchClient(awsCredentialsProvider, clientConfiguration);
}
 
Example #7
Source File: ScanUploadModule.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
protected AmazonCloudWatch provideAmazonCloudWatch(Region region, AWSCredentialsProvider credentialsProvider) {
    AmazonCloudWatch cloudWatch = new AmazonCloudWatchClient(credentialsProvider);
    cloudWatch.setRegion(region);
    return cloudWatch;
}
 
Example #8
Source File: AwsClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public AmazonCloudWatchClient createCloudWatchClient(AwsCredentialView awsCredential, String regionName) {
    AmazonCloudWatchClient client = isRoleAssumeRequired(awsCredential) ?
            new AmazonCloudWatchClient(createAwsSessionCredentialProvider(awsCredential)) :
            new AmazonCloudWatchClient(createAwsCredentials(awsCredential));
    client.setRegion(RegionUtils.getRegion(regionName));
    return client;
}
 
Example #9
Source File: MetricsEmittingBasicClickEventsToKinesis.java    From aws-big-data-blog with Apache License 2.0 5 votes vote down vote up
protected MetricsEmittingBasicClickEventsToKinesis(
        BlockingQueue<ClickEvent> inputQueue) {
    super(inputQueue);
    kinesis = new AmazonKinesisClient().withRegion(
            Regions.fromName(REGION));
    cw = new AmazonCloudWatchClient().withRegion(Regions.fromName(REGION));
}
 
Example #10
Source File: AwsCloudWatchService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void deleteCloudWatchAlarms(String regionName, AwsCredentialView credentialView, List<String> alarmNames) {
    try {
        DeleteAlarmsRequest deleteAlarmsRequest = new DeleteAlarmsRequest().withAlarmNames(alarmNames);
        AmazonCloudWatchClient amazonCloudWatchClient = awsClient.createCloudWatchClient(credentialView, regionName);
        amazonCloudWatchClient.deleteAlarms(deleteAlarmsRequest);
        LOGGER.debug("Deleted cloudwatch alarms [{}]", alarmNames);
    } catch (AmazonCloudWatchException acwe) {
        LOGGER.error("Unable to delete cloudwatch alarms [{}]: {}", alarmNames, acwe.getLocalizedMessage());
        throw new CloudConnectorException("unable to delete cloud watch alarms", acwe);
    }
}
 
Example #11
Source File: CloudWatchClientProducer.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
CloudWatchClientProvider(AmazonCloudWatchClient client) {
    this.client = client;
}
 
Example #12
Source File: PutCloudWatchMetric.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected PutMetricDataResult putMetricData(PutMetricDataRequest metricDataRequest) throws AmazonClientException {
    final AmazonCloudWatchClient client = getClient();
    final PutMetricDataResult result = client.putMetricData(metricDataRequest);
    return result;
}
 
Example #13
Source File: CloudWatchIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testKeyValueOperations() throws Exception {

    AmazonCloudWatchClient cwClient = provider.getClient();
    Assume.assumeNotNull("AWS client not null", cwClient);

    List<Metric> staleMetrics = cwClient.listMetrics(new ListMetricsRequest().withNamespace(NAMESPACE)).getMetrics()
            .stream() //
            .filter(metric -> !metric.getMetricName().startsWith(CloudWatchIntegrationTest.class.getSimpleName())
                    || System.currentTimeMillis()
                            - AWSUtils.toEpochMillis(metric.getMetricName()) > AWSUtils.TWO_WEEKS) //
            .collect(Collectors.toList());
    if (staleMetrics.size() > 0) {
        Assert.fail("Found '" + CloudWatchIntegrationTest.class.getName() + "-*' metrics older than two weeks: "
                + staleMetrics);
    }

    WildFlyCamelContext camelctx = new WildFlyCamelContext();
    camelctx.getNamingContext().bind("cwClient", cwClient);

    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:metrics").to("aws-cw://" + NAMESPACE + "?amazonCwClient=#cwClient");
        }
    });

    camelctx.start();
    try {
        Map<String, Object> headers = new HashMap<>();
        headers.put(CwConstants.METRIC_NAME, METRIC_NAME);
        headers.put(CwConstants.METRIC_DIMENSION_NAME, DIM_NAME);
        headers.put(CwConstants.METRIC_DIMENSION_VALUE, DIM_VALUE);

        ListMetricsRequest request = new ListMetricsRequest().withNamespace(NAMESPACE).withMetricName(METRIC_NAME)
                .withDimensions(new DimensionFilter().withName(DIM_NAME).withValue(DIM_VALUE));

        List<Metric> metrics = Collections.emptyList();
        ProducerTemplate producer = camelctx.createProducerTemplate();
        for (int i = 100; i < 105 && metrics.size() == 0; i++) {
            producer.sendBodyAndHeaders("direct:metrics", new Double(i), headers);
            metrics = cwClient.listMetrics(request).getMetrics();
            System.out.println("metrics #" + i + ": " + metrics);
            Thread.sleep(1000);
        }

        // It may take several minutes for the metric to show up
        // Assert.assertEquals(1, metrics.size());

    } finally {
        camelctx.close();
    }
}
 
Example #14
Source File: StreamsAdapterDemo.java    From aws-dynamodb-examples with Apache License 2.0 4 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) throws Exception {
    System.out.println("Starting demo...");

    String srcTable = tablePrefix + "-src";
    String destTable = tablePrefix + "-dest";
    streamsCredentials = new ProfileCredentialsProvider();
    dynamoDBCredentials = new ProfileCredentialsProvider();
    recordProcessorFactory = new StreamsRecordProcessorFactory(dynamoDBCredentials, dynamodbEndpoint, serviceName, destTable);


    /* ===== REQUIRED =====
     * Users will have to explicitly instantiate and configure the adapter, then pass it to
     * the KCL worker.
     */
    adapterClient = new AmazonDynamoDBStreamsAdapterClient(streamsCredentials, new ClientConfiguration());
    adapterClient.setEndpoint(streamsEndpoint);

    dynamoDBClient = new AmazonDynamoDBClient(dynamoDBCredentials, new ClientConfiguration());
    dynamoDBClient.setEndpoint(dynamodbEndpoint);

    cloudWatchClient = new AmazonCloudWatchClient(dynamoDBCredentials, new ClientConfiguration());

    setUpTables();

    workerConfig = new KinesisClientLibConfiguration("streams-adapter-demo",
            streamArn, streamsCredentials, "streams-demo-worker")
        .withMaxRecords(1)
        .withInitialPositionInStream(InitialPositionInStream.TRIM_HORIZON);

    System.out.println("Creating worker for stream: " + streamArn);
    worker = new Worker(recordProcessorFactory, workerConfig, adapterClient, dynamoDBClient, cloudWatchClient);
    System.out.println("Starting worker...");
    Thread t = new Thread(worker);
    t.start();

    Thread.sleep(25000);
    worker.shutdown();
    t.join();

    if(StreamsAdapterDemoHelper.scanTable(dynamoDBClient, srcTable).getItems().equals(StreamsAdapterDemoHelper.scanTable(dynamoDBClient, destTable).getItems())) {
        System.out.println("Scan result is equal.");
    } else {
        System.out.println("Tables are different!");
    }

    System.out.println("Done.");
    cleanupAndExit(0);
}
 
Example #15
Source File: CloudWatchClientProducer.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
public AmazonCloudWatchClient getClient() {
    return client;
}
 
Example #16
Source File: CloudWatchClientProducer.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Produces
@Singleton
public CloudWatchClientProvider getClientProvider() throws Exception {
    AmazonCloudWatchClient client = CloudWatchUtils.createCloudWatchClient();
    return new CloudWatchClientProvider(client);
}
 
Example #17
Source File: LambdaFunctionThrottleInvocationsRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    cloudWatchClient = PowerMockito.mock(AmazonCloudWatchClient.class); 
}
 
Example #18
Source File: PutCloudWatchMetric.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AmazonCloudWatchClient createClient(ProcessContext processContext, AWSCredentials awsCredentials, ClientConfiguration clientConfiguration) {
    getLogger().debug("Creating client with aws credentials");
    return new AmazonCloudWatchClient(awsCredentials, clientConfiguration);
}
 
Example #19
Source File: AwsCloudWatchServiceTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Test
void testDeleteCloudWatchAlarmsForSystemFailuresWhenOneAlarmHasAlreadyBeenDeleted() {
    String alarm1Name = "i-1-Status-Check-Failed-System";
    String alarm2Name = "i-2-Status-Check-Failed-System";
    String alarm3Name = "i-3-Status-Check-Failed-System";
    String instanceId1 = "i-1";
    String instanceId2 = "i-2";
    String instanceId3 = "i-3";
    MetricAlarm alarm1 = mock(MetricAlarm.class);
    MetricAlarm alarm2 = mock(MetricAlarm.class);
    DescribeAlarmsResult describeAlarmsResult = mock(DescribeAlarmsResult.class);
    AmazonCloudWatchClient cloudWatchClient = mock(AmazonCloudWatchClient.class);
    AwsCredentialView credentialView = mock(AwsCredentialView.class);
    CloudStack stack = mock(CloudStack.class);
    Group group = mock(Group.class);
    CloudInstance instance1 = mock(CloudInstance.class);
    CloudInstance instance2 = mock(CloudInstance.class);
    CloudInstance instance3 = mock(CloudInstance.class);
    List<Group> groups = List.of(group);
    when(stack.getParameters()).thenReturn(PARAMETERS);
    when(stack.getGroups()).thenReturn(groups);
    when(group.getInstances()).thenReturn(List.of(instance1, instance2, instance3));
    when(instance1.getInstanceId()).thenReturn(instanceId1);
    when(instance2.getInstanceId()).thenReturn(instanceId2);
    when(instance3.getInstanceId()).thenReturn(instanceId3);
    when(awsClient.createCloudWatchClient(eq(credentialView), eq(REGION))).thenReturn(cloudWatchClient);
    when(cloudWatchClient.describeAlarms(any())).thenReturn(describeAlarmsResult);
    // alarm 3 was already deleted
    when(describeAlarmsResult.getMetricAlarms()).thenReturn(List.of(alarm1, alarm2));
    when(alarm1.getAlarmName()).thenReturn(alarm1Name);
    when(alarm2.getAlarmName()).thenReturn(alarm2Name);

    underTest.deleteCloudWatchAlarmsForSystemFailures(stack, REGION, credentialView);

    ArgumentCaptor<DescribeAlarmsRequest> captorDescribe = ArgumentCaptor.forClass(DescribeAlarmsRequest.class);
    ArgumentCaptor<DeleteAlarmsRequest> captorDelete = ArgumentCaptor.forClass(DeleteAlarmsRequest.class);
    verify(cloudWatchClient, times(1)).describeAlarms(captorDescribe.capture());
    verify(cloudWatchClient, times(1)).deleteAlarms(captorDelete.capture());
    assertEquals(List.of(alarm1Name, alarm2Name, alarm3Name), captorDescribe.getValue().getAlarmNames());

    // only delete alarms that were not already deleted
    assertEquals(List.of(alarm1Name, alarm2Name), captorDelete.getValue().getAlarmNames());
}
 
Example #20
Source File: AmazonDynamoDBStreamstoIgnite.java    From aws-big-data-blog with Apache License 2.0 4 votes vote down vote up
public void run() throws Exception {
	adapterClient = new AmazonDynamoDBStreamsAdapterClient(new ClientConfiguration());
	adapterClient.setEndpoint(streamsEndpoint);
	dynamoDBClient = new AmazonDynamoDBClient(new ClientConfiguration());
	dynamoDBClient.setEndpoint(dynamodbEndpoint);

	cloudWatchClient = new AmazonCloudWatchClient(dynamoDBCredentials, new ClientConfiguration());

	TcpDiscoverySpi spi = new TcpDiscoverySpi();
	TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder();
	List<String> hostList = Arrays.asList(Properties.getString("hostList").split(","));
	ipFinder.setAddresses(hostList);
	spi.setIpFinder(ipFinder);
	IgniteConfiguration cfg = new IgniteConfiguration();
	cfg.setDiscoverySpi(spi);
	cfg.setClientMode(true);
	cfg.setPeerClassLoadingEnabled(true);

	@SuppressWarnings("unused")
	Ignite ignite = Ignition.start(cfg);
	cache = Ignition.ignite().cache(Properties.getString("cacheName"));
	LOG.info(">>> cache acquired");

	recordProcessorFactory = new StreamsRecordProcessorFactory(cache);
	workerConfig = new KinesisClientLibConfiguration(Properties.getString("applicationName"), streamArn,
			streamsCredentials, "ddbstreamsworker")
					.withMaxRecords(Integer.parseInt(Properties.getString("maxRecords")))
					.withInitialPositionInStream(
							InitialPositionInStream.valueOf(Properties.getString("initialPositionInStream")));

	LOG.info("Creating worker for stream: " + streamArn);
	worker = new Worker(recordProcessorFactory, workerConfig, adapterClient, dynamoDBClient, cloudWatchClient);
	LOG.info("Starting worker...");

	int exitCode = 0;
	try {
		worker.run();
	} catch (Throwable t) {
		LOG.error("Caught throwable while processing data.");
		t.printStackTrace();
		exitCode = 1;
	}
	System.exit(exitCode);
}
 
Example #21
Source File: KouplerMetrics.java    From koupler with MIT License 4 votes vote down vote up
public KouplerMetrics(KinesisEventProducer producer, KinesisProducerConfiguration config, String appName) {
    this(producer, appName);
    cloudWatch = new AmazonCloudWatchClient();
    Region region = Region.getRegion(Regions.fromName(config.getRegion()));
    cloudWatch.setRegion(region);
}
 
Example #22
Source File: PutCloudWatchMetric.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected PutMetricDataResult putMetricData(PutMetricDataRequest metricDataRequest) throws AmazonClientException {
    final AmazonCloudWatchClient client = getClient();
    final PutMetricDataResult result = client.putMetricData(metricDataRequest);
    return result;
}
 
Example #23
Source File: PutCloudWatchMetric.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AmazonCloudWatchClient createClient(ProcessContext processContext, AWSCredentials awsCredentials, ClientConfiguration clientConfiguration) {
    getLogger().debug("Creating client with aws credentials");
    return new AmazonCloudWatchClient(awsCredentials, clientConfiguration);
}
 
Example #24
Source File: LambdaFunctionInvocationCountRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    cloudWatchClient = PowerMockito.mock(AmazonCloudWatchClient.class); 
}