-
Notifications
You must be signed in to change notification settings - Fork 163
/
index.js
1650 lines (1477 loc) · 67.6 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
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 debug = (process.env['DEBUG'] === 'true');
var log_level = process.env['LOG_LEVEL'] || 'info';
var pjson = require('./package.json');
var region = process.env['AWS_REGION'];
let semver = require('semver');
if (!region || region === null || region === "") {
region = "us-east-1";
console.log("AWS Lambda Redshift Database Loader using default region " + region);
}
var aws = require('aws-sdk');
aws.config.update({
region: region
});
var https_proxy = process.env['https_proxy'];
if (https_proxy !== undefined && https_proxy !== "") {
console.log("Using proxy server " + https_proxy);
var proxy_agent = require('https-proxy-agent');
aws.config.update({
httpOptions: {agent: new proxy_agent(https_proxy)}
});
}
var s3 = new aws.S3({
apiVersion: '2006-03-01',
region: region
});
var dynamoDB = new aws.DynamoDB({
apiVersion: '2012-08-10',
region: region
});
var sns = new aws.SNS({
apiVersion: '2010-03-31',
region: region
});
require('./constants');
var kmsCrypto = require('./kmsCrypto');
kmsCrypto.setRegion(region);
var common = require('./common');
var async = require('async');
var uuid = require('uuid');
const {Client} = require('pg');
const maxRetryMS = 200;
const winston = require('winston');
const logger = winston.createLogger({
level: debug === true ? 'debug' : log_level,
transports: [
new winston.transports.Console({
format: winston.format.simple()
})
]
});
// empty import/invocation of the keepalive fix for node-postgres module
require('pg-ka-fix')();
var upgrade = require('./upgrades');
// load the list of prefixes where wildcard expansion should be suppressed. this can be a blanket switch if set to *
let suppressWildcardPrefixes = common.getWildcardPrefixSuppressionList();
function getConfigWithRetry(prefix, callback) {
var proceed = false;
var lookupConfigTries = 10;
var tryNumber = 0;
var configData = null;
var dynamoLookup = {
Key: {
s3Prefix: {
S: prefix
}
},
TableName: configTable,
ConsistentRead: true
};
logger.debug(JSON.stringify(dynamoLookup));
async.whilst(function (test_cb) {
// return OK if the proceed flag has been set, or if
// we've hit the retry count
test_cb(null, !proceed && tryNumber < lookupConfigTries);
}, function (callback) {
tryNumber++;
logger.debug("Fetching S3 Configuration: Try " + tryNumber);
// lookup the configuration item, and run foundConfig on completion
dynamoDB.getItem(dynamoLookup, function (err, data) {
if (err) {
if (err.code === provisionedThroughputExceeded) {
// sleep for bounded jitter time up to 1
// second and then retry
var timeout = common.randomInt(0, 1000);
logger.info(provisionedThroughputExceeded + " while accessing " + configTable + ". Retrying in " + timeout + " ms");
setTimeout(callback, timeout);
} else {
// some other error - call the error callback
callback(err);
}
} else {
configData = data;
proceed = true;
callback(null);
}
});
}, function (err) {
if (err) {
logger.error(err);
callback(err);
} else {
callback(null, configData);
}
});
}
exports.getConfigWithRetry = getConfigWithRetry;
function resolveConfig(prefix, successCallback, noConfigFoundCallback) {
var searchPrefix = prefix;
var config;
async.until(function (test_cb) {
// run until we have found a configuration item, or the search
// prefix is undefined due to the shortening being completed
test_cb(null, config || !searchPrefix);
}, function (untilCallback) {
// query for the prefix, implementing a reduce by '/' each time,
// such that we load the most specific config first
logger.debug("Extracting S3 Config for Path: " + searchPrefix);
getConfigWithRetry(searchPrefix, function (err, data) {
if (err) {
untilCallback(err);
} else {
if (data.Item) {
// set the config = this will cause the 'until' to complete
config = data;
} else {
// reduce the search prefix by one prefix item
searchPrefix = searchPrefix.shortenPrefix();
}
untilCallback();
}
});
}, function (err) {
if (err) {
noConfigFoundCallback(err)
} else {
if (config) {
successCallback(err, config);
} else {
noConfigFoundCallback(err);
}
}
});
};
exports.resolveConfig = resolveConfig;
// main function for AWS Lambda
function handler(event, context) {
/** runtime functions * */
/*
* Function which performs all version upgrades over time - must be able to
* do a forward migration from any version to 'current' at all times!
*/
function upgradeConfig(s3Info, currentConfig, callback) {
// v 1.x to 2.x upgrade for multi-cluster loaders
if (semver.lt(currentConfig.version.S, pjson.version)) {
logger.debug(`Performing version upgrade from ${currentConfig.version.S} to ${pjson.version}`);
upgrade.upgradeAll(dynamoDB, s3Info, currentConfig, callback);
} else {
// no upgrade needed
callback(null, s3Info, currentConfig);
}
}
/* callback run when we find a configuration for load in Dynamo DB */
function foundConfig(s3Info, err, data) {
if (err) {
logger.error(err);
var msg = `Error getting Redshift Configuration for ${s3Info.prefix} from DynamoDB`;
logger.error(msg);
context.done(error, msg);
}
logger.info(`Found Redshift Load Configuration for ${s3Info.prefix}`);
var config = data.Item;
var thisBatchId = config.currentBatch.S;
// run all configuration upgrades required
upgradeConfig(s3Info, config, function (err, s3Info, useConfig) {
if (err) {
console.error(JSON.stringify(err));
context.done(error, JSON.stringify(err));
} else {
if (useConfig.filenameFilterRegex) {
var isFilterRegexMatch = true;
try {
isFilterRegexMatch = s3Info.key.match(useConfig.filenameFilterRegex.S);
} catch (e) {
// suppress this error - it may have been a malformed
// regex as well as just a non-match
// exceptions are treated as a file match here - we'd
// rather process a file and have the batch
// fail than erroneously ignore it
logger.error("Error on filename filter evaluation. File will be included for processing");
logger.error(e);
}
if (isFilterRegexMatch) {
checkFileProcessed(useConfig, thisBatchId, s3Info);
} else {
logger.info('Object ' + s3Info.key + ' excluded by filename filter \'' + useConfig.filenameFilterRegex.S + '\'');
// scan the current batch to decide if it needs to be
// flushed due to batch timeout
processPendingBatch(useConfig, thisBatchId, s3Info);
}
} else {
// no filter, so we'll load the data
checkFileProcessed(useConfig, thisBatchId, s3Info);
}
}
});
}
/*
* function to add a file to the pending batch set and then call the success
* callback
*/
function checkFileProcessed(config, thisBatchId, s3Info) {
var itemEntry = s3Info.bucket + '/' + s3Info.key;
// perform the idempotency check for the file before we put it
// into a manifest
var fileEntry = {
Key: {
loadFile: {
S: itemEntry
}
},
TableName: filesTable,
ExpressionAttributeNames: {
"#rcvDate": "receiveDateTime"
},
ExpressionAttributeValues: {
":rcvDate": {
S: common.readableTime(common.now())
},
":incr": {
N: "1"
}
},
UpdateExpression: "set #rcvDate = :rcvDate add timesReceived :incr",
ReturnValues: "ALL_NEW"
};
logger.debug("Checking whether File is already processed");
logger.debug(JSON.stringify(fileEntry));
// add the file to the processed list
dynamoDB.updateItem(fileEntry, function (err, data) {
var msg;
if (err) {
msg = "Error " + err.code + " for " + fileEntry;
logger.error(msg);
context.done(error, msg);
} else {
if (!data) {
msg = "Update failed to return data from Processed File Check";
logger.error(msg);
context.done(error, msg);
} else {
if (data.Attributes.batchId && data.Attributes.batchId.S) {
// there's already a pending batch link, so this is a
// full duplicate and we'll discard
logger.info("File " + itemEntry + " Already Processed");
context.done(null, null);
} else {
// update was successful, and either this is the first
// event and there was no batch ID
// specified, or the file is a reprocess but the batch
// ID attachment didn't work - proceed
// with adding the entry to the pending batch
addFileToPendingBatch(config, thisBatchId, s3Info, itemEntry);
}
}
}
});
};
/**
* Function run to add a file to the existing open batch. This will
* repeatedly try to write and if unsuccessful it will requery the batch ID
* on the configuration
*/
function addFileToPendingBatch(config, thisBatchId, s3Info, itemEntry) {
console.log("Adding Pending Batch Entry for " + itemEntry);
var proceed = false;
var asyncError;
var addFileRetryLimit = 100;
var tryNumber = 0;
var configReloads = 0;
async.whilst(
function (test_cb) {
// return OK if the proceed flag has been set, or if we've hit
// the retry count
test_cb(null, !proceed && tryNumber < addFileRetryLimit);
},
function (callback) {
tryNumber++;
// build the reference to the pending batch, with an atomic add
// of the current file
var now = common.now();
var item = {
Key: {
batchId: {
S: thisBatchId
},
s3Prefix: {
S: s3Info.prefix
}
},
TableName: batchTable,
UpdateExpression: "add writeDates :appendFileDate, size :size set #stat = :open, lastUpdate = :updateTime, entryMap = list_append(if_not_exists(entryMap, :emptyList), :entry)",
ExpressionAttributeNames: {
"#stat": 'status'
},
ExpressionAttributeValues: {
":entry": {
L: [{
M: {
"file": {S: itemEntry},
"size": {N: '' + s3Info.size}
}
}
]
},
":emptyList": {
L: []
},
":appendFileDate": {
NS: ['' + now]
},
":updateTime": {
N: '' + now
},
":open": {
S: open
},
":size": {
N: '' + s3Info.size
}
},
/*
* current batch can't be locked
*/
ConditionExpression: "#stat = :open or attribute_not_exists(#stat)"
};
logger.debug(JSON.stringify(item));
// add the file to the pending batch
dynamoDB.updateItem(item, function (err, data) {
if (err) {
let waitFor = Math.min(Math.pow(tryNumber, 2) * 10, maxRetryMS);
if (err.code === provisionedThroughputExceeded) {
logger.warn("Provisioned Throughput Exceeded on addition of " + s3Info.prefix + " to pending batch " + thisBatchId + ". Trying again in " + waitFor + " ms");
setTimeout(callback, waitFor);
} else if (err.code === conditionCheckFailed) {
// the batch I have a reference to was locked so
// reload the current batch ID from the config
var configReloadRequest = {
Key: {
s3Prefix: {
S: s3Info.prefix
}
},
TableName: configTable,
/*
* we need a consistent read here to ensure we
* get the latest batch ID
*/
ConsistentRead: true
};
dynamoDB.getItem(configReloadRequest, function (err, data) {
configReloads++;
if (err) {
if (err === provisionedThroughputExceeded) {
logger.warn("Provisioned Throughput Exceeded on reload of " + configTable + " due to locked batch write");
callback();
} else {
console.log(err);
callback(err);
}
} else {
if (data.Item.currentBatch.S === thisBatchId) {
// we've obtained the same batch ID back
// from the configuration as we have
// now, meaning it hasn't yet rotated
logger.warn("Batch " + thisBatchId + " still current after configuration reload attempt " + configReloads + ". Recycling in " + waitFor + " ms.");
// because the batch hasn't been
// reloaded on the configuration, we'll
// backoff here for a moment to let that
// happen
setTimeout(callback, waitFor);
} else {
// we've got an updated batch id, so use
// this in the next cycle of file add
thisBatchId = data.Item.currentBatch.S;
logger.warn("Obtained new Batch ID " + thisBatchId + " after configuration reload. Attempt " + configReloads);
/*
* callback immediately, as we should
* now have a valid and open batch to
* use
*/
callback();
}
}
});
} else {
asyncError = err;
proceed = true;
callback();
}
} else {
// no error - the file was added to the batch, so mark
// the operation as OK so async will not retry
proceed = true;
callback();
}
});
},
function (err) {
if (err) {
// throw presented errors
logger.error(JSON.stringify(err));
context.done(error, JSON.stringify(err));
} else {
if (asyncError) {
/*
* throw errors which were encountered during the async
* calls
*/
logger.error(JSON.stringify(asyncError));
context.done(error, JSON.stringify(asyncError));
} else {
if (!proceed) {
/*
* process what happened if the iterative request to
* write to the open pending batch timed out
*
* TODO Can we force a rotation of the current batch
* at this point?
*/
var e = "Unable to write "
+ itemEntry
+ " in "
+ addFileRetryLimit
+ " attempts. Failing further processing to Batch "
+ thisBatchId
+ " which may be stuck in '"
+ locked
+ "' state. If so, unlock the batch using `node unlockBatch.js <region> <batch ID> <s3Prefix>`, delete the processed file marker with `node processedFiles.js --delete --file <filename> --region <region>`, and then re-store the file in S3";
logger.error(e);
var msg = "Lambda Redshift Loader unable to write to Open Pending Batch";
if (config.failureTopicARN) {
sendSNS(config.failureTopicARN.S, msg, e, function () {
context.done(error, e);
}, function (err) {
logger.error(err);
context.done(error, "Unable to Send SNS Notification");
});
} else {
logger.error("Unable to send failure notifications");
logger.error(msg);
context.done(error, msg);
}
} else {
// the add of the file was successful,
// so we
linkProcessedFileToBatch(itemEntry, thisBatchId);
// which is async, so may fail but we'll
// still sweep
// the pending batch
processPendingBatch(config, thisBatchId, s3Info);
}
}
}
});
};
/**
* Function which will link the deduplication table entry for the file to
* the batch into which the file was finally added
*/
function linkProcessedFileToBatch(itemEntry, batchId) {
var updateProcessedFile = {
Key: {
loadFile: {
S: itemEntry
}
},
TableName: filesTable,
AttributeUpdates: {
batchId: {
Action: 'PUT',
Value: {
S: batchId
}
}
}
};
logger.debug("Linking file to current batch");
logger.debug(JSON.stringify(updateProcessedFile));
common.retryableUpdate(dynamoDB, updateProcessedFile, function (err, data) {
// because this is an async call which doesn't affect
// process flow, we'll just log the error and do nothing with the OK
// response
if (err) {
logger.error(err);
}
});
};
/**
* Function which links the manifest name used to load redshift onto the
* batch table entry
*/
function addManifestToBatch(config, thisBatchId, s3Info, manifestInfo) {
// build the reference to the pending batch, with an atomic
// add of the current file
var item = {
Key: {
batchId: {
S: thisBatchId
},
s3Prefix: {
S: s3Info.prefix
}
},
TableName: batchTable,
AttributeUpdates: {
manifestFile: {
Action: 'PUT',
Value: {
S: manifestInfo.manifestPath
}
},
lastUpdate: {
Action: 'PUT',
Value: {
N: '' + common.now()
}
}
}
};
logger.debug("Linking manifest file pointer to Batch");
logger.debug(JSON.stringify(item));
common.retryableUpdate(dynamoDB, item, function (err, data) {
if (err) {
logger.error(err);
} else {
logger.info("Linked Manifest " + manifestInfo.manifestName + " to Batch " + thisBatchId);
}
});
};
/**
* Function to process the current pending batch, and create a batch load
* process if required on the basis of size or timeout
*/
function processPendingBatch(config, thisBatchId, s3Info) {
// make the request for the current batch
var currentBatchRequest = {
Key: {
batchId: {
S: thisBatchId
},
s3Prefix: {
S: s3Info.prefix
}
},
TableName: batchTable,
ConsistentRead: true
};
logger.debug("Loading current Batch record from prefix config");
logger.debug(JSON.stringify(currentBatchRequest));
dynamoDB.getItem(currentBatchRequest, function (err, data) {
if (err) {
if (err === provisionedThroughputExceeded) {
logger.warn("Provisioned Throughput Exceeded on read of " + batchTable);
callback();
} else {
logger.error(JSON.stringify(err));
context.done(error, JSON.stringify(err));
}
} else if (!data || !data.Item) {
var msg = "No open pending Batch " + thisBatchId;
logger.error(msg);
context.done(null, msg);
} else {
// first step is to resolve the earliest writeDate as the batch
// creation date
var batchCreateDate;
data.Item.writeDates.NS.map(function (item) {
var t = parseInt(item);
if (!batchCreateDate || t < batchCreateDate) {
batchCreateDate = t;
}
});
var lastUpdateTime = data.Item.lastUpdate.N;
/*
* grab the pending entries from the locked
* batch. We have 2 copies - a batch that uses StringSet from pre 2.7.8, and a List from 2.7.9
*/
let pendingEntries = {};
let pendingEntryCount = 0;
if (data.Item.entryMap) {
pendingEntryCount += data.Item.entryMap.L.length;
pendingEntries["entryMap"] = data.Item.entryMap.L;
}
if (data.Item.entrySet) {
pendingEntryCount += data.Item.entries.SS.length;
pendingEntries["entrySet"] = data.Item.entries.SS;
}
var doProcessBatch = false;
if (pendingEntryCount >= parseInt(config.batchSize.N)) {
logger.info("Batch count " + config.batchSize.N + " reached");
doProcessBatch = true;
} else {
if (config.batchSize && config.batchSize.N) {
logger.debug("Current batch count of " + pendingEntryCount + " below batch limit of " + config.batchSize.N);
}
}
// check whether the current batch is bigger than the configured
// max count, size, or older than configured max age
if (config.batchTimeoutSecs && config.batchTimeoutSecs.N && pendingEntryCount > 0 && common.now() - batchCreateDate > parseInt(config.batchTimeoutSecs.N)) {
logger.info("Batch age " + config.batchTimeoutSecs.N + " seconds reached");
doProcessBatch = true;
} else {
if (config.batchTimeoutSecs && config.batchTimeoutSecs.N) {
logger.debug("Current batch age of " + (common.now() - batchCreateDate) + " seconds below batch timeout: "
+ (config.batchTimeoutSecs.N ? config.batchTimeoutSecs.N : "None Defined"));
}
}
if (config.batchSizeBytes && config.batchSizeBytes.N && pendingEntryCount > 0 && parseInt(config.batchSizeBytes.N) <= parseInt(data.Item.size.N)) {
logger.info("Batch size " + config.batchSizeBytes.N + " bytes reached");
doProcessBatch = true;
} else {
if (data.Item.size.N) {
logger.debug("Current batch size of " + data.Item.size.N + " below batch threshold or not configured");
}
}
if (doProcessBatch) {
// set the current batch to locked status
var updateCurrentBatchStatus = {
Key: {
batchId: {
S: thisBatchId
},
s3Prefix: {
S: s3Info.prefix
}
},
TableName: batchTable,
AttributeUpdates: {
status: {
Action: 'PUT',
Value: {
S: locked
}
},
lastUpdate: {
Action: 'PUT',
Value: {
N: '' + common.now()
}
}
},
/*
* the batch to be processed has to be 'open', otherwise
* we'll have multiple processes all handling a single
* batch
*/
Expected: {
status: {
AttributeValueList: [{
S: open
}],
ComparisonOperator: 'EQ'
}
},
/*
* add the ALL_NEW return values so we have the most up
* to date version of the entries string set
*/
ReturnValues: "ALL_NEW"
};
logger.debug("Attempting to lock Batch for processing");
logger.debug(JSON.stringify(updateCurrentBatchStatus));
common.retryableUpdate(dynamoDB, updateCurrentBatchStatus, function (err, data) {
if (err) {
if (err.code === conditionCheckFailed) {
// some other Lambda function has locked the
// batch - this is OK and we'll just exit
// quietly
logger.debug("Batch is ready to be processed, but another thread has locked it for loading");
context.done(null, null);
} else if (err.code === provisionedThroughputExceeded) {
logger.error("Provisioned Throughput Exceeded on " + batchTable + " while trying to lock Batch");
context.done(error, JSON.stringify(err));
} else {
logger.error("Unhandled exception while trying to lock Batch " + thisBatchId);
logger.error(JSON.stringify(err));
context.done(error, JSON.stringify(err));
}
} else {
if (!data || !data.Attributes) {
var e = "Unable to extract latest pending entries set from Locked batch";
logger.error(e);
context.done(error, e);
} else {
/*
* assign the loaded configuration a new batch
* ID
*/
var allocateNewBatchRequest = {
Key: {
s3Prefix: {
S: s3Info.prefix
}
},
TableName: configTable,
AttributeUpdates: {
currentBatch: {
Action: 'PUT',
Value: {
S: uuid.v4()
}
},
lastBatchRotation: {
Action: 'PUT',
Value: {
S: common.getFormattedDate()
}
}
}
};
logger.debug("Allocating new Batch ID for future processing");
logger.debug(JSON.stringify(allocateNewBatchRequest));
common.retryableUpdate(dynamoDB, allocateNewBatchRequest, function (err, data) {
if (err) {
logger.error("Error while allocating new Pending Batch ID");
logger.error(JSON.stringify(err));
context.done(error, JSON.stringify(err));
} else {
// OK - let's create the manifest file
createManifest(config, thisBatchId, s3Info, pendingEntries);
}
});
}
}
});
} else {
logger.info("No pending batch flush required");
context.done(null, null);
}
}
});
};
/**
* Function which will create the manifest for a given batch and entries
*/
function createManifest(config, thisBatchId, s3Info, batchEntries) {
logger.info("Creating Manifest for Batch " + thisBatchId);
var manifestInfo = common.createManifestInfo(config);
// create the manifest file for the file to be loaded
var manifestContents = {
entries: []
};
logger.debug("Building new COPY Manifest");
function addEntry(url, contentLength) {
manifestContents.entries.push({
/*
* fix url encoding for files with spaces. Space values come in from
* Lambda with '+' and plus values come in as %2B. Redshift wants
* the original S3 value
*/
url: 's3://' + url.replace(/\+/g, ' ').replace(/%2B/g, '+'),
mandatory: true,
meta: {
content_length: contentLength
}
});
}
// process the batch contents which are structured as a map listing filename and file size
if (batchEntries.entryMap) {
batchEntries.entryMap.map(function (batchEntry) {
addEntry(batchEntry.M.file.S, parseInt(batchEntry.M.size.N));
});
}
// process batch contents which are structured as a StringSet
if (batchEntries.entrySet) {
batchEntries.entrySet.map(function (batchEntry) {
addEntry(batchEntry, s3Info.size);
});
}
let s3PutParams = {
Bucket: manifestInfo.manifestBucket,
Key: manifestInfo.manifestPrefix,
Body: JSON.stringify(manifestContents)
};
logger.info("Writing manifest to " + manifestInfo.manifestBucket + "/" + manifestInfo.manifestPrefix);
/*
* save the manifest file to S3 and build the rest of the copy command
* in the callback letting us know that the manifest was created
* correctly
*/
s3.putObject(s3PutParams, loadRedshiftWithManifest.bind(undefined, config, thisBatchId, s3Info, manifestInfo));
};
/**
* Function run when the Redshift manifest write completes successfully
*/
function loadRedshiftWithManifest(config, thisBatchId, s3Info, manifestInfo, err, data) {
if (err) {
logger.error("Error on Manifest Creation");
logger.error(err);
failBatch(err, config, thisBatchId, s3Info, manifestInfo);
} else {
logger.info("Created Manifest " + manifestInfo.manifestPath + " Successfully");
// add the manifest file to the batch - this will NOT stop
// processing if it fails
addManifestToBatch(config, thisBatchId, s3Info, manifestInfo);
// convert the config.loadClusters list into a format that
// looks like a native dynamo entry
var clustersToLoad = [];
for (var i = 0; i < config.loadClusters.L.length; i++) {
clustersToLoad[clustersToLoad.length] = config.loadClusters.L[i].M;
}
logger.info("Loading " + clustersToLoad.length + " Clusters");
// run all the cluster loaders in parallel
async.map(clustersToLoad, function (item, callback) {
// call the load cluster function, passing it the continuation
// callback
loadCluster(config, thisBatchId, s3Info, manifestInfo, item, callback);
}, function (err, results) {
if (err) {
logger.error(err);
}
// go through all the results - if they were all
// OK, then close the batch OK - otherwise fail
var allOK = true;
var loadState = {};
for (var i = 0; i < results.length; i++) {
if (!results[i] || results[i].status === ERROR) {
allOK = false;
logger.error("Cluster Load Failure " + results[i].error + " on Cluster " + results[i].cluster);
}
// log the response state for each cluster
loadState[results[i].cluster] = {
status: results[i].status,
error: results[i].error
};
}
var loadStateRequest = {
Key: {
batchId: {
S: thisBatchId
},
s3Prefix: {
S: s3Info.prefix
}
},
TableName: batchTable,
AttributeUpdates: {
clusterLoadStatus: {
Action: 'PUT',
Value: {
S: JSON.stringify(loadState)
}
},
lastUpdate: {
Action: 'PUT',
Value: {
N: '' + common.now()
}
}
}
};
logger.debug("Linking Batch load state for cluster");
logger.debug(JSON.stringify(loadStateRequest));
common.retryableUpdate(dynamoDB, loadStateRequest, function (err, data) {
if (err) {
logger.error("Error while attaching per-Cluster Load State");
failBatch(err, config, thisBatchId, s3Info, manifestInfo);
} else {
if (allOK === true) {
// close the batch as OK
closeBatch(null, config, thisBatchId, s3Info, manifestInfo, loadState);
} else {
// close the batch as failure
failBatch(loadState, config, thisBatchId, s3Info, manifestInfo);
}
}
});
});
}
};
/**
* Function which will run a postgres command with retries
*/
function runPgCommand(clusterInfo, client, command, retries, retryableErrorTraps, retryBackoffBaseMs, callback) {
var completed = false;
var retryCount = 0;
var lastError;
async.until(function (test_cb) {
if (retryCount > 1) {
logger.info("Retrying PG Query: attempt " + retryCount);
}
test_cb(null, completed || !retries || retryCount >= retries);
}, function (asyncCallback) {
logger.debug("Performing Database Command:");
logger.debug(command);
client.query(command, function (queryCommandErr, result) {
if (queryCommandErr) {
lastError = queryCommandErr;
// check all the included retryable error traps to see if
// this is a retryable error
var retryable = false;
if (retryableErrorTraps) {
retryableErrorTraps.map(function (retryableError) {
if (queryCommandErr.detail && queryCommandErr.detail.indexOf(retryableError) > -1) {
retryable = true;