awscdkawssyntheticsalpha

package module
v2.0.0-rc.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2021 License: Apache-2.0 Imports: 10 Imported by: 0

README

Amazon CloudWatch Synthetics Construct Library


All classes with the Cfn prefix in this module (CFN Resources) are always stable and safe to use.

The APIs of higher level constructs in this module are in developer preview before they become stable. We will only make breaking changes to address unforeseen API issues. Therefore, these APIs are not subject to Semantic Versioning, and breaking changes will be announced in release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


Amazon CloudWatch Synthetics allow you to monitor your application by generating synthetic traffic. The traffic is produced by a canary: a configurable script that runs on a schedule. You configure the canary script to follow the same routes and perform the same actions as a user, which allows you to continually verify your user experience even when you don't have any traffic on your applications.

Canary

To illustrate how to use a canary, assume your application defines the following endpoint:

% curl "https://api.example.com/user/books/topbook/"
The Hitchhikers Guide to the Galaxy

The below code defines a canary that will hit the books/topbook endpoint every 5 minutes:

const canary = new synthetics.Canary(this, 'MyCanary', {
  schedule: synthetics.Schedule.rate(Duration.minutes(5)),
  test: synthetics.Test.custom({
    code: synthetics.Code.fromAsset(path.join(__dirname, 'canary')),
    handler: 'index.handler',
  }),
  runtime: synthetics.Runtime.SYNTHETICS_NODEJS_PUPPETEER_3_1,
  environmentVariables: {
      stage: 'prod',
  },
});

The following is an example of an index.js file which exports the handler function:

const synthetics = require('Synthetics');
const log = require('SyntheticsLogger');

const pageLoadBlueprint = async function () {
    // Configure the stage of the API using environment variables
    const url = `https://api.example.com/${process.env.stage}/user/books/topbook/`;

    const page = await synthetics.getPage();
    const response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
    // Wait for page to render. Increase or decrease wait time based on endpoint being monitored.
    await page.waitFor(15000);
    // This will take a screenshot that will be included in test output artifacts.
    await synthetics.takeScreenshot('loaded', 'loaded');
    const pageTitle = await page.title();
    log.info('Page title: ' + pageTitle);
    if (response.status() !== 200) {
        throw 'Failed to load page!';
    }
};

exports.handler = async () => {
    return await pageLoadBlueprint();
};

Note: The function must be called handler.

The canary will automatically produce a CloudWatch Dashboard:

UI Screenshot

The Canary code will be executed in a lambda function created by Synthetics on your behalf. The Lambda function includes a custom runtime provided by Synthetics. The provided runtime includes a variety of handy tools such as Puppeteer (for nodejs based one) and Chromium.

To learn more about Synthetics capabilities, check out the docs.

Canary Schedule

You can specify the schedule on which a canary runs by providing a Schedule object to the schedule property.

Configure a run rate of up to 60 minutes with Schedule.rate:

Schedule.rate(Duration.minutes(5)), // Runs every 5 minutes.

You can also specify a cron expression via Schedule.expression:

Schedule.expression('cron(0 0,8,16 * * ? *)'), // Run at 12am, 8am, 4pm UTC every day

If you want the canary to run just once upon deployment, you can use Schedule.once().

Configuring the Canary Script

To configure the script the canary executes, use the test property. The test property accepts a Test instance that can be initialized by the Test class static methods. Currently, the only implemented method is Test.custom(), which allows you to bring your own code. In the future, other methods will be added. Test.custom() accepts code and handler properties -- both are required by Synthetics to create a lambda function on your behalf.

The synthetics.Code class exposes static methods to bundle your code artifacts:

  • code.fromInline(code) - specify an inline script.
  • code.fromAsset(path) - specify a .zip file or a directory in the local filesystem which will be zipped and uploaded to S3 on deployment. See the above Note for directory structure.
  • code.fromBucket(bucket, key[, objectVersion]) - specify an S3 object that contains the .zip file of your runtime code. See the above Note for directory structure.

Using the Code class static initializers:

// To supply the code inline:
new synthetics.Canary(this, 'Inline Canary', {
  test: synthetics.Test.custom({
    code: synthetics.Code.fromInline('/* Synthetics handler code */'),
    handler: 'index.handler', // must be 'index.handler'
  }),
  runtime: synthetics.Runtime.SYNTHETICS_NODEJS_PUPPETEER_3_1,
});

// To supply the code from your local filesystem:
new synthetics.Canary(this, 'Asset Canary', {
  test: synthetics.Test.custom({
    code: synthetics.Code.fromAsset(path.join(__dirname, 'canary')),
    handler: 'index.handler', // must end with '.handler'
  }),
  runtime: synthetics.Runtime.SYNTHETICS_NODEJS_PUPPETEER_3_1,
});

// To supply the code from a S3 bucket:
import * as s3 from '@aws-cdk/aws-s3';
const bucket = new s3.Bucket(this, 'Code Bucket');
new synthetics.Canary(this, 'Bucket Canary', {
  test: synthetics.Test.custom({
    code: synthetics.Code.fromBucket(bucket, 'canary.zip'),
    handler: 'index.handler', // must end with '.handler'
  }),
  runtime: synthetics.Runtime.SYNTHETICS_NODEJS_PUPPETEER_3_1,
});

Note: Synthetics have a specified folder structure for canaries. For Node scripts supplied via code.fromAsset() or code.fromBucket(), the canary resource requires the following folder structure:

canary/
├── nodejs/
   ├── node_modules/
        ├── <filename>.js

For Python scripts supplied via code.fromAsset() or code.fromBucket(), the canary resource requires the following folder structure:

canary/
├── python/
    ├── <filename>.py

See Synthetics docs.

Alarms

You can configure a CloudWatch Alarm on a canary metric. Metrics are emitted by CloudWatch automatically and can be accessed by the following APIs:

  • canary.metricSuccessPercent() - percentage of successful canary runs over a given time
  • canary.metricDuration() - how much time each canary run takes, in seconds.
  • canary.metricFailed() - number of failed canary runs over a given time

Create an alarm that tracks the canary metric:

import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
new cloudwatch.Alarm(this, 'CanaryAlarm', {
  metric: canary.metricSuccessPercent(),
  evaluationPeriods: 2,
  threshold: 90,
  comparisonOperator: cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD,
});
Future Work
  • Add blueprints to the Test class #9613.

Documentation

Overview

The CDK Construct Library for AWS::Synthetics

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Canary_IsConstruct

func Canary_IsConstruct(x interface{}) *bool

Checks if `x` is a construct.

Returns: true if `x` is an object created from a class which extends `Construct`. Deprecated: use `x instanceof Construct` instead

func Canary_IsResource

func Canary_IsResource(construct constructs.IConstruct) *bool

Check whether the given construct is a Resource. Experimental.

func NewAssetCode_Override

func NewAssetCode_Override(a AssetCode, assetPath *string, options *awss3assets.AssetOptions)

Experimental.

func NewCanary_Override

func NewCanary_Override(c Canary, scope constructs.Construct, id *string, props *CanaryProps)

Experimental.

func NewCode_Override

func NewCode_Override(c Code)

Experimental.

func NewInlineCode_Override

func NewInlineCode_Override(i InlineCode, code *string)

Experimental.

func NewRuntime_Override

func NewRuntime_Override(r Runtime, name *string, family RuntimeFamily)

Experimental.

func NewS3Code_Override

func NewS3Code_Override(s S3Code, bucket awss3.IBucket, key *string, objectVersion *string)

Experimental.

Types

type ArtifactsBucketLocation

type ArtifactsBucketLocation struct {
	// The s3 location that stores the data of each run.
	// Experimental.
	Bucket awss3.IBucket `json:"bucket"`
	// The S3 bucket prefix.
	//
	// Specify this if you want a more specific path within the artifacts bucket.
	// Experimental.
	Prefix *string `json:"prefix"`
}

Options for specifying the s3 location that stores the data of each canary run.

The artifacts bucket location **cannot** be updated once the canary is created. Experimental.

type AssetCode

type AssetCode interface {
	Code
	Bind(scope constructs.Construct, handler *string, family RuntimeFamily) *CodeConfig
}

Canary code from an Asset. Experimental.

func AssetCode_FromAsset

func AssetCode_FromAsset(assetPath *string, options *awss3assets.AssetOptions) AssetCode

Specify code from a local path.

Path must include the folder structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `AssetCode` associated with the specified path. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

func Code_FromAsset

func Code_FromAsset(assetPath *string, options *awss3assets.AssetOptions) AssetCode

Specify code from a local path.

Path must include the folder structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `AssetCode` associated with the specified path. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

func InlineCode_FromAsset

func InlineCode_FromAsset(assetPath *string, options *awss3assets.AssetOptions) AssetCode

Specify code from a local path.

Path must include the folder structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `AssetCode` associated with the specified path. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

func NewAssetCode

func NewAssetCode(assetPath *string, options *awss3assets.AssetOptions) AssetCode

Experimental.

func S3Code_FromAsset

func S3Code_FromAsset(assetPath *string, options *awss3assets.AssetOptions) AssetCode

Specify code from a local path.

Path must include the folder structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `AssetCode` associated with the specified path. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

type Canary

type Canary interface {
	awscdk.Resource
	ArtifactsBucket() awss3.IBucket
	CanaryId() *string
	CanaryName() *string
	CanaryState() *string
	Env() *awscdk.ResourceEnvironment
	Node() constructs.Node
	PhysicalName() *string
	Role() awsiam.IRole
	Stack() awscdk.Stack
	ApplyRemovalPolicy(policy awscdk.RemovalPolicy)
	GeneratePhysicalName() *string
	GetResourceArnAttribute(arnAttr *string, arnComponents *awscdk.ArnComponents) *string
	GetResourceNameAttribute(nameAttr *string) *string
	MetricDuration(options *awscloudwatch.MetricOptions) awscloudwatch.Metric
	MetricFailed(options *awscloudwatch.MetricOptions) awscloudwatch.Metric
	MetricSuccessPercent(options *awscloudwatch.MetricOptions) awscloudwatch.Metric
	ToString() *string
}

Define a new Canary. Experimental.

func NewCanary

func NewCanary(scope constructs.Construct, id *string, props *CanaryProps) Canary

Experimental.

type CanaryProps

type CanaryProps struct {
	// Specify the runtime version to use for the canary.
	// See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html
	//
	// Experimental.
	Runtime Runtime `json:"runtime"`
	// The type of test that you want your canary to run.
	//
	// Use `Test.custom()` to specify the test to run.
	// Experimental.
	Test Test `json:"test"`
	// The s3 location that stores the data of the canary runs.
	// Experimental.
	ArtifactsBucketLocation *ArtifactsBucketLocation `json:"artifactsBucketLocation"`
	// The name of the canary.
	//
	// Be sure to give it a descriptive name that distinguishes it from
	// other canaries in your account.
	//
	// Do not include secrets or proprietary information in your canary name. The canary name
	// makes up part of the canary ARN, which is included in outbound calls over the internet.
	// See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html
	//
	// Experimental.
	CanaryName *string `json:"canaryName"`
	// Key-value pairs that the Synthetics caches and makes available for your canary scripts.
	//
	// Use environment variables
	// to apply configuration changes, such as test and production environment configurations, without changing your
	// Canary script source code.
	// Experimental.
	EnvironmentVariables *map[string]*string `json:"environmentVariables"`
	// How many days should failed runs be retained.
	// Experimental.
	FailureRetentionPeriod awscdk.Duration `json:"failureRetentionPeriod"`
	// Canary execution role.
	//
	// This is the role that will be assumed by the canary upon execution.
	// It controls the permissions that the canary will have. The role must
	// be assumable by the AWS Lambda service principal.
	//
	// If not supplied, a role will be created with all the required permissions.
	// If you provide a Role, you must add the required permissions.
	// See: required permissions: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn
	//
	// Experimental.
	Role awsiam.IRole `json:"role"`
	// Specify the schedule for how often the canary runs.
	//
	// For example, if you set `schedule` to `rate(10 minutes)`, then the canary will run every 10 minutes.
	// You can set the schedule with `Schedule.rate(Duration)` (recommended) or you can specify an expression using `Schedule.expression()`.
	// Experimental.
	Schedule Schedule `json:"schedule"`
	// Whether or not the canary should start after creation.
	// Experimental.
	StartAfterCreation *bool `json:"startAfterCreation"`
	// How many days should successful runs be retained.
	// Experimental.
	SuccessRetentionPeriod awscdk.Duration `json:"successRetentionPeriod"`
	// How long the canary will be in a 'RUNNING' state.
	//
	// For example, if you set `timeToLive` to be 1 hour and `schedule` to be `rate(10 minutes)`,
	// your canary will run at 10 minute intervals for an hour, for a total of 6 times.
	// Experimental.
	TimeToLive awscdk.Duration `json:"timeToLive"`
}

Properties for a canary. Experimental.

type Code

type Code interface {
	Bind(scope constructs.Construct, handler *string, family RuntimeFamily) *CodeConfig
}

The code the canary should execute. Experimental.

type CodeConfig

type CodeConfig struct {
	// Inline code (mutually exclusive with `s3Location`).
	// Experimental.
	InlineCode *string `json:"inlineCode"`
	// The location of the code in S3 (mutually exclusive with `inlineCode`).
	// Experimental.
	S3Location *awss3.Location `json:"s3Location"`
}

Configuration of the code class. Experimental.

type CustomTestOptions

type CustomTestOptions struct {
	// The code of the canary script.
	// Experimental.
	Code Code `json:"code"`
	// The handler for the code.
	//
	// Must end with `.handler`.
	// Experimental.
	Handler *string `json:"handler"`
}

Properties for specifying a test. Experimental.

type InlineCode

type InlineCode interface {
	Code
	Bind(_scope constructs.Construct, handler *string, _family RuntimeFamily) *CodeConfig
}

Canary code from an inline string. Experimental.

func AssetCode_FromInline

func AssetCode_FromInline(code *string) InlineCode

Specify code inline.

Returns: `InlineCode` with inline code. Experimental.

func Code_FromInline

func Code_FromInline(code *string) InlineCode

Specify code inline.

Returns: `InlineCode` with inline code. Experimental.

func InlineCode_FromInline

func InlineCode_FromInline(code *string) InlineCode

Specify code inline.

Returns: `InlineCode` with inline code. Experimental.

func NewInlineCode

func NewInlineCode(code *string) InlineCode

Experimental.

func S3Code_FromInline

func S3Code_FromInline(code *string) InlineCode

Specify code inline.

Returns: `InlineCode` with inline code. Experimental.

type Runtime

type Runtime interface {
	Family() RuntimeFamily
	Name() *string
}

Runtime options for a canary. Experimental.

func NewRuntime

func NewRuntime(name *string, family RuntimeFamily) Runtime

Experimental.

func Runtime_SYNTHETICS_1_0

func Runtime_SYNTHETICS_1_0() Runtime

func Runtime_SYNTHETICS_NODEJS_2_0

func Runtime_SYNTHETICS_NODEJS_2_0() Runtime

func Runtime_SYNTHETICS_NODEJS_2_1

func Runtime_SYNTHETICS_NODEJS_2_1() Runtime

func Runtime_SYNTHETICS_NODEJS_2_2

func Runtime_SYNTHETICS_NODEJS_2_2() Runtime

func Runtime_SYNTHETICS_NODEJS_PUPPETEER_3_0

func Runtime_SYNTHETICS_NODEJS_PUPPETEER_3_0() Runtime

func Runtime_SYNTHETICS_NODEJS_PUPPETEER_3_1

func Runtime_SYNTHETICS_NODEJS_PUPPETEER_3_1() Runtime

func Runtime_SYNTHETICS_NODEJS_PUPPETEER_3_2

func Runtime_SYNTHETICS_NODEJS_PUPPETEER_3_2() Runtime

func Runtime_SYNTHETICS_PYTHON_SELENIUM_1_0

func Runtime_SYNTHETICS_PYTHON_SELENIUM_1_0() Runtime

type RuntimeFamily

type RuntimeFamily string

All known Lambda runtime families. Experimental.

const (
	RuntimeFamily_NODEJS RuntimeFamily = "NODEJS"
	RuntimeFamily_PYTHON RuntimeFamily = "PYTHON"
	RuntimeFamily_OTHER  RuntimeFamily = "OTHER"
)

type S3Code

type S3Code interface {
	Code
	Bind(_scope constructs.Construct, _handler *string, _family RuntimeFamily) *CodeConfig
}

S3 bucket path to the code zip file. Experimental.

func AssetCode_FromBucket

func AssetCode_FromBucket(bucket awss3.IBucket, key *string, objectVersion *string) S3Code

Specify code from an s3 bucket.

The object in the s3 bucket must be a .zip file that contains the structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `S3Code` associated with the specified S3 object. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

func Code_FromBucket

func Code_FromBucket(bucket awss3.IBucket, key *string, objectVersion *string) S3Code

Specify code from an s3 bucket.

The object in the s3 bucket must be a .zip file that contains the structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `S3Code` associated with the specified S3 object. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

func InlineCode_FromBucket

func InlineCode_FromBucket(bucket awss3.IBucket, key *string, objectVersion *string) S3Code

Specify code from an s3 bucket.

The object in the s3 bucket must be a .zip file that contains the structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `S3Code` associated with the specified S3 object. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

func NewS3Code

func NewS3Code(bucket awss3.IBucket, key *string, objectVersion *string) S3Code

Experimental.

func S3Code_FromBucket

func S3Code_FromBucket(bucket awss3.IBucket, key *string, objectVersion *string) S3Code

Specify code from an s3 bucket.

The object in the s3 bucket must be a .zip file that contains the structure `nodejs/node_modules/myCanaryFilename.js`.

Returns: `S3Code` associated with the specified S3 object. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_WritingCanary.html#CloudWatch_Synthetics_Canaries_write_from_scratch

Experimental.

type Schedule

type Schedule interface {
	ExpressionString() *string
}

Schedule for canary runs. Experimental.

func Schedule_Expression

func Schedule_Expression(expression *string) Schedule

Construct a schedule from a literal schedule expression.

The expression must be in a `rate(number units)` format. For example, `Schedule.expression('rate(10 minutes)')` Experimental.

func Schedule_Once

func Schedule_Once() Schedule

The canary will be executed once. Experimental.

func Schedule_Rate

func Schedule_Rate(interval awscdk.Duration) Schedule

Construct a schedule from an interval.

Allowed values: 0 (for a single run) or between 1 and 60 minutes. To specify a single run, you can use `Schedule.once()`. Experimental.

type Test

type Test interface {
	Code() Code
	Handler() *string
}

Specify a test that the canary should run. Experimental.

func Test_Custom

func Test_Custom(options *CustomTestOptions) Test

Specify a custom test with your own code.

Returns: `Test` associated with the specified Code object Experimental.

Directories

Path Synopsis
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL