forked from yfinkelstein/node-zookeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
electleader.js
61 lines (51 loc) · 1.63 KB
/
electleader.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
const { constants, isClientConnected } = require('./wrapper.js');
const notifier = require('./notifier.js');
const logger = require('./logger.js');
function emit(client, path) {
logger.log(`Elect leader: (${path}) ${client.client_id}`);
notifier.emit('leader');
}
function onData(client, path, rc, error, stat, data) {
const clientId = client.client_id;
if (data && data.toString() === clientId) {
emit(client, path);
}
}
async function watcher(client, path, checkFunc, retryFunc, rc) {
if (rc === -1) {
await checkFunc(client, path, retryFunc);
} else if (rc === 2) {
await retryFunc(client, path);
}
}
async function checkMaster(client, path, retryFunc) {
const watchFunc = watcher.bind(null, client, path, checkMaster, retryFunc);
try {
if (!isClientConnected()) {
throw new Error('is not connected');
}
const res = await client.w_get(path, watchFunc);
onData(client, path, res.rc, res.error, res.stat, res.data);
} catch (error) {
logger.error('checkMaster:', error.message);
}
}
async function runForLeader(client, path) {
const clientId = client.client_id;
try {
if (!isClientConnected()) {
throw new Error('is not connected');
}
await client.create(path, `${clientId}`, constants.ZOO_EPHEMERAL);
emit(client, path);
} catch (error) {
logger.error('runForLeader:', error.message);
await checkMaster(client, path, runForLeader);
}
}
async function electLeader(client, path) {
runForLeader(client, path);
}
module.exports = {
electLeader,
};