forked from eosrio/hyperion-history-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaster.js
425 lines (380 loc) · 13.6 KB
/
master.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
const {JsonRpc} = require('eosjs');
const fetch = require('node-fetch');
const cluster = require('cluster');
const fs = require('fs');
const redis = require('redis');
const pmx = require('pmx');
const {elasticsearchConnect} = require("./connections/elasticsearch");
const {
getLastIndexedBlock,
messageAllWorkers,
printWorkerMap,
getLastIndexedBlockFromRange,
onSaveAbi
} = require("./helpers/functions");
const {promisify} = require('util');
let client;
let cachedInitABI = null;
async function main() {
// Preview mode - prints only the proposed worker map
let preview = process.env.PREVIEW === 'true';
const rClient = redis.createClient();
const getAsync = promisify(rClient.get).bind(rClient);
client = await elasticsearchConnect();
const n_deserializers = parseInt(process.env.DESERIALIZERS, 10);
const n_ingestors_per_queue = parseInt(process.env.ES_INDEXERS_PER_QUEUE, 10);
const action_indexing_ratio = parseInt(process.env.ES_ACT_QUEUES, 10);
let max_readers = parseInt(process.env.READERS, 10);
if (process.env.DISABLE_READING === 'true') {
// Create a single reader to read the abi struct and quit.
max_readers = 1;
}
const activeReaders = [];
const eos_endpoint = process.env.NODEOS_HTTP;
const rpc = new JsonRpc(eos_endpoint, {fetch});
const queue_prefix = process.env.CHAIN;
const queue = queue_prefix + ':blocks';
const {index_queues} = require('./definitions/index-queues');
const indicesList = ["action", "block", "abi"];
const indexConfig = require('./definitions/mappings');
// Update index templates
for (const index of indicesList) {
const creation_status = await client['indices'].putTemplate({
name: `${queue_prefix}-${index}`,
body: indexConfig[index]
});
if (!creation_status['acknowledged']) {
console.log('Failed to create template', `${queue_prefix}-${index}`);
console.log(creation_status);
process.exit(1);
}
}
console.log('Index templates updated');
if (process.env.CREATE_INDICES !== 'false') {
// Create indices
let version = '';
if (process.env.CREATE_INDICES === 'true') {
version = 'v1';
} else {
version = process.env.CREATE_INDICES;
}
for (const index of indicesList) {
const new_index = `${queue_prefix}-${index}-${version}-000001`;
const exists = await client['indices'].exists({
index: new_index
});
if (!exists) {
console.log(`Creating index ${new_index}...`);
await client['indices'].create({
index: new_index
});
console.log(`Creating alias ${queue_prefix}-${index} >> ${new_index}`);
await client['indices'].putAlias({
index: new_index,
name: `${queue_prefix}-${index}`
});
} else {
console.log(`WARNING! Index ${new_index} already created!`);
}
}
}
// Check for indexes
for (const index of indicesList) {
const status = await client['indices'].existsAlias({
name: `${queue_prefix}-${index}`
});
if (!status) {
console.log('Alias ' + `${queue_prefix}-${index}` + ' not found! Aborting!');
process.exit(1);
}
}
const workerMap = [];
let worker_index = 0;
let pushedBlocks = 0;
let consumedBlocks = 0;
let indexedObjects = 0;
let deserializedActions = 0;
let lastProcessedBlockNum = 0;
let total_read = 0;
let total_blocks = 0;
let total_indexed_blocks = 0;
let total_actions = 0;
let log_interval = 5000;
let total_range = 0;
let allowShutdown = false;
let allowMoreReaders = true;
let maxBatchSize = parseInt(process.env.BATCH_SIZE, 10);
// Monitoring
setInterval(() => {
const _workers = Object.keys(cluster.workers).length;
const tScale = (log_interval / 1000);
total_read += pushedBlocks;
total_blocks += consumedBlocks;
total_actions += deserializedActions;
total_indexed_blocks += indexedObjects;
const log_msg = [
`Workers: ${_workers}`,
`Read: ${pushedBlocks / tScale} blocks/s`,
`Consume: ${consumedBlocks / tScale} blocks/s`,
`Deserialize: ${deserializedActions / tScale} actions/s`,
`Index: ${indexedObjects / tScale} docs/s`,
`${total_blocks}/${total_read}/${total_range}`
];
console.log(log_msg.join(' | '));
if (indexedObjects === 0 && deserializedActions === 0 && consumedBlocks === 0) {
allowShutdown = true;
// if (allowMoreReaders) {
// if (process.env.LIVE_READER !== 'true') {
// console.log('All workers finished. Ready to quit.');
// process.exit(1);
// }
// }
}
// reset counters
pushedBlocks = 0;
consumedBlocks = 0;
deserializedActions = 0;
indexedObjects = 0;
if (_workers === 0) {
console.log('FATAL ERROR - All Workers have stopped!');
process.exit(1);
}
}, log_interval);
const lastIndexedBlock = await getLastIndexedBlock(client);
// Start from the last indexed block
let starting_block = 1;
console.log('Last indexed block:', lastIndexedBlock);
// Fecth chain lib
const chain_data = await rpc.get_info();
let lib = chain_data['last_irreversible_block_num'];
if (lastIndexedBlock > 0) {
starting_block = lastIndexedBlock;
}
if (process.env.STOP_ON !== "0") {
lib = parseInt(process.env.STOP_ON, 10);
}
if (process.env.START_ON !== "0") {
starting_block = parseInt(process.env.START_ON, 10);
// Check last indexed block again
if (process.env.REWRITE !== 'true') {
const lastIndexedBlockOnRange = await getLastIndexedBlockFromRange(client, starting_block, lib);
if (lastIndexedBlockOnRange > starting_block) {
console.log('WARNING! Data present on target range!');
console.log('Changing initial block num. Use REWRITE = true to bypass.');
starting_block = lastIndexedBlockOnRange;
}
}
console.log('FIRST BLOCK: ' + starting_block);
console.log('LAST BLOCK: ' + lib);
}
total_range = lib - starting_block;
// Create first batch of parallel readers
let lastAssignedBlock = starting_block;
if (process.env.LIVE_ONLY === 'false') {
while (activeReaders.length < max_readers && lastAssignedBlock < lib) {
worker_index++;
const start = lastAssignedBlock;
let end = lastAssignedBlock + maxBatchSize;
if (end > lib) {
end = lib;
}
lastAssignedBlock += maxBatchSize;
const def = {
worker_id: worker_index,
worker_role: 'reader',
first_block: start,
last_block: end
};
activeReaders.push(def);
workerMap.push(def);
// console.log(`Launching new worker from ${start} to ${end}`);
}
}
// Setup Serial reader worker
if (process.env.LIVE_READER === 'true') {
const _lib = chain_data['last_irreversible_block_num'];
console.log(`Starting live reader at lib = ${_lib}`);
worker_index++;
workerMap.push({
worker_id: worker_index,
worker_role: 'continuous_reader',
worker_last_processed_block: _lib,
ws_router: ''
});
}
// Setup Deserialization Workers
for (let i = 0; i < n_deserializers; i++) {
for (let j = 0; j < process.env.DS_MULT; j++) {
worker_index++;
workerMap.push({
worker_queue: queue + ":" + (i + 1),
worker_id: worker_index,
worker_role: 'deserializer'
});
}
}
// Setup ES Ingestion Workers
index_queues.forEach((q) => {
let n = n_ingestors_per_queue;
if (q.type === 'abi') {
n = 1;
}
let qIdx = 0;
for (let i = 0; i < n; i++) {
let m = 1;
if (q.type === 'action') {
m = action_indexing_ratio;
}
for (let j = 0; j < m; j++) {
worker_index++;
workerMap.push({
worker_id: worker_index,
worker_role: 'ingestor',
type: q.type,
queue: q.name + ":" + (qIdx + 1)
});
qIdx++;
}
}
});
// Setup ws router
if (process.env.ENABLE_STREAMING) {
worker_index++;
workerMap.push({
worker_id: worker_index,
worker_role: 'router'
});
}
// Quit App if on preview mode
if (preview) {
printWorkerMap(workerMap);
process.exit(1);
}
// Launch all workers
workerMap.forEach((conf) => {
cluster.fork(conf);
});
const dsErrorsLog = 'logs/' + process.env.CHAIN + "_ds_err_" + starting_block + "_" + lib + ".txt";
if (fs.existsSync(dsErrorsLog)) {
fs.unlinkSync(dsErrorsLog);
}
const ds_errors = fs.createWriteStream(dsErrorsLog, {flags: 'a'});
const cachedMap = await getAsync(process.env.CHAIN + ":" + 'abi_cache');
let abiCacheMap;
if (cachedMap) {
abiCacheMap = JSON.parse(cachedMap);
console.log(`Found ${Object.keys(abiCacheMap).length} entries in the local ABI cache`)
} else {
abiCacheMap = {};
}
setInterval(() => {
rClient.set(process.env.CHAIN + ":" + 'abi_cache', JSON.stringify(abiCacheMap));
}, 10000);
// Worker event listener
const workerHandler = (msg) => {
switch (msg.event) {
case 'init_abi': {
if (!cachedInitABI) {
cachedInitABI = msg.data;
setTimeout(() => {
messageAllWorkers(cluster, {
event: 'initialize_abi',
data: msg.data
});
}, 1000);
}
break;
}
case 'router_ready': {
messageAllWorkers(cluster, {
event: 'connect_ws'
});
break;
}
case 'save_abi': {
onSaveAbi(msg.data, abiCacheMap, rClient);
break;
}
case 'completed': {
const idx = activeReaders.findIndex(w => w.worker_id.toString() === msg.id);
activeReaders.splice(idx, 1);
if (activeReaders.length < max_readers && lastAssignedBlock < lib && allowMoreReaders) {
// Deploy next worker
worker_index++;
const start = lastAssignedBlock;
let end = lastAssignedBlock + maxBatchSize;
if (end > lib) {
end = lib;
}
lastAssignedBlock += maxBatchSize;
const def = {
worker_id: worker_index,
worker_role: 'reader',
first_block: start,
last_block: end,
init_abi: cachedInitABI
};
activeReaders.push(def);
workerMap.push(def);
setTimeout(() => {
// console.log(`Launching new worker from ${start} to ${end}`);
cluster.fork(def).on('message', workerHandler);
}, 100);
}
break;
}
case 'add_index': {
indexedObjects += msg.size;
break;
}
case 'ds_action': {
deserializedActions++;
break;
}
case 'ds_error': {
ds_errors.write(msg.gs + '\n');
break;
}
case 'read_block': {
pushedBlocks++;
break;
}
case 'consumed_block': {
consumedBlocks++;
if (msg.block_num > lastProcessedBlockNum) {
lastProcessedBlockNum = msg.block_num;
}
break;
}
}
};
// Attach handlers
for (const c in cluster.workers) {
if (cluster.workers.hasOwnProperty(c)) {
const self = cluster.workers[c];
self.on('message', (msg) => {
workerHandler(msg, self);
});
}
}
// Catch dead workers
cluster.on('exit', (worker, code) => {
// console.log(`Worker ${worker.id}, pid: ${worker.process.pid} finished with code ${code}`);
});
pmx.action('stop', (reply) => {
allowMoreReaders = false;
console.info('Stop signal received. Shutting down readers immediately!');
console.log('Waiting for queues...');
reply({
ack: true
});
setInterval(() => {
if (allowShutdown) {
console.log('Shutting down master...');
rClient.set('abi_cache', JSON.stringify(abiCacheMap));
process.exit(1);
}
}, 500);
});
}
module.exports = {main};