This repository has been archived by the owner on Jul 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
251 lines (209 loc) · 7.32 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
var url = require('url');
var https = require('https');
var AWS = require('aws-sdk');
var AgentKeepAlive = require('agentkeepalive');
var crypto = require('crypto');
module.exports = streambot;
module.exports.env = manageEnv;
module.exports.connector = manageConnector;
module.exports.agent = new AgentKeepAlive.HttpsAgent({
keepAlive: true,
maxSockets: Math.ceil(require('os').cpus().length * 16),
keepAliveTimeout: 60000
});
var tableName = module.exports.tableName = 'streambot-env';
function streambot(service) {
return function streambot(event, context) {
console.log('Start time: %s', (new Date()).toISOString());
console.log('Event md5: %s', crypto.createHash('md5').update(JSON.stringify(event)).digest('hex'));
var callback = context.done.bind(context);
var functionArn = context.invokedFunctionArn;
var functionRegion = functionArn.split(':')[3];
var dynamodb = new AWS.DynamoDB({
region: functionRegion,
maxRetries: 1000,
httpOptions: {
timeout: 500,
agent: module.exports.agent
}
});
var getParams = {
TableName: tableName,
Key: { name: { S: context.functionName } }
};
dynamodb.getItem(getParams, function(err, data) {
if (err) {
console.log('[error] Failed to load environment in %s: %s', functionRegion, err.message);
return context.fail(err);
}
if (!data.Item) {
console.log('No environment found!');
return service.call(context, event, callback);
}
console.log('Loaded environment: %s', JSON.stringify(getParams));
var env = JSON.parse(data.Item.env.S);
Object.keys(env).forEach(function(key) {
process.env[key] = env[key];
});
service.call(context, event, callback);
}).on('retry', function(res) {
if (res.error) {
console.log('[streambot request failed] dynamodb.getItem | %s | request id: %s | retries: %s',
res.error.code, res.requestId, res.retryCount
);
// Other errors automatically retryable by aws-sdk:
// https://github.com/aws/aws-sdk-js/blob/d20ddadd7ac39b81f4262cacd1ad29813988bf84/lib/service.js#L314-L320
if (res.error.name === 'TimeoutError') res.error.retryable = true;
}
});
};
}
function isCloudFormationEvent(event) {
var required = [
'RequestType',
'ResourceProperties',
'StackId',
'LogicalResourceId',
'RequestId',
'ResponseURL'
];
return required.reduce(function(valid, key) {
if (!(key in event)) return false;
return key;
}, true);
}
function respond(err, data, event, context) {
if (err) console.log(err);
var status = err ? 'FAILED' : 'SUCCESS';
if (err && !err.message) {
err.message = 'An unexpected error occurred';
if (err.code) err.message += ': ' + err.code;
}
var body = JSON.stringify({
Status: status,
Reason: err ? err.message : '',
PhysicalResourceId: event.PhysicalResourceId || context.logStreamName,
StackId: event.StackId,
LogicalResourceId: event.LogicalResourceId,
RequestId: event.RequestId,
Data: data
});
var parsedUrl = url.parse(event.ResponseURL);
var options = {
hostname: parsedUrl.hostname,
port: 443,
path: parsedUrl.path,
method: 'PUT',
headers: {
'content-type': '',
'content-length': body.length
}
};
console.log('Send response to: %j', options);
console.log('Response body: %s', body);
(function sendResponse(attempts) {
if (attempts > 5) return context.done(new Error('Failed to respond to CloudFormation'));
var req = https.request(options, function(res) {
console.log('Response status: ' + res.statusCode);
console.log('Response headers: ' + JSON.stringify(res.headers));
context.done(null, err || body);
}).on('error', function(err) {
console.log(err);
attempts++;
sendResponse(attempts);
});
req.write(body);
req.end();
})(0);
}
function manageEnv(event, context) {
var functionArn = context.invokedFunctionArn;
var functionRegion = functionArn.split(':')[3];
var dynamodb = new AWS.DynamoDB({
region: functionRegion,
maxRetries: 1000,
httpOptions: {
timeout: 500,
agent: module.exports.agent
}
});
if (!isCloudFormationEvent(event))
return context.done(null, 'ERROR: Invalid CloudFormation event');
if (!event.ResourceProperties.FunctionName)
return respond(new Error('Invalid StreambotEnv parameters'), null, event, context);
console.log('%s config for %s', event.RequestType, event.ResourceProperties.FunctionName);
if (event.RequestType === 'Delete') return dynamodb.deleteItem({
TableName: tableName,
Key: { name: { S: event.ResourceProperties.FunctionName } }
}, function(err) {
respond(err, null, event, context);
});
var env = Object.keys(event.ResourceProperties).reduce(function(env, key) {
if (key !== 'ServiceToken' && key !== 'FunctionName')
env[key] = event.ResourceProperties[key];
return env;
}, {});
dynamodb.putItem({
TableName: tableName,
Item: {
name: { S: event.ResourceProperties.FunctionName },
env: { S: JSON.stringify(env) }
}
}, function(err) {
respond(err, null, event, context);
});
}
function manageConnector(event, context) {
if (!isCloudFormationEvent(event))
return context.done(null, 'ERROR: Invalid CloudFormation event');
var requiredProperties = [
'FunctionRegion',
'FunctionName',
'StreamArn'
];
var valid = requiredProperties.reduce(function(valid, key) {
if (!(key in event.ResourceProperties)) return false;
return key;
}, true);
if (!valid)
return respond(new Error('Invalid StreambotConnector parameters'), null, event, context);
console.log(
'%s eventSourceMapping for %s: %s - %s',
event.RequestType,
event.StackId,
event.ResourceProperties.StreamArn,
event.ResourceProperties.FunctionName
);
var lambda = new AWS.Lambda({ region: event.ResourceProperties.FunctionRegion });
lambda.listEventSourceMappings({
EventSourceArn: event.ResourceProperties.StreamArn,
FunctionName: event.ResourceProperties.FunctionName
}, function(err, data) {
if (err && event.RequestType === 'Delete') return respond(null, null, event, context);
if (err) return respond(err, null, event, context);
var existingUUID = data.EventSourceMappings.length ?
data.EventSourceMappings[0].UUID : null;
if (event.RequestType === 'Delete') {
if (!existingUUID) return respond(null, null, event, context);
return lambda.deleteEventSourceMapping({ UUID: existingUUID }, function(err) {
respond(err, null, event, context);
});
}
var params = {
FunctionName: event.ResourceProperties.FunctionName,
BatchSize: event.ResourceProperties.BatchSize || 100,
Enabled: event.ResourceProperties.hasOwnProperty('Enabled') ?
event.ResourceProperties.Enabled : true
};
if (existingUUID) {
params.UUID = existingUUID;
} else {
params.StartingPosition = event.ResourceProperties.StartingPosition || 'TRIM_HORIZON';
params.EventSourceArn = event.ResourceProperties.StreamArn;
}
var action = existingUUID ? 'updateEventSourceMapping' : 'createEventSourceMapping';
lambda[action](params, function(err, data) {
respond(err, data ? { UUID: data.UUID } : null, event, context);
});
});
}