forked from yfinkelstein/node-zookeeper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
electleader.js
55 lines (45 loc) · 1.41 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
const { constants } = require('./wrapper');
const notifier = require('./notifier');
const logger = require('./logger');
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 {
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 {
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,
};