Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function flip_cloudwatch(event, callback) {
console.log(event);
var cloudwatch = new AWS.CloudWatch();
var value = 0.0;
var snsmessage = JSON.parse(event.Records[0].Sns.Message);
console.log('newstatevalue is: ',snsmessage.NewStateValue);
if (snsmessage.NewStateValue == 'ALARM') { value = 0.0 }
else if (snsmessage.NewStateValue == 'OK' || snsmessage.NewStateValue == 'INSUFFICIENT_DATA') { value = 1.0 }
var params = { MetricData: [ { MetricName: 'LambdaCron', Timestamp: new Date, Unit: 'None', Value: value } ], Namespace: 'LambdaCron' };
cloudwatch.putMetricData(params, function(err, data) {
console.log("managed to callback, data is ",data);
if (err) callback(err);
else callback(null); // successful response
});
}
exports.myHandler = function(event, context, callback) {
const message = JSON.parse(event.Records[0].Sns.Message),
trigger = message.Trigger,
to = email_to,
body = message.NewStateReason,
subject = `Alert: ${trigger.Namespace} Metric: ${trigger.MetricName} Threshold: ${trigger.Threshold}` ; ;
var cloudwatch = new AWS.CloudWatch();
cloudwatch.getMetricWidgetImage(getWidgetDefinition(trigger, message), function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
var image = new Buffer(data.MetricWidgetImage).toString('base64')
var response = {
statusCode: (err ? 500 : 200),
headers: {
'Content-Type' : 'image/png'
},
body: image
};
sendImagesToEmail(email_from,
to,
subject,
// Set common error handler for logger.send() and logger.flush()
Logger.error = (error, payload) => {
console.log('error', error, 'context', payload);
callback(error);
}
}
var config = {
url: process.env.SPLUNK_HEC_URL,
token: process.env.SPLUNK_HEC_TOKEN,
maxBatchCount: 1,
maxRetries: 2
};
var Logger = new SplunkLogger(config);
var cloudwatch = new aws.CloudWatch();
var dynamodb = new aws.DynamoDB();
var periodicity_minutes = 5;
var periodicity_seconds = periodicity_minutes * 60;
var namespace = 'AWS/EC2';
var region = process.env.AWS_REGION;
function get_metric_and_send_to_splunk(event, context, highwater, new_highwater, new_highwater_clean_bounds, metric_name, dimension, ddb_metric_key) {
// TODO: Kill function if less than 10 seconds left until lambda timeout?
var cweParams = {
EndTime: new_highwater_clean_bounds,
Dimensions: dimension,
MetricName: metric_name,
Namespace: namespace,
Period: periodicity_seconds,
async getBucketNumberOfObjectsLastDays(bucket, storageType, days) {
const credentials = this.settings.getSettings();
const cloudwatch = new AWS.CloudWatch({region: credentials.awsRegion});
const today = new Date();
const daysBack = new Date();
daysBack.setDate(daysBack.getDate() - days);
const params = {
EndTime: today, /* required */
MetricName: 'NumberOfObjects', /* required */
Namespace: 'AWS/S3', /* required */
Period: 86400, /* required */
StartTime: daysBack, /* required */
Dimensions: [
{
Name: 'BucketName', /* required */
Value: bucket /* required */
},
Namespace: namespace,
MetricName: metricName,
Dimensions: dimensions,
Region: region
} = props
let statistics = (props.Statistics ? props.Statistics : 'Average')
let period = 60
let twoWeeksBefore = new Date()
twoWeeksBefore.setDate(twoWeeksBefore.getDate() - 14)
if (startTime <= twoWeeksBefore) {
// Data points with a period of 60 seconds are not available
period = 300
}
const cloudWatch = new AWS.CloudWatch({region})
return new Promise((resolve, reject) => {
const params = {
Namespace: namespace,
MetricName: metricName,
Dimensions: dimensions,
EndTime: endTime,
StartTime: startTime,
Period: period
}
if (statistics.startsWith('p')) {
params.ExtendedStatistics = [statistics]
} else {
params.Statistics = [statistics]
}
cloudWatch.getMetricStatistics(params, (err, result) => {
if (err) {
var config = {};
function configure(values) {
if(values) {
for(var key in values) {
config[key] = values[key];
}
}
};
exports.configure = configure;
configure(defaultValues);
// Runtime variables
var currentRegion = process.env.AWS_REGION; // Current region from Lambda environment variables (where the function runs)
var cloudWatch = new AWS.CloudWatch({ region: currentRegion }); // CloudWatch service for loading the configuration, in the current region
exports.create = function() {
var metrics = {};
var entries = {};
var register = function(name, displayName, type, unit, source, destination) {
if (metrics.hasOwnProperty(name)) {
return;
}
var dimensions = [];
if (source) {
if (destination) {
// Aggregation per source, destination and function
dimensions = [{ Name: "Source", Value: source }, { Name: "Destination", Value: source }, { Name: "Function", Value: process.env.AWS_LAMBDA_FUNCTION_NAME }];
async function setFunctionInvocationAlarms() {
await awsConfigHelper.updateConfig(cliArgs.region);
const lambda = new AWS.Lambda();
const cloudwatch = new AWS.CloudWatch();
while (!isCompleted) {
try {
const response = await lambda.listFunctions({
Marker: nextToken
}).promise();
if (response.Functions) {
for (let i = 0; i < response.Functions.length; i++) {
const fn = response.Functions[i];
if (cliArgs.filterName && !fn.FunctionName.match(filterRegex)) {
console.log("Skipping function", fn.FunctionName);
continue;
}
console.log(`Creating Invocation count Alarm for function: ${fn.FunctionName}`);
await cloudwatch.putMetricAlarm({
AlarmName: `${fn.FunctionName}_InvocationCount`,
AlarmDescription: "Invocations count Alarm",
async getServiceUsage(checkName, params, valid_regions) {
let usage_map = {};
let region_map = {};
for (let currentRegion of valid_regions) {
AWS.config.update({region: currentRegion});
let cloudwatch = new AWS.CloudWatch();
try {
let response = await cloudwatch.getMetricData(params).promise();
if (response.MetricDataResults[0].Values[0] !== undefined) {
let maxUsage = response.MetricDataResults[0].Values[0]
region_map[currentRegion] = maxUsage;
}
} catch (err) {
LOGGER.log('ERROR', err);
}
}
usage_map[checkName]=region_map;
return usage_map;
}
module.exports.dbsleep = (event, context, callback) => {
var rds = new AWS.RDS();
var cloudwatch = new AWS.CloudWatch();
var sleepTimeout = parseInt(process.env.WP_RDS_SLEEP_TIMEOUT);
var now = new Date();
var startTime = new Date();
startTime.setMinutes(startTime.getMinutes() - sleepTimeout);
var cloudwatchParams = {
EndTime: now.toISOString(),
MetricName: 'Invocations',
Namespace: 'AWS/Lambda',
Period: sleepTimeout * 60,
StartTime: startTime.toISOString(),
Dimensions: [
{
Name: 'FunctionName',
Value: process.env.WP_WEB_FUNCTION_NAME
}
function setEmitter() {
self.cloudwatch = new AWS.CloudWatch(self.config);
emitter.on('flush', function(timestamp, metrics) { self.flush(timestamp, metrics); });
}