forked from awslabs/aws-lambda-redshift-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
808 lines (729 loc) · 27.4 KB
/
common.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
/*
Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Amazon Software License (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/asl/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
var async = require('async');
var uuid = require('uuid');
require('./constants');
var pjson = require('./package.json');
// function which creates a string representation of now suitable for use in S3
// paths
exports.getFormattedDate = function (date) {
if (!date) {
date = new Date();
}
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
};
/* current time as seconds */
exports.now = function () {
return new Date().getTime() / 1000;
};
exports.readableTime = function (epochSeconds) {
var d = new Date(0);
d.setUTCSeconds(epochSeconds);
return exports.getFormattedDate(d);
};
exports.createTableAndWait = function (tableParams, dynamoDB, callback) {
dynamoDB.createTable(tableParams, function (err, data) {
if (err) {
if (err.code !== 'ResourceInUseException') {
console.log(err.toString());
callback(err);
} else {
console.log("Table " + tableParams.TableName + " already exists");
callback();
}
} else {
console.log("Created DynamoDB Table " + tableParams.TableName);
setTimeout(callback, 1000);
}
});
};
exports.createTables = function (dynamoDB, callback) {
// processed files table spec
var pfKey = 'loadFile';
var processedFilesSpec = {
AttributeDefinitions: [{
AttributeName: pfKey,
AttributeType: 'S'
}],
KeySchema: [{
AttributeName: pfKey,
KeyType: 'HASH'
}],
TableName: filesTable,
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 5
}
};
var configKey = s3prefix;
var configSpec = {
AttributeDefinitions: [{
AttributeName: configKey,
AttributeType: 'S'
}],
KeySchema: [{
AttributeName: configKey,
KeyType: 'HASH'
}],
TableName: configTable,
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 5
}
};
var batchKey = batchId;
var inputLoc = s3prefix;
var batchSpec = {
AttributeDefinitions: [{
AttributeName: batchKey,
AttributeType: 'S'
}, {
AttributeName: 'status',
AttributeType: 'S'
}, {
AttributeName: lastUpdate,
AttributeType: 'N'
}, {
AttributeName: inputLoc,
AttributeType: 'S'
}],
KeySchema: [{
AttributeName: inputLoc,
KeyType: 'HASH'
}, {
AttributeName: batchKey,
KeyType: 'RANGE'
}],
TableName: batchTable,
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 5
},
GlobalSecondaryIndexes: [{
IndexName: batchStatusGSI,
KeySchema: [{
AttributeName: 'status',
KeyType: 'HASH'
}, {
AttributeName: lastUpdate,
KeyType: 'RANGE'
}],
Projection: {
ProjectionType: 'ALL'
},
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 5
}
}]
};
console.log("Creating Tables in Dynamo DB if Required");
var functions = [exports.createTableAndWait.bind(undefined, processedFilesSpec, dynamoDB), exports.createTableAndWait.bind(undefined, batchSpec, dynamoDB),
exports.createTableAndWait.bind(undefined, configSpec, dynamoDB)];
async.waterfall(functions, function (err, results) {
if (err) {
console.log(err);
callback(err);
} else {
callback();
}
});
};
exports.retryableUpdate = function (dynamoDB, updateRequest, callback) {
var tryNumber = 0;
var writeRetryLimit = 100;
var done = false;
async.whilst(function () {
// retry until the try count is hit
return tryNumber < writeRetryLimit && done === false;
}, function (asyncCallback) {
tryNumber++;
dynamoDB.updateItem(updateRequest, function (err, data) {
if (err) {
if (err.code === 'ResourceInUseException' || err.code === 'ResourceNotFoundException' || err.code === 'ProvisionedThroughputExceededException') {
// retry in 1 second if the table is still in the process of
// being created
setTimeout(asyncCallback, 1000);
} else {
console.log(JSON.stringify(updateRequest));
console.log(err);
asyncCallback(err);
}
} else {
// all OK - exit OK
if (data) {
done = true;
asyncCallback(undefined, data);
} else {
var msg = "Wrote to DynamoDB but didn't receive a verification data element";
console.log(msg);
asyncCallback(msg);
}
}
});
}, function (err, data) {
callback(err, data);
});
};
exports.retryablePut = function (dynamoDB, putRequest, callback) {
var tryNumber = 0;
var writeRetryLimit = 100;
var done = false;
async.whilst(function () {
// retry until the try count is hit
return tryNumber < writeRetryLimit && done === false;
}, function (asyncCallback) {
tryNumber++;
dynamoDB.putItem(putRequest, function (err, data) {
if (err) {
if (err.code === 'ResourceInUseException' || err.code === 'ResourceNotFoundException' || err.code === 'ProvisionedThroughputExceededException') {
// retry in 1 second if the table is still in the process of
// being created
setTimeout(asyncCallback, 1000);
} else {
console.log(JSON.stringify(putRequest));
console.log(err);
asyncCallback(err);
}
} else {
// all OK - exit OK
if (data) {
done = true;
asyncCallback(undefined, data);
} else {
var msg = "Wrote to DynamoDB but didn't receive a verification data element";
console.log(msg);
asyncCallback(msg);
}
}
});
}, function (err) {
callback(err);
});
};
exports.dropTables = function (dynamoDB, callback) {
// drop the config table
dynamoDB.deleteTable({
TableName: configTable
}, function (err, data) {
if (err && err.code !== 'ResourceNotFoundException') {
console.log(err);
callback(err);
} else {
// drop the processed files table
dynamoDB.deleteTable({
TableName: filesTable
}, function (err, data) {
if (err && err.code !== 'ResourceNotFoundException') {
console.log(err);
callback(err);
} else {
// drop the batches table
dynamoDB.deleteTable({
TableName: batchTable
}, function (err, data) {
if (err && err.code !== 'ResourceNotFoundException') {
console.log(err);
callback(err);
}
console.log("All Configuration Tables Dropped");
// call the callback requested
if (callback) {
callback();
}
});
}
});
}
});
};
/* validate that the given value is a number, and if so return it */
exports.getIntValue = function (value, rl) {
if (!value || value === null) {
rl.close();
console.log('Null Value');
process.exit(INVALID_ARG);
} else {
var num = parseInt(value);
if (isNaN(num)) {
rl.close();
console.log('Value \'' + value + '\' is not a Number');
process.exit(INVALID_ARG);
} else {
return num;
}
}
};
exports.getBooleanValue = function (value) {
if (value) {
if (['TRUE', '1', 'YES', 'Y'].indexOf(value.toUpperCase()) > -1) {
return true;
} else {
return false;
}
} else {
return false;
}
};
/* validate that the provided value is not null/undefined */
exports.validateNotNull = function (value, message, rl) {
if (!value || value === null || value === '') {
rl.close();
console.log(message);
process.exit(INVALID_ARG);
}
};
/* turn blank lines read from STDIN to Null */
exports.blank = function (value) {
if (value === '') {
return null;
} else {
return value;
}
};
exports.validateArrayContains = function (array, value, rl) {
if (array.indexOf(value) === -1) {
rl.close();
console.log('Value must be one of ' + array.toString());
process.exit(INVALID_ARG);
}
};
exports.createManifestInfo = function (config) {
// manifest file will be at the configuration location, with a fixed
// prefix and the date plus a random value for uniqueness across all
// executing functions
var dateName = exports.getFormattedDate();
var rand = Math.floor(Math.random() * 10000);
var manifestInfo = {
manifestBucket: config.manifestBucket.S,
manifestKey: config.manifestKey.S,
manifestName: 'manifest-' + dateName + '-' + rand
};
manifestInfo.manifestPrefix = manifestInfo.manifestKey + '/' + manifestInfo.manifestName;
manifestInfo.manifestPath = manifestInfo.manifestBucket + "/" + manifestInfo.manifestPrefix;
return manifestInfo;
};
exports.randomInt = function (low, high) {
return Math.floor(Math.random() * (high - low) + low);
};
exports.getFunctionArn = function (lambda, functionName, callback) {
var params = {
FunctionName: functionName
};
lambda.getFunction(params, function (err, data) {
if (err) {
console.log(err);
callback(err);
} else {
if (data && data.Configuration) {
callback(undefined, data.Configuration.FunctionArn);
} else {
callback();
}
}
});
};
exports.getS3NotificationConfiguration = function (s3, bucket, prefix, functionArn, callback) {
var params = {
Bucket: bucket
};
s3.getBucketNotificationConfiguration(params, function (err, data) {
if (err) {
callback(err);
} else {
// have to iterate through all the function configurations
if (data.LambdaFunctionConfigurations && data.LambdaFunctionConfigurations.length > 0) {
var matchConfigId;
data.LambdaFunctionConfigurations.map(function (item) {
if (item && item.Filter && item.Filter.Key && item.Filter.Key.FilterRules) {
item.Filter.Key.FilterRules.map(function (filter) {
if (filter.Name === 'Prefix' && filter.Value === prefix) {
if (item.LambdaFunctionArn === functionArn) {
matchConfigId = item.Id;
}
}
});
}
});
if (matchConfigId) {
callback(undefined, matchConfigId, data);
} else {
callback(undefined, undefined, data);
}
} else {
callback();
}
}
});
};
function getS3Arn(bucket, prefix) {
var arn = "arn:aws:s3:::" + bucket;
if (prefix) {
arn = arn + prefix;
}
return arn;
}
exports.ensureS3InvokePermisssions = function (lambda, bucket, prefix, functionName, functionArn, callback) {
lambda.getPolicy({
FunctionName: functionName
}, function (err, data) {
if (err && err.code !== 'ResourceNotFoundException') {
callback(err);
}
var foundMatch = false;
var s3Arn = getS3Arn(bucket);
var sourceAccount = functionArn.split(":")[4];
// process the existing permissions policy if there is one
if (data && data.Policy) {
var statements = JSON.parse(data.Policy).Statement;
statements.map(function (item) {
try {
if (item.Resource === functionArn && item.Condition.StringEquals['AWS:SourceAccount'] === sourceAccount) {
foundMatch = true;
}
} catch (e) {
// this is OK - just means that the policy structure doesn't match the above format
}
});
}
if (foundMatch === true) {
console.log("Found existing Policy match for S3 path to invoke " + functionName);
callback();
} else {
var lambdaPermissions = {
Action: "lambda:InvokeFunction",
FunctionName: functionName,
Principal: "s3.amazonaws.com",
// only use internal account sources
SourceAccount: sourceAccount,
SourceArn: s3Arn,
StatementId: uuid.v4()
};
lambda.addPermission(lambdaPermissions, function (err, data) {
if (err) {
console.log(err);
callback(err);
} else {
console.log("Granted S3 permission to invoke " + functionArn);
callback();
}
});
}
});
};
exports.createS3EventSource = function (s3, lambda, bucket, prefix, functionName, callback) {
console.log("Creating S3 Event Source for s3://" + bucket + "/" + prefix);
// lookup the deployed function name to get the ARN
exports.getFunctionArn(lambda, functionName, function (err, functionArn) {
if (err) {
callback(err);
} else {
// blow up if there's no deployed function - can't create the event
// source
if (!functionArn) {
var msg = "Unable to resolve Function ARN for " + functionName;
console.log(msg);
callback(msg);
} else {
exports.getS3NotificationConfiguration(s3, bucket, prefix, functionArn, function (err, lambdaFunctionId, currentNotificationConfiguration) {
if (err) {
// this almost certainly will be because the bucket name
// doesn't exist
console.log(err);
callback(err);
} else {
if (lambdaFunctionId) {
// found an existing function
console.log("Found existing event source for s3://" + bucket + "/" + prefix + " forwarding notifications to " + functionArn);
callback(undefined, lambdaFunctionId);
} else {
// there isn't a matching event
// configuration so create a new one for the
// specified prefix
exports.ensureS3InvokePermisssions(lambda, bucket, prefix, functionName, functionArn, function (err, data) {
if (err) {
callback(err);
} else {
// add the notification configuration to the
// set of existing lambda configurations
if (!currentNotificationConfiguration) {
currentNotificationConfiguration = {};
}
if (!currentNotificationConfiguration.LambdaFunctionConfigurations) {
currentNotificationConfiguration.LambdaFunctionConfigurations = [];
}
configAlreadyExists = false;
// Let's check our configs to see if we already have one that exists
currentNotificationConfiguration.LambdaFunctionConfigurations.forEach(config => {
if (config.Filter.Key.FilterRules[0].Value == prefix + '/') {
console.log('Skipping creation of notification config because it already exists');
configAlreadyExists = true;
}
});
// Create a new notification config
if (!configAlreadyExists) {
console.log('Creating notification configuration');
// now create the event source mapping
var newEventConfiguration = {
Events: ['s3:ObjectCreated:*',],
LambdaFunctionArn: functionArn,
Filter: {
Key: {
FilterRules: [{
Name: 'prefix',
Value: prefix + "/"
}]
}
},
Id: "LambdaRedshiftLoaderEventSource-" + uuid.v4()
};
currentNotificationConfiguration.LambdaFunctionConfigurations.push(newEventConfiguration);
// push the function event trigger
// configurations back into S3
var params = {
Bucket: bucket,
NotificationConfiguration: currentNotificationConfiguration
};
s3.putBucketNotificationConfiguration(params, function (err, data) {
if (err) {
console.log(this.httpResponse.body.toString());
console.log(err);
callback(err);
} else {
callback();
}
});
}
}
});
}
}
});
}
}
});
};
// function which sets up the tables, writes the configuration, and creates the
// event source for S3->Lambda
exports.setup = function (useConfig, dynamoDB, s3, lambda, callback) {
// function to create tables
var createTables = function (c) {
exports.createTables(dynamoDB, function (err) {
c(err);
});
};
// function to write the configuration into the config tables
var writeConfig = function (c) {
exports.retryablePut(dynamoDB, useConfig, function (err) {
c(err);
});
};
// function which invokes the creation of the event source for the bucket
// and prefix
var createEventSource = function (c) {
var s3prefix = useConfig.Item.s3Prefix.S;
var tokens = s3prefix.split("/");
var bucket = tokens[0];
var prefix = tokens.slice(1).join("/");
// deployedFunctionName is defined in constants.js
exports.createS3EventSource(s3, lambda, bucket, prefix, deployedFunctionName, function (err, configId) {
c(err);
});
};
async.waterfall([createTables, writeConfig, createEventSource], function (err, result) {
if (err) {
console.log(err);
callback(err);
} else {
callback();
}
});
};
exports.inPlaceCopyFile = function (s3, batchId, batchEntry, callback) {
// issue a same source/target copy command to S3, which will cause
// Lambda to receive a new event
var bucketName = batchEntry.split("/")[0];
var fileKey = batchEntry.replace(bucketName + "\/", "");
var headSpec = {
Bucket: bucketName,
Key: fileKey,
};
s3.headObject(headSpec, function (err, data) {
if (err) {
console.log(err);
callback(err);
} else {
// Modify the metadata to allow the in-place copy
var meta;
if (data.Metadata) {
meta = data.Metadata;
} else {
meta = {}
}
if (batchId) {
meta["x-amz-meta-copy-reason"] = "AWS Lambda Redshift Loader Reprocess Batch " + batchId;
} else {
meta["x-amz-meta-copy-reason"] = "AWS Lambda Redshift Loader Reprocess File";
}
// request the copy
var copySpec = {
Metadata: meta,
MetadataDirective: "REPLACE",
Bucket: bucketName,
Key: fileKey,
CopySource: batchEntry
};
s3.copyObject(copySpec, function (err, data) {
if (err) {
console.log(err);
callback(err);
} else {
console.log("Submitted reprocess request for " + batchEntry);
// done - call the callback
callback();
}
});
}
});
};
exports.updateConfig = function (s3Prefix, configAttribute, configValue, dynamoDB, callback) {
var dynamoConfig = {
TableName: configTable,
Key: {
"s3Prefix": {
S: s3Prefix
}
},
ExpressionAttributeNames: {
"#attribute": configAttribute
}
};
if (configValue) {
dynamoConfig.UpdateExpression = "set #attribute = :value, #version = :version";
dynamoConfig.ExpressionAttributeValues = {
":value":
{
S: configValue
}
};
dynamoConfig.ExpressionAttributeNames["#version"] = "version";
dynamoConfig.ExpressionAttributeValues[":version"] = {
S: pjson.version
};
} else {
dynamoConfig.UpdateExpression = "remove #attribute";
}
exports.retryableUpdate(dynamoDB, dynamoConfig, function (err, data) {
callback(err);
});
}
exports.deleteFile = function (dynamoDB, region, file, callback) {
var fileItem = {
Key: {
loadFile: {
S: file
}
},
TableName: filesTable
};
dynamoDB.deleteItem(fileItem, function (err, data) {
callback(err, data);
});
}
exports.queryFile = function (dynamoDB, region, file, callback) {
var fileItem = {
Key: {
loadFile: {
S: file
}
},
TableName: filesTable
};
dynamoDB.getItem(fileItem, function (err, data) {
callback(err, data);
});
}
exports.reprocessFile = function (dynamoDB, s3, region, file, callback) {
// get the file so we know what the current batch ID is
var fileItem = {
Key: {
loadFile: {
S: file
}
},
TableName: filesTable
};
dynamoDB.getItem(fileItem, function (err, data) {
if (err) {
if (callback) {
callback(err);
}
} else {
if (data.Item.batchId && data.Item.batchId.S) {
var updateExpr = "remove #batchId ";
if (data.Item.previousBatches) {
// add to the end of the list
updateExpr = updateExpr + "set previousBatches = list_append(previousBatches,:oldBatch)"
} else {
// create a new list
updateExpr = updateExpr + "set previousBatches = :oldBatch";
}
// rotate the current batch information onto a tracking list
var update = {
Key: {
loadFile: {
S: file
}
},
TableName: filesTable,
ExpressionAttributeNames: {
"#batchId": "batchId"
},
ExpressionAttributeValues: {
":oldBatch": {
L: [
{S: "" + data.Item.batchId.S}
]
}
},
UpdateExpression: updateExpr,
ReturnValues: "ALL_NEW"
};
dynamoDB.updateItem(update, function (err, data) {
if (err) {
callback(err);
} else {
// now the file needs an in-place copy with new metadata to cause a reprocess
exports.inPlaceCopyFile(s3, undefined, file, function (err, data) {
if (callback) {
callback(err);
}
});
}
});
} else {
// not currently assigned to a batch, so just do an s3 update
exports.inPlaceCopyFile(s3, undefined, file, function (err, data) {
if (callback) {
callback(err);
}
});
}
}
});
}