/
index.js
164 lines (142 loc) · 5.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
'use strict';
const _ = require('lodash');
class AwsCompileCloudWatchLogEvents {
constructor(serverless) {
this.serverless = serverless;
this.provider = this.serverless.getProvider('aws');
this.hooks = {
'package:compileEvents': this.compileCloudWatchLogEvents.bind(this),
};
this.serverless.configSchemaHandler.defineFunctionEvent('aws', 'cloudwatchLog', {
anyOf: [
{ $ref: '#/definitions/awsLogGroupName' },
{
type: 'object',
properties: {
logGroup: { $ref: '#/definitions/awsLogGroupName' },
filter: { type: 'string' },
},
required: ['logGroup'],
additionalProperties: false,
},
],
});
}
compileCloudWatchLogEvents() {
const logGroupNames = [];
this.serverless.service.getAllFunctions().forEach(functionName => {
const functionObj = this.serverless.service.getFunction(functionName);
let cloudWatchLogNumberInFunction = 0;
if (functionObj.events) {
const logGroupNamesThisFunction = [];
functionObj.events.forEach(event => {
if (event.cloudwatchLog) {
cloudWatchLogNumberInFunction++;
let LogGroupName;
let FilterPattern;
if (typeof event.cloudwatchLog === 'object') {
LogGroupName = event.cloudwatchLog.logGroup.replace(/\r?\n/g, '');
FilterPattern = event.cloudwatchLog.filter
? event.cloudwatchLog.filter.replace(/\r?\n/g, '')
: '';
} else if (typeof event.cloudwatchLog === 'string') {
LogGroupName = event.cloudwatchLog.replace(/\r?\n/g, '');
FilterPattern = '';
}
if (logGroupNames.includes(LogGroupName)) {
const errorMessage = [
`"${LogGroupName}" logGroup for cloudwatchLog event is duplicated.`,
' This property can only be set once per CloudFormation stack.',
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
logGroupNames.push(LogGroupName);
logGroupNamesThisFunction.push(LogGroupName);
const lambdaLogicalId = this.provider.naming.getLambdaLogicalId(functionName);
const cloudWatchLogLogicalId = this.provider.naming.getCloudWatchLogLogicalId(
functionName,
cloudWatchLogNumberInFunction
);
const lambdaPermissionLogicalId = this.provider.naming.getLambdaCloudWatchLogPermissionLogicalId(
functionName
);
// unescape quotes once when the first quote is detected escaped
const idxFirstSlash = FilterPattern.indexOf('\\');
const idxFirstQuote = FilterPattern.indexOf('"');
if (idxFirstSlash >= 0 && idxFirstQuote >= 0 && idxFirstQuote > idxFirstSlash) {
FilterPattern = FilterPattern.replace(/\\("|\\|')/g, (match, g) => g);
}
const cloudWatchLogRuleTemplate = `
{
"Type": "AWS::Logs::SubscriptionFilter",
"DependsOn": "${lambdaPermissionLogicalId}",
"Properties": {
"LogGroupName": "${LogGroupName}",
"FilterPattern": ${JSON.stringify(FilterPattern)},
"DestinationArn": { "Fn::GetAtt": ["${lambdaLogicalId}", "Arn"] }
}
}
`;
const commonSuffixOfLogGroupName = this.longestCommonSuffix(logGroupNamesThisFunction);
const permissionTemplate = `
{
"Type": "AWS::Lambda::Permission",
"Properties": {
"FunctionName": { "Fn::GetAtt": ["${lambdaLogicalId}", "Arn"] },
"Action": "lambda:InvokeFunction",
"Principal": {
"Fn::Join": [ "", [
"logs.",
{ "Ref": "AWS::Region" },
".amazonaws.com"
] ]
},
"SourceArn": {
"Fn::Join": [ "", [
"arn:",
{ "Ref": "AWS::Partition" },
":logs:",
{ "Ref": "AWS::Region" },
":",
{ "Ref": "AWS::AccountId" },
":log-group:",
"${commonSuffixOfLogGroupName}",
":*"
] ]
}
}
}
`;
const newCloudWatchLogRuleObject = {
[cloudWatchLogLogicalId]: JSON.parse(cloudWatchLogRuleTemplate),
};
const newPermissionObject = {
[lambdaPermissionLogicalId]: JSON.parse(permissionTemplate),
};
_.merge(
this.serverless.service.provider.compiledCloudFormationTemplate.Resources,
newCloudWatchLogRuleObject,
newPermissionObject
);
}
});
}
});
}
longestCommonSuffix(logGroupNames) {
const first = logGroupNames[0];
let longestCommon = logGroupNames.reduce((last, current) => {
for (let i = 0; i < last.length; i++) {
if (last[i] !== current[i]) {
return last.substring(0, i);
}
}
return last;
}, first);
if (logGroupNames.length > 1 && !longestCommon.endsWith('*')) {
longestCommon += '*';
}
return longestCommon;
}
}
module.exports = AwsCompileCloudWatchLogEvents;