-
Notifications
You must be signed in to change notification settings - Fork 33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Raise an alarm when any stages are in a Failed state. #6
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f7b23b3
Configure a lambda function to watch the pipeline and emit a metric f…
7fe45e6
Remove samgood test names of stacks
5ae888f
Move pipeline watcher construct and functio to lib/pipeline-watcher/.…
8429776
Update expected.json
9bd96f5
Add unit tests, refactor names as requested.
88c5cc4
Don't export the watcher handler and remove 'failed failed'
9d5d04e
Use pipeline name in metric name instead of namespace
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './watcher'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import AWS = require('aws-sdk'); | ||
|
||
// export for tests | ||
export const codePipeline = new AWS.CodePipeline(); | ||
export const logger = { | ||
log: (line: string) => process.stdout.write(line) | ||
}; | ||
|
||
/** | ||
* Lambda function for checking the stages of a CodePipeline and emitting log | ||
* entries with { failedCount = <no. of failed stages> } for async metric | ||
* aggregation via metric filters. | ||
* | ||
* It requires the pipeline's name be set as the 'PIPELINE_NAME' environment variable. | ||
*/ | ||
export async function handler() { | ||
const pipelineName = process.env.PIPELINE_NAME; | ||
if (!pipelineName) { | ||
throw new Error("Pipeline name expects environment variable: 'PIPELINE_NAME'"); | ||
} | ||
const state = await codePipeline.getPipelineState({ | ||
name: pipelineName | ||
}).promise(); | ||
|
||
let failedCount = 0; | ||
if (state.stageStates) { | ||
failedCount = state.stageStates | ||
.filter(stage => stage.latestExecution !== undefined && stage.latestExecution.status === 'Failed') | ||
.length; | ||
} | ||
logger.log(JSON.stringify({ | ||
failedCount | ||
})); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import cloudwatch = require('@aws-cdk/aws-cloudwatch'); | ||
import cpipeline = require('@aws-cdk/aws-codepipeline'); | ||
import events = require('@aws-cdk/aws-events'); | ||
import iam = require('@aws-cdk/aws-iam'); | ||
import lambda = require('@aws-cdk/aws-lambda'); | ||
import logs = require('@aws-cdk/aws-logs'); | ||
import cdk = require('@aws-cdk/cdk'); | ||
import fs = require('fs'); | ||
import path = require('path'); | ||
|
||
export interface PipelineWatcherProps { | ||
/** | ||
* Code Pipeline to monitor for failed stages | ||
*/ | ||
pipeline: cpipeline.Pipeline; | ||
|
||
/** | ||
* Set the pipelineName of the alarm description. | ||
* | ||
* Description is set to 'Pipeline <title> has failed stages' | ||
* | ||
* @default pipeline's name | ||
*/ | ||
title?: string; | ||
} | ||
|
||
/** | ||
* Construct which watches a Code Pipeline for failed stages and raises an alarm | ||
* if there are any failed stages. | ||
* | ||
* A function runs every minute and calls GetPipelineState for the provided pipeline's | ||
* name, counts the number of failed stages and emits a JSON log { failedCount: <number> }. | ||
* A metric filter is then configured to track this value as a CloudWatch metric, and | ||
* a corresponding alarm is set to fire when the maximim value of a single 5-minute interval | ||
* is >= 1. | ||
*/ | ||
export class PipelineWatcher extends cdk.Construct { | ||
public readonly alarm: cloudwatch.Alarm; | ||
|
||
constructor(parent: cdk.Construct, name: string, props: PipelineWatcherProps) { | ||
super(parent, name); | ||
|
||
const pipelineWatcher = new lambda.Function(this, 'Poller', { | ||
handler: 'index.handler', | ||
runtime: lambda.Runtime.NodeJS810, | ||
code: lambda.Code.inline(fs.readFileSync(path.join(__dirname, 'watcher-handler.js')).toString('utf8')), | ||
environment: { | ||
PIPELINE_NAME: props.pipeline.pipelineName | ||
} | ||
}); | ||
|
||
// See https://github.com/awslabs/aws-cdk/issues/1340 for exposing grants on the pipeline. | ||
pipelineWatcher.addToRolePolicy(new iam.PolicyStatement() | ||
.addResource(props.pipeline.pipelineArn) | ||
.addAction('codepipeline:GetPipelineState')); | ||
|
||
// ex: arn:aws:logs:us-east-1:123456789012:log-group:my-log-group | ||
const logGroup = new logs.LogGroup(this, 'Logs', { | ||
logGroupName: `/aws/lambda/${pipelineWatcher.functionName}`, | ||
retentionDays: 731 | ||
}); | ||
|
||
const trigger = new events.EventRule(this, 'Trigger', { | ||
scheduleExpression: 'rate(1 minute)', | ||
targets: [pipelineWatcher] | ||
}); | ||
|
||
const logGroupResource = logGroup.findChild('Resource') as cdk.Resource; | ||
const triggerResource = trigger.findChild('Resource') as cdk.Resource; | ||
triggerResource.addDependency(logGroupResource); | ||
|
||
const metricNamespace = `CDK/Delivlib`; | ||
const metricName = `${props.pipeline.pipelineName}_FailedStages`; | ||
|
||
new logs.MetricFilter(this, 'MetricFilter', { | ||
filterPattern: logs.FilterPattern.exists('$.failedCount'), | ||
metricNamespace, | ||
metricName, | ||
metricValue: '$.failedCount', | ||
logGroup | ||
}); | ||
|
||
this.alarm = new cloudwatch.Alarm(this, 'Alarm', { | ||
alarmDescription: `Pipeline ${props.title || props.pipeline.pipelineName} has failed stages`, | ||
metric: new cloudwatch.Metric({ | ||
eladb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
metricName, | ||
namespace: metricNamespace, | ||
statistic: cloudwatch.Statistic.Maximum | ||
}), | ||
threshold: 1, | ||
comparisonOperator: cloudwatch.ComparisonOperator.GreaterThanOrEqualToThreshold, | ||
evaluationPeriods: 1, | ||
treatMissingData: cloudwatch.TreatMissingData.Ignore, // We expect a steady stream of data points | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can probably use
logGroup.extractMetric
here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tried, it doesn't support namespaces with a
/
or token values. Cut an issue: aws/aws-cdk#1351There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think this namespace is appropriate. Generally this would contain the service name, like
AWS/SQS
orAWS/DynamoDB
. Variables go intoDimensions
. So in this case, I would expect it to beCDK/Delivlib
or similar.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't use dimensions in metric filters unfortunately.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I could instead make the metric name ugly instead of the namespace:
CDK/Delivlib
<pipeline-name>_FailedStages