cdk-monitoring-constructs

repository·main·Indexed 20 days ago

https://github.com/cdklabs/cdk-monitoring-constructs

High-level AWS CDK constructs for simplifying AWS infrastructure monitoring via Amazon CloudWatch. It provides automated alarm creation and dashboard generation for various AWS services, including Lambda, ECS, DynamoDB, S3, API Gateway, and more. Supports TypeScript, Java, Python, and C#.

Tokens
24K
Snippets
37
Records
134
Agent score
69%

What's inside cdk-monitoring-constructs

  1. Overview of CDK Monitoring Constructs

    main

    CDK Monitoring Constructs provides easy-to-use AWS CDK constructs for monitoring AWS infrastructure using Amazon CloudWatch.

    Key capabilities include:

    • Adding commonly-used alarms using predefined properties.
    • Generating concise CloudWatch dashboards that visualize your alarms.
    • Extending the library with custom metrics or your own extensions.
    • Multi-language support (TypeScript, Java, Python, and C#).
  2. Implement dynamic dashboards with IDynamicDashboardSegment

    main

    For complete control over dashboard generation, you can use dynamic dashboarding. This allows you to create multiple dashboards (e.g., 'HostedService' and 'Infrastructure') that share the same monitoring logic but display different content based on the dashboard name.

    Steps:

    1. Create a DynamicDashboardFactory with your desired dashboard configurations.
    2. Implement IDynamicDashboardSegment, using a switch statement in widgetsForDashboard(name: string) to return different widgets based on the dashboard name.
    3. Register the segment with monitoring.addDynamicSegment().
    // 1. Create the factory
    const factory = new DynamicDashboardFactory(stack, "DynamicDashboards", {
      dashboardNamePrefix: "ExampleDashboards",
      dashboardConfigs: [
        { name: "HostedService" },
        {
          name: "Infrastructure",
          range: Duration.hours(3),
          periodOverride: PeriodOverride.AUTO,
          renderingPreference: DashboardRenderingPreference.BITMAP_ONLY,
        },
      ],
    });
    
    // 2. Implement the segment
    class ExampleSegment implements IDynamicDashboardSegment {
      widgetsForDashboard(name: string): IWidget[] {
        switch (name) {
          case "HostedService":
            return [new TextWidget({ markdown: "Service metrics" })];
          case "Infrastructure":
            return [new TextWidget({ markdown: "Infrastructure metrics" })];
          default:
            throw new Error("Unexpected dashboard name!");
        }
      }
    }
    
    // 3. Add to facade
    monitoring.addDynamicSegment(new ExampleSegment());
  3. Configure alarm actions and overrides

    main

    Alarms are more useful when they have actions (e.g., notifying SNS or triggering Lambda). You can set default actions for all alarms via the alarmFactoryDefaults in the MonitoringFacade constructor, or override them for specific alarms.

    To compose multiple actions, use the multipleActions utility function.

    Supported actions include SNS and Lambda (refer to the library's lib/common/alarm/action for the full list).

    // Set a default action for all alarms in the facade
    const monitoring = new MonitoringFacade(this, "Monitoring", {
      alarmFactoryDefaults: {
        action: new SnsAlarmActionStrategy({ onAlarmTopic }),
      },
    });
    
    // Override the action for a specific alarm
    monitoring.monitorSomething(something, {
      addSomeAlarm: {
        Warning: {
          threshold: 42,
          actionOverride: new SnsAlarmActionStrategy({ onAlarmTopic }),
        },
      },
    });
    
    // Compose multiple actions
    const action = multipleActions(
      notifySns(onAlarmTopic),
      triggerLambda(onAlarmFunction),
    );
  4. Extend or modify monitoring segments

    main

    If the default dashboard widgets do not meet your needs, you can customize them by extending the appropriate Monitoring class (e.g., LambdaFunctionMonitoring) and overriding the widgets() method.

    Once extended, register your custom segment using facade.addSegment().

    // 1. Extend the class and override widgets
    export class MyCustomizedLambdaFunctionMonitoring extends LambdaFunctionMonitoring {
      widgets(): IWidget[] {
        return [
          // Your custom widgets here
        ];
      }
    }
    
    // 2. Add the custom segment to the facade
    facade.addSegment(
      new MyCustomizedLambdaFunctionMonitoring(facade, { /* props */ })
    );
  5. Create a monitoring facade with MonitoringFacade

    main

    The MonitoringFacade is the main entrypoint for the library. You create an instance of it within a CDK stack (or as a nested stack) and then chain methods to define your monitors.

    Important: Do NOT import anything from the /dist/lib package, as it is unsupported and subject to breaking changes.

    Common methods include .monitorLambdaFunction(), .monitorDynamoTable(), .monitorCustom(), and UI methods like .addLargeHeader() to organize your dashboard.

    // This could be in the same stack as your resources, as a nested stack, or a separate stack
    export class MonitoringStack extends DeploymentStack {
      constructor(parent: App, name: string, props: MonitoringStackProps) {
        super(parent, name, props);
    
        const monitoring = new MonitoringFacade(this, "Monitoring", {
          metricFactoryDefaults: { /* ... */ },
          alarmFactoryDefaults: { /* ... */ },
          dashboardFactory: { /* ... */ },
        });
    
        // Monitor your resources using method chaining
        monitoring
          .addLargeHeader("Storage")
          .monitorDynamoTable({ /* ... */ })
          .monitorLambdaFunction({ /* ... */ })
          .monitorCustom({ /* ... */ });
      }
    }
  6. Configure Route53 Health Check alarms

    main

    Route53 Health Checks have strict requirements for referenced alarms. To ensure an alarm is compatible, use the Route53HealthCheckMetricAdjuster.INSTANCE via the metricAdjuster option in your alarm configuration.

    You can also tag these alarms to easily retrieve them when creating CfnHealthCheck resources.

    // Configure alarm for Route53 compatibility
    monitoring.monitorSomething(something, {
      addSomeAlarm: {
        Warning: {
          customTags: ["route53-health-check"],
          metricAdjuster: Route53HealthCheckMetricAdjuster.INSTANCE,
        },
      },
    });
    
    // Retrieve alarms by tag to create Route53 Health Checks
    const alarms = monitoring.createdAlarmsWithTag("route53-health-check");
    const healthChecks = alarms.map(({ alarm }) => {
      const id = getHealthCheckConstructId(alarm);
      return new CfnHealthCheck(scope, id, {
        healthCheckConfig: {
          type: "CLOUDWATCH_METRIC",
          alarmIdentifier: {
            name: alarm.alarmName,
            region: alarm.stack.region,
          },
        },
      });
    });
  7. Monitor cross-account and cross-Region resources

    main

    You can monitor resources located in different AWS accounts or Regions.

    Precedence for region/account settings:

    1. Individual monitor props (e.g., inside monitorDynamoTable).
    2. The facade's metricFactoryDefaults.
    3. The region/account of the stack deployment.

    Note: While cross-account/Region dashboarding is supported, cross-Region alarming is not supported by CloudWatch.

    // Configure facade for a different region/account
    new MonitoringFacade(stack, "Monitoring", {
      metricFactoryDefaults: {
        region: "us-west-2",
        account: "01234567890",
      },
    });
    
    // Or configure at the individual resource level
    monitoring.monitorDynamoTable({
      table: Table.fromTableArn(stack, "ImportedTable", "arn:aws:dynamodb:us-west-2:01234567890:table/my-table"),
      region: "us-west-2",
      account: "01234567890",
    });
  8. Install cdk-monitoring-constructs

    main

    You can install cdk-monitoring-constructs using various package managers depending on your language.

    TypeScript

    Add cdk-monitoring-constructs to your package.json. Note that you must also include the required peer dependencies aws-cdk-lib and constructs.

    Java

    Available via Maven Central.

    Python

    Available via PyPI.

    C#

    Available via NuGet.

    {
      "dependencies": {
        "cdk-monitoring-constructs": "^9.0.0",
    
        // peer dependencies of cdk-monitoring-constructs
        "aws-cdk-lib": "^2.160.0",
        "constructs": "^10.0.5"
      }
    }
  9. Use OpenSearch Serverless monitoring constructs

    main

    The cdk-monitoring-constructs package provides high-level constructs for monitoring AWS OpenSearch Serverless. The entry point exports several key classes for creating monitoring setups:

    • OpenSearchServerlessMonitoring: A high-level construct to set up monitoring for an OpenSearch Serverless collection.
    • OpenSearchServerlessIndexMonitoring: A construct focused on monitoring specific indices within an OpenSearch Serverless collection.
    • OpenSearchServerlessMetricFactory: A factory for generating standard OpenSearch Serverless metrics.
    • OpenSearchServerlessIndexMetricFactory: A factory for generating metrics specific to OpenSearch Serverless indices.
  10. Use ElastiCache Monitoring constructs

    main

    The aws-elasticache module provides constructs for monitoring both ElastiCache Clusters and ElastiCache Serverless instances. It exports metric factories and monitoring constructs to simplify the creation of CloudWatch alarms and dashboards for ElastiCache resources.

    Available components:

    • ElastiCacheClusterMonitoring: A construct for adding monitoring to an existing ElastiCache Cluster.
    • ElastiCacheServerlessMonitoring: A construct for adding monitoring to an existing ElastiCache Serverless resource.
    • ElastiCacheClusterMetricFactory: A factory for generating specific CloudWatch metrics for ElastiCache Clusters.
    • ElastiCacheServerlessMetricFactory: A factory for generating specific CloudWatch metrics for ElastiCache Serverless.
  11. Use API Gateway V2 HTTP API monitoring constructs

    main

    The aws-apigatewayv2 module provides constructs for monitoring AWS API Gateway V2 HTTP APIs. It exports two primary components:

    1. ApiGatewayV2HttpApiMetricFactory: A factory used to generate specific CloudWatch metrics for an HTTP API.
    2. ApiGatewayV2HttpApiMonitoring: A high-level construct that automates the creation of monitoring resources (like Dashboards or Alarms) for an HTTP API.
  12. Use Kinesis Monitoring constructs

    main

    The aws-kinesis module provides constructs for monitoring AWS Kinesis resources, including Kinesis Data Streams and Kinesis Data Firehose. It exports several specialized monitoring and metric factory classes:

    • Data Stream Monitoring: Use KinesisDataStreamMonitoring to attach monitoring to a Kinesis Data Stream.
    • Data Stream Metric Factories: Use KinesisDataStreamMetricFactory or KinesisDataStreamConsumerMetricFactory to generate specific metrics for streams or stream consumers.
    • Firehose Monitoring: Use KinesisFirehoseMonitoring to attach monitoring to a Kinesis Data Firehose delivery stream.
    • Firehose Metric Factories: Use KinesisFirehoseMetricFactory to generate metrics for Firehose.