-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathZookeeperConfigManager.js
More file actions
513 lines (480 loc) · 17.1 KB
/
ZookeeperConfigManager.js
File metadata and controls
513 lines (480 loc) · 17.1 KB
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
const async = require('async');
const joi = require('joi');
const { EventEmitter } = require('events');
const zookeeper = require('node-zookeeper-client');
const ZookeeperManager = require('../../../lib/clients/ZookeeperManager');
const BaseConfigManager = require('./BaseConfigManager');
const safeJsonParse = require('../utils/safeJsonParse');
const constants = require('../constants');
const paramsJoi = joi.object({
zkClient: joi.object().optional(),
zkConfig: joi.object().when('zkClient', {
is: joi.exist(),
then: joi.optional(),
otherwise: joi.required(),
}),
zkPath: joi.string().when('zkClient', {
is: joi.exist(),
then: joi.optional(),
otherwise: joi.required(),
}),
zkConcurrency: joi.number().required(),
logger: joi.object().required(),
}).required();
/**
* @class ZookeeperConfigManager
*
* @classdesc Manages bucket notification configurations in zookeeper
*/
class ZookeeperConfigManager extends BaseConfigManager {
/**
* @constructor
* @param {Object} params - constructor params
* @param {Object} params.zkClient - zookeeper client
* @param {Logger} params.logger - logger object
*/
constructor(params) {
super();
joi.attempt(params, paramsJoi);
this._zkClient = params.zkClient;
this._zkPath = params.zkPath;
this._zkConfig = params.zkConfig;
this._zkConcurrency = params.zkConcurrency;
this.log = params.logger;
this._configs = new Map();
this._emitter = new EventEmitter();
this._setupEventListeners();
}
// https://github.com/alexguan/node-zookeeper-client/blob/master/lib/WatcherManager.js#L13-L39
// watchers should be reapplied only when their event is triggered, otherwise they will be duplicated
// and the lib will keep adding listeners
// (even if the functions are the same, they are js object so they don't match)
// warn early to catch leak more easily instead of waiting event emitter limit at 10 listeners.
_warnZkWatchersLeak(type, path) {
const watcherManager = this._zkClient?.client?.connectionManager?.watcherManager;
const watchers = watcherManager?.[`${type}Watchers`]?.[path];
if (!watchers) {
return;
}
const listeners = watchers.listenerCount('notification');
if (listeners > 0) {
process.emitWarning(`${type}Watchers[${path}] has already ${listeners} listeners`, {
code: 'ZkWatchersLeak',
});
}
}
_errorListener(error, listener) {
this.log.error('ZookeeperConfigManager.emitter.error', {
listener,
error,
});
return undefined;
}
_setConfigListener(bucket, config) {
this.log.debug('ZookeeperConfigManager.emitter.setConfig', {
event: 'setConfig',
bucket,
config,
});
this._setBucketNotifConfig(bucket, JSON.stringify(config), err => {
if (err) {
this._emitter.emit('error', err, 'setConfigListener');
}
return undefined;
});
}
_getConfigListener(bucket) {
this.log.debug('ZookeeperConfigManager.emitter.getConfig', {
event: 'getConfig',
bucket,
});
this._updateLocalStore([bucket]);
}
_listConfigsListener() {
this.log.debug('ZookeeperConfigManager.emitter.listConfigs', {
event: 'listConfigs',
});
this._listBucketsWithConfig((err, buckets) => {
if (err) {
this._emitter.emit('error', err, 'listConfigsListener');
return undefined;
}
const newBuckets = this._getNewBucketNodes(buckets);
this.log.debug('new bucket configs to be added to map', {
buckets: newBuckets,
});
if (newBuckets.length > 0) {
this._updateLocalStore(newBuckets);
}
return undefined;
});
}
_removeConfigListener(bucket) {
this.log.debug('ZookeeperConfigManager.emitter.removeConfig', {
event: 'removeConfig',
bucket,
});
this._removeBucketNotifConfigNode(bucket, err => {
if (err) {
this._emitter.emit('error', err, 'removeConfigListener');
}
return undefined;
});
}
_setupEventListeners() {
this._emitter
.on('error', error => this._errorListener(error))
.on('setConfig',
(bucket, config) => this._setConfigListener(bucket, config))
.on('getConfig', bucket => this._getConfigListener(bucket))
.on('listConfigs', () => this._listConfigsListener())
.on('removeConfig', bucket => this._removeConfigListener(bucket));
}
_callbackHandler(cb, err, result) {
if (cb && typeof cb === 'function') {
return cb(err, result);
}
return undefined;
}
_getBucketNodeZkPath(bucket) {
return `/${constants.zkConfigParentNode}/${bucket}`;
}
_getConfigDataFromBuffer(data, bucket) {
const { error, result } = safeJsonParse(data);
if (error) {
this.log.error('invalid config', { error, config: data, bucket });
return undefined;
}
return result;
}
_getBucketNotifConfig(bucket, cb) {
const method
= 'ZookeeperConfigManager._getBucketNotifConfig';
const zkPath = this._getBucketNodeZkPath(bucket);
this.log.debug('fetching bucket notification configuration', {
method,
bucket,
zkPath,
});
this._warnZkWatchersLeak('data', zkPath);
return this._zkClient.getData(zkPath, event => {
this.log.debug('zookeeper getData watcher triggered', {
zkPath,
method,
event,
bucket,
});
if (event.type === zookeeper.Event.NODE_DATA_CHANGED) {
this._emitter.emit('getConfig', bucket);
}
if (event.type === zookeeper.Event.NODE_DELETED) {
this.removeConfig(bucket, false);
}
}, (error, data) => {
if (error && error.name !== 'NO_NODE') {
const errMsg
= 'error fetching bucket notification configuration';
this.log.error(errMsg, {
method,
error,
});
return this._callbackHandler(cb, error);
}
if (data) {
return this._callbackHandler(cb, null, data);
}
// no configuration
return this._callbackHandler(cb);
});
}
_checkNodeExists(zkPath, cb) {
const method
= 'ZookeeperConfigManager._checkNodeExists';
return this._zkClient.exists(zkPath, (err, stat) => {
if (err) {
this.log.error('error checking node existence',
{ method, zkPath });
return this._callbackHandler(cb, err);
}
if (stat) {
this.log.debug('node exists', { method, zkPath });
return this._callbackHandler(cb, null, true);
}
this.log.debug('node does not exist', { method, zkPath });
return this._callbackHandler(cb, null, false);
});
}
_setBucketNotifConfig(bucket, data, cb) {
const method
= 'ZookeeperConfigManager._setBucketNotifConfig';
const zkPath = this._getBucketNodeZkPath(bucket);
this.log.debug('setting bucket notification configuration', {
method,
bucket,
zkPath,
});
return async.waterfall([
next => this._checkNodeExists(zkPath, next),
(exists, next) => {
if (!exists) {
return this._createBucketNotifConfigNode(bucket,
err => next(err, exists));
}
return next(null, exists);
},
(exists, next) => this._zkClient.setData(zkPath, Buffer.from(data), -1, err => next(err, exists)),
(exists, next) => {
if (!exists) {
// if znode is created, run getData to set a watcher on the bucket config
// in case another node becomes leader on the raft and modifies the config
// while the current process keeps running
return this._updateLocalStore([bucket], next);
}
return next();
},
], err => {
if (err) {
this.log.error('error saving config', { method, zkPath, data });
}
return this._callbackHandler(cb, err);
});
}
_checkConfigurationParentNode(cb) {
const method
= 'ZookeeperConfigManager._checkConfigurationParentNode';
const zkPath = `/${constants.zkConfigParentNode}`;
return async.waterfall([
next => this._checkNodeExists(zkPath, next),
(exists, next) => {
if (!exists) {
this.log.debug('parent configuration zookeeper node does ' +
'not exist', { method, zkPath });
return this._zkClient.mkdirp(zkPath, err => next(err));
}
this.log.debug('parent configuration zookeeper node exists',
{ method, zkPath });
return next();
},
], err => {
if (err) {
const errMsg
= 'error checking configuration zookeeper parent node';
this.log.error(errMsg, { method, zkPath, error: err.message });
return this._callbackHandler(cb, err);
}
this.log.debug('parent configuration zookeeper checked/added',
{ method, zkPath });
return this._callbackHandler(cb);
});
}
_createBucketNotifConfigNode(bucket, cb) {
const method
= 'ZookeeperConfigManager._createBucketNotifConfigNode';
const zkPath = this._getBucketNodeZkPath(bucket);
this.log.debug('creating bucket notification configuration node', {
method,
bucket,
zkPath,
});
return this._zkClient.mkdirp(zkPath, err => {
if (err) {
this.log.error('Could not pre-create path in zookeeper', {
method,
zkPath,
error: err,
});
return this._callbackHandler(cb, err);
}
return this._callbackHandler(cb);
});
}
_removeBucketNotifConfigNode(bucket, cb) {
const method
= 'ZookeeperConfigManager._removeBucketNotifConfigNode';
const zkPath = this._getBucketNodeZkPath(bucket);
this.log.debug('removing bucket notification configuration node', {
method,
bucket,
zkPath,
});
return this._zkClient.remove(zkPath, error => {
if (error && error.name !== 'NO_NODE') {
this.log.error('Could not remove zookeeper node', {
method,
zkPath,
error,
});
return this._callbackHandler(cb, error);
}
if (!error) {
const msg
= 'removed notification configuration zookeeper node';
this.log.debug(msg, {
method,
bucket,
});
}
return this._callbackHandler(cb);
});
}
_getNewBucketNodes(bucketsNodeList) {
if (Array.isArray(bucketsNodeList)) {
const bucketsFromMap = [...this._configs.keys()];
return bucketsNodeList.filter(b => !bucketsFromMap.includes(b));
}
return [];
}
_listBucketsWithConfig(cb) {
const method
= 'ZookeeperConfigManager._listBucketsWithConfig';
const zkPath = `/${constants.zkConfigParentNode}`;
this._warnZkWatchersLeak('child', zkPath);
this._zkClient.getChildren(zkPath, event => {
this.log.debug('zookeeper getChildren watcher triggered', {
zkPath,
method,
event,
});
if (event.type === zookeeper.Event.NODE_CHILDREN_CHANGED) {
this._emitter.emit('listConfigs');
}
}, (error, buckets) => {
if (error) {
const errMsg
= 'error listing buckets with configuration';
this.log.error(errMsg, {
zkPath,
method,
error,
});
this._callbackHandler(cb, error);
}
this.log.debug('list of buckets', {
zkPath,
method,
buckets,
});
this._callbackHandler(cb, null, buckets);
});
}
_updateLocalStore(buckets, cb) {
async.eachLimit(buckets, this._zkConcurrency, (bucket, next) => {
this._getBucketNotifConfig(bucket, (err, data) => {
if (err) {
return next(err);
}
const configObject = this._getConfigDataFromBuffer(data, bucket);
if (configObject) {
this._configs.set(bucket, configObject);
}
return next();
});
}, err => this._callbackHandler(cb, err));
}
/**
* Get bucket notification configuration
*
* @param {String} bucket - bucket
* @return {Object|undefined} - configuration if available or undefined
*/
getConfig(bucket) {
return this._configs.get(bucket);
}
/**
* Add/update bucket notification configuration
*
* @param {String} bucket - bucket
* @param {Object} config - bucket notification configuration
* @return {boolean} - true if set
*/
setConfig(bucket, config) {
try {
this.log.debug('set config', {
method: 'ZookeeperConfigManager.setConfig',
bucket,
config,
});
this._configs.set(bucket, config);
this._emitter.emit('setConfig', bucket, config);
return true;
} catch (err) {
const errMsg
= 'error setting bucket notification configuration';
this.log.error(errMsg, {
method: 'ZookeeperConfigManager.setConfig',
error: err.message,
bucket,
config,
});
return false;
}
}
/**
* Remove bucket notification configuration
*
* @param {String} bucket - bucket
* @param {boolean} [emitToZk = true] - whether to emit the event to zookeeper
* @return {boolean} - true if removed
*/
removeConfig(bucket, emitToZk = true) {
try {
this.log.debug('remove config', {
method: 'ZookeeperConfigManager.removeConfig',
bucket,
emitToZk,
});
this._configs.delete(bucket);
if (emitToZk) {
this._emitter.emit('removeConfig', bucket);
}
return true;
} catch (err) {
const errMsg
= 'error removing bucket notification configuration';
this.log.error(errMsg, {
method: 'ZookeeperConfigManager.removeConfig',
error: err,
bucket,
});
return false;
}
}
_setupZookeeper(done) {
if (this._zkClient) {
done();
return;
}
const zookeeperUrl =
`${this._zkConfig.connectionString}${this._zkPath}`;
this.log.info('opening zookeeper connection for reading ' +
'bucket notification configuration', {
zookeeperUrl,
method: 'ZookeeperConfigManager._setupZookeeper',
});
this._zkClient = new ZookeeperManager(zookeeperUrl, {
autoCreateNamespace: this._zkConfig.autoCreateNamespace,
retries: this._zkConfig.retries,
}, this.log);
this._zkClient.once('error', done);
this._zkClient.once('ready', () => {
// just in case there would be more 'error' events emitted
this._zkClient.removeAllListeners('error');
done();
});
}
/**
* Setup bucket notification configuration manager
*
* @param {function} [cb] - callback
* @return {undefined}
*/
setup(cb) {
async.waterfall([
next => this._setupZookeeper(next),
next => this._checkConfigurationParentNode(next),
(_, next) => this._listBucketsWithConfig(next),
(buckets, next) => this._updateLocalStore(buckets, next),
], cb);
}
}
module.exports = ZookeeperConfigManager;