/
IngestionReader.js
495 lines (456 loc) · 18.1 KB
/
IngestionReader.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
const async = require('async');
const { errors } = require('arsenal');
const VID_SEP = require('arsenal').versioning.VersioningConstants
.VersionId.Separator;
const IngestionProducer = require('./IngestionProducer');
const LogReader = require('./LogReader');
const { decryptLocationSecret } = require('../management/index');
const {
metricsExtension,
metricsTypeQueued
} = require('../../extensions/ingestion/constants');
function _isVersionedLogKey(key) {
return key.split(VID_SEP)[1] !== undefined;
}
class IngestionReader extends LogReader {
constructor(params) {
const { zkClient, ingestionConfig, kafkaConfig, bucketdConfig, qpConfig,
logger, extensions, producer, metricsProducer, s3Config } = params;
super({ zkClient, kafkaConfig, logConsumer: {}, logId: '',
logger, extensions, metricsProducer });
this._ingestionConfig = ingestionConfig;
this.qpConfig = qpConfig;
this.s3Config = s3Config;
this.bucketdConfig = bucketdConfig;
this.logger = logger;
this._producer = producer;
// source ingestion bucket
this.bucket = bucketdConfig.bucket;
// zenko bucket to ingest to
this._targetZenkoBucket = bucketdConfig.name;
const ingestionPath = this._ingestionConfig.zookeeperPath;
this.zkBasePath = `${ingestionPath}/${this._targetZenkoBucket}`;
this.bucketInitPath = `${this.zkBasePath}/init`;
this.pathToLogOffset = null;
this.raftId = null;
this.logId = null;
this._batchInProgress = false;
this._shouldProcessInitState = true;
}
/**
* static method to return a list of ingestion init nodes used in zookeeper
* @return {Array} - array of ingestion init nodes as strings
*/
static getInitIngestionNodes() {
return ['isStatusComplete', 'versionMarker', 'keyMarker'];
}
_setupIngestionProducer(cb) {
const encryptedKey = this.bucketdConfig.auth.secretKey;
return decryptLocationSecret(encryptedKey, this.logger,
(err, decryptedKey) => {
if (err) {
this.logger.error('failed to decrypt source secret key');
return cb(err);
}
// only save decrypted key within IngestionProducer instance
const updatedAuth = Object.assign({},
this.bucketdConfig.auth, { secretKey: decryptedKey });
const bucketdConfig = Object.assign({},
this.bucketdConfig, { auth: updatedAuth });
this._iProducer = new IngestionProducer(bucketdConfig,
this.qpConfig, this.s3Config);
return cb();
});
}
setup(done) {
async.series([
next => this._setupIngestionProducer(next),
next => this._iProducer.validateSourceSetup(this.bucket,
this.logger, next),
next => this._iProducer.getRaftId(this.bucket, (err, data) => {
if (err) {
return next(err);
}
this.raftId = data;
this.logId = `raft_${this.raftId}`;
this.pathToLogOffset =
`${this.zkBasePath}/logState/${this.logId}/logOffset`;
return super.setup(next);
}),
], done);
}
/**
* Get the init (snapshot) state for this given IngestionReader
* @param {Logger.newRequestLogger} logger - request logger object
* @param {function} done - callback(error, object)
* where object.versionMarker is the NextVersionIdMarker
* where object.keyMarker is the NextKeyMarker
* @return {undefined}
*/
_readInitState(logger, done) {
const initPathNodes = IngestionReader.getInitIngestionNodes();
if (this._shouldProcessInitState === false) {
return done(null, {
isStatusComplete: true,
});
}
return async.map(initPathNodes, (pathNode, cb) => {
const path = `${this.bucketInitPath}/${pathNode}`;
return this.zkClient.getData(path, (err, data) => {
if (err) {
if (err.name !== 'NO_NODE') {
logger.error(
'Could not fetch ingestion init state',
{ method: 'IngestionReader._readInitState',
zkPath: path,
error: err });
return cb(err);
}
return this.zkClient.mkdirp(path, err => {
if (err) {
logger.error(
'Could not pre-create path in zookeeper',
{ method: 'IngestionReader._readInitState',
zkPath: path,
error: err });
return cb(err);
}
return cb();
});
}
const d = data && data.toString();
logger.debug('fetched ingestion init state node', {
method: 'IngestionReader._readInitState',
zkPath: path,
data: d,
});
return cb(null, d);
});
}, (err, data) => {
if (err) {
return done(err);
}
const [isStatusComplete, versionMarker, keyMarker] = data;
return done(null, {
isStatusComplete: isStatusComplete === 'true',
versionMarker,
keyMarker
});
});
}
/**
* Set the init (snapshot) state for this given IngestionReader
* @param {object} initState - initState (snapshot) for ingestion
* @param {boolean} initState.isStatusComplete - true/false
* @param {string} [initState.versionMarker] - NextVersionIdMarker
* @param {string} [initState.keyMarker] - NextKeyMarker
* @param {Logger.newRequestLogger} logger - request logger object
* @param {function} done - callback(error)
* @return {undefined}
*/
_writeInitState(initState, logger, done) {
// initState is set by each request of processLogEntries. If undefined,
// we did not go through snapshot phase
if (!initState) {
return process.nextTick(done);
}
const initPathNodes = IngestionReader.getInitIngestionNodes();
return async.each(initPathNodes, (pathNode, cb) => {
const path = `${this.bucketInitPath}/${pathNode}`;
const data = (initState[pathNode] || 'null').toString();
return this.zkClient.setData(path, Buffer.from(data), err => {
if (err) {
logger.error('error saving init state', {
method: 'IngestionReader._writeInitState',
zkPath: path,
error: err,
});
return cb(err);
}
logger.debug('saved init state', {
method: 'IngestionReader._writeInitState',
zkPath: path,
});
if (pathNode === 'isStatusComplete' && data[pathNode]) {
this._shouldProcessInitState = false;
}
return cb();
});
}, done);
}
processLogEntries(params, done) {
this._batchInProgress = true;
super.processLogEntries(params, err => {
this._batchInProgress = false;
return done(err);
});
}
/* eslint-disable no-param-reassign */
_processReadRecords(params, batchState, done) {
const { logger } = batchState;
const readOptions = {};
if (this.logOffset !== undefined) {
readOptions.startSeq = this.logOffset;
}
if (params && params.maxRead !== undefined) {
readOptions.limit = params.maxRead;
}
logger.debug('reading records', { readOptions });
return async.waterfall([
next => this._readInitState(logger, next),
(state, next) => {
if (state.isStatusComplete) {
return this._iProducer.getRaftLog(this.raftId,
readOptions.startSeq, readOptions.limit, false,
(err, data) => {
if (err) {
logger.error('Error retrieving logs', { err,
raftId: this.raftId, method:
'IngestionReader._processReadRecords' });
return next(err);
}
logger.debug('readRecords got raft logs', {
method: 'IngestionReader._processReadRecords',
params });
batchState.logRes = data;
return next();
});
}
return this._iProducer.snapshot(this.bucket, state,
(err, res) => {
if (err) {
logger.error('error generating snapshot for ' +
'ingestion', {
error: err,
method: 'IngestionReader._processReadRecords',
});
return next(err);
}
if (!res) {
logger.error('failed to get metadata logs', {
method: 'IngestionReader._processReadRecords',
});
return next(errors.InternalError);
}
batchState.logRes = { info: { start: 1 }, log: res.logRes };
batchState.initState = res.initState;
return next();
});
},
], done);
}
_processLogEntry(batchState, record, entry) {
// NOTE: Using zenkoName because should be unique to other entries.
// for a "del", entry.value will not exist but we still need to
// pass through the event
// for a bucket metadata entry from s3Connector, there will be no
// entry.key but there will be an entry.type and we
// need to pass this through
if (entry.key === undefined && entry.type === undefined) {
return;
}
if (!record.db) {
this._extensions.forEach(ext => ext.filter({
type: entry.type,
bucket: entry.bucket,
key: entry.key,
value: entry.value,
}));
} else {
let key;
let db;
if (record.db === 'users..bucket') {
const keySplit = entry.key.split('..|..');
key = `${keySplit[0]}..|..${this._targetZenkoBucket}`;
} else if (record.db === 'metastore') {
const keySplit = entry.key.split('/');
key = `${keySplit[0]}/${this._targetZenkoBucket}`;
} else {
if (record.db === entry.key) {
key = this._targetZenkoBucket;
}
db = this._targetZenkoBucket;
}
if (db === undefined) {
db = record.db;
}
if (key === undefined) {
key = entry.key;
}
this._extensions.forEach(ext => ext.filter({
type: entry.type,
bucket: db,
key,
value: entry.value,
}));
}
}
_processPrepareEntries(batchState, done) {
const {
entriesToPublish, logRes, logStats, logger, initState,
} = batchState;
this._setEntryBatch(entriesToPublish);
// if logRes.log is empty (empty listObjectVersions listing), skip
if (!logRes.log) {
return done();
}
// if initState, then these current log entries came from a snapshot
if (initState) {
logRes.log.forEach(entry => {
// for snapshot phase, only versioned keys are separate records
// and non-versioned keys are only considered entries.
// Doing this for logging only. This won't affect offset in zk
if (_isVersionedLogKey(entry.key)) {
logStats.nbLogRecordsRead += 1;
}
logStats.nbLogEntriesRead += 1;
this._processLogEntry(batchState, entry, entry);
});
return done();
}
if (logRes.info.start === null || logRes.log === null) {
return done(null);
}
this._setEntryBatch(entriesToPublish);
logRes.log.on('data', record => {
logStats.nbLogRecordsRead += 1;
record.entries.forEach(entry => {
logStats.nbLogEntriesRead += 1;
if (record.db === this.bucket) {
this._processLogEntry(batchState, record, entry);
}
});
});
logRes.log.on('error', err => {
logger.error('error fetching entries from log',
{ method: 'LogReader._processPrepareEntries',
error: err });
return done(err);
});
logRes.log.on('end', () => {
logger.debug('ending record stream');
return done();
});
return undefined;
}
_processPublishEntries(batchState, done) {
const {
entriesToPublish, logRes, logStats, logger, initState,
} = batchState;
// initState.cseq is only fetched at very start of snapshot phase.
// We want to save cseq right before we started snapshot
// phase to guarantee we don't miss any new entries while snapshot
// is in process
if (initState && initState.cseq) {
batchState.nextLogOffset = initState.cseq;
}
// only set this after snapshot phase is done.
// `initState` is only set during snapshot phase.
if (!initState) {
batchState.nextLogOffset =
logRes.info.start + logStats.nbLogRecordsRead;
}
return async.each(Object.keys(entriesToPublish), (topic, done) => {
const topicEntries = entriesToPublish[topic];
if (topicEntries.length === 0) {
return done();
}
return this._producer.send(topicEntries, err => {
if (err) {
logger.error('error publishing entries from log to topic', {
method: 'LogReader._processPublishEntries',
topic,
entryCount: topicEntries.length,
error: err,
});
return done(err);
}
logger.debug('entries published successfully to topic',
{ method: 'LogReader._processPublishEntries',
topic, entryCount: topicEntries.length });
batchState.publishedEntries[topic] = topicEntries;
return done();
});
}, err => {
if (err) {
return done(err);
}
this._publishMetrics();
return done();
});
}
_processSaveLogOffset(batchState, done) {
const { initState, logger } = batchState;
async.series([
next => this._writeInitState(initState, logger, next),
next => {
if (batchState.nextLogOffset !== undefined &&
batchState.nextLogOffset !== this.logOffset) {
if (batchState.nextLogOffset > this.logOffset) {
this.logOffset = batchState.nextLogOffset;
}
return this._writeLogOffset(logger, done);
}
return process.nextTick(next);
},
], done);
}
_publishMetrics() {
// Ingestion extensions is a single IngestionQueuePopulatorExt
const extension = this._extensions[0];
const location = this.getLocationConstraint();
const metric = extension.getAndResetMetrics(this._targetZenkoBucket);
if (metric && metric.ops > 0) {
const value = { [location]: metric };
this._mProducer.publishMetrics(value, metricsTypeQueued,
metricsExtension, () => {});
}
}
/**
* Bucket configs have user editable fields: credentials, endpoint
* This method will detect if a change has occurred. If a change occurred,
* update relevant instance variables
* @param {Object} sourceInfo - latest bucketdConfig information
* @return {Boolean} true if a change occurred
*/
refresh(sourceInfo) {
const bucketdConfig = this._getEditableFields(this.bucketdConfig);
const latestBucketdConfig = this._getEditableFields(sourceInfo);
const updated = bucketdConfig !== latestBucketdConfig;
if (updated) {
// update instance variables
this.bucketdConfig = sourceInfo;
return true;
}
return false;
}
/**
* Helper method to fetch an bucketdConfig object of only editable fields
* following a specific format.
* Editable fields: auth.accessKey, auth.secretKey, host, port, https
* @param {Object} info - bucketdConfig information
* @return {String} editableInfo as a string
*/
_getEditableFields(info) {
return JSON.stringify({
accessKey: info.auth && info.auth.accessKey,
secretKey: info.auth && info.auth.secretKey,
host: info.host,
port: info.port,
https: info.https,
});
}
getLogInfo() {
return { raftId: this.raftId };
}
getTargetZenkoBucketName() {
return this._targetZenkoBucket;
}
getLocationConstraint() {
return this.bucketdConfig.locationConstraint;
}
isBatchInProgress() {
return this._batchInProgress;
}
}
module.exports = IngestionReader;