-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinit.js
299 lines (261 loc) · 13.2 KB
/
init.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
const os = require('os');
const cluster = require('cluster');
const posix = require('posix');
const appwrite = require('appwrite');
const pino = require('pino');
const prettifier = require('pino-pretty');
const chalk = require('chalk');
const config = require('config');
const algoProperties = require('./lib/algoproperties');
const poolWorker = require('./lib/poolworker');
const cliListener = require('./lib/clilistener');
const appwriteConfig = config.get('appwrite');
const loggingConfig = config.get('logging');
const coinConfigs = parseCoinConfigs();
const poolWorkers = {};
const parseCoinConfigs = () => {
const coins = config.get('coins');
const coinArray = Array.from(Object.keys(coins));
const count = coins.length;
for (var leftIndex = 0; leftIndex < count; leftIndex++) {
const name = coinArray[ leftIndex ];
const leftCoin = coins[ name ];
const algo = leftCoin.algo;
const leftPorts = Object.keys(leftCoin.ports);
// Making sure no coin uses any of same ports as another
for (
var rightIndex = leftIndex + 1; rightIndex < count; rightIndex++
) {
const rightCoin = coins[
coinArray[ rightIndex ]
];
const rightPorts = Object.keys(rightConfig.ports);
const duplicatePort = leftPorts.find((port) => {
rightPorts.hasOwnProperty(port);
});
if (duplicatePort) {
logger.error(
'Coin ' + leftCoin.name
+ ' has same configured port, '
+ duplicatePort
+ ', as '
+ rightCoin.name
);
process.exit(1);
}
}
if (!(algo in algoProperties)) {
delete coins[ name ];
logger.error(`Algorithm ${ algo } isn’t supported`);
}
}
return coins;
};
const spawnPoolWorkers = () => {
const coins = Object.keys(coinConfigs);
if (coins.length) {
const forkCount = (() => {
const clustering = config.get('clustering');
let count = 1;
if (clustering && clustering.isEnabled) {
const forkCount = clustering.forkCount;
if (forkCount) {
if (!isNaN(forkCount)) {
count = forkCount;
} else if (forkCount == 'auto') {
count = os.cpus().length;
}
}
}
return count;
})();
var index = 0;
coins.forEach((coin) => {
const daemons = coinConfigs[ coin ].daemons;
if (!Array.isArray(daemons) || !daemons.length) {
delete coinConfigs[ coin ];
logger.error(
'Coin ' + coin
+ ' has no daemons configured,'
+ ' so corresponding pool worker can’t be started'
);
}
});
// TODO: Move interval to config
const spawnInterval = setInterval(() => {
spawnPoolWorker(index);
index++;
if (index == forkCount) {
clearInterval(spawnInterval);
logger.info(
'Started ' + coins.length
+ ' pool worker(s) in '
+ forkCount
+ ' thread(s)'
);
}
}, 250);
} else {
logger.error(
'No pool workers started' + ' because no coin configs exist'
+ ' or are enabled'
);
}
};
const spawnPoolWorker = (forkId) => {
const pid = process.pid;
const worker = cluster.fork({
workerType: 'pool',
forkId: forkId,
pid: pid,
coins: JSON.stringify(coinConfigs)
});
worker.type = 'pool';
worker.forkId = forkId;
poolWorkers[ forkId ] = worker;
worker.on('message', (message) => {
switch (message.type) {
case 'ipBan':
const clusterWorkers = cluster.workers;
Object.keys(clusterWorkers).forEach((id) => {
const clusterWorker = clusterWorkers[ id ];
if (clusterWorker.type == 'pool') {
clusterWorker.send({ type: 'ipBan', ip: message.ip });
}
});
break;
case 'minerCount':
minerCount += message.count;
workerCount++;
break;
case 'axm:transport:ipc':
case 'axm:option:configuration':
case 'axm:option:setPID':
case 'axm:monitor':
case 'axm:action':
case 'axm:reply':
case 'application:dependencies':
// Ignoring PM2 probes
break;
default:
if (
Object.keys(message).length == 1 && !('node_version' in message)
) {
logger.warn(
`Unrecognized message: ${ JSON.stringify(message) }`
);
}
break;
}
}).on('exit', () => {
logger.error(
`Pool worker in thread ${ forkId } died; starting replacement`
);
// TODO: Move interval to config
setTimeout(() => { spawnPoolWorker(forkId); }, 2000);
});
logger.info(
`Started pool worker from thread ${ forkId } and process ${ pid }`
);
};
const startCliListener = () => {
new cliListener(config.get('cli').port).on(
'command', (command, params, options, reply) => {
const coin = params[0];
const workers = cluster.workers;
switch (command) {
case 'blocknotify':
Object.keys(workers).forEach((id) => {
workers[ id ].send({
type: 'blocknotify', coin, hash: params[1]
});
});
reply(`Notified pool workers for coin ${ coin }`);
break;
case 'reloadpool':
Object.keys(workers).forEach((id) => {
workers[ id ].send({ type: 'reloadpool', coin });
});
reply(`Reloaded pool worker for coin ${ coin }`);
break;
default:
reply(`Unrecognized command, ${ command }`);
break;
}
}
).on(
'log', (message) => {
logger.info(message);
}
).start();
};
let minerCount = 0;
let workerCount = 0;
JSON.minify = JSON.minify || require('node-json-minify');
global.logger = pino({
level: loggingConfig.level,
redact: {
paths: [ 'pid', 'hostname' ],
remove: true
},
timestamp: pino.stdTimeFunctions.isoTime,
prettyPrint: {
levelFirst: true
},
prettifier: prettifier,
colorize: loggingConfig.shouldColorize && chalk.supportsColor
});
if (process.argv.length != 2) {
console.error('Usage: node init.js');
process.exit(1);
}
try {
global.appwrite = new appwrite.Client();
global.appwrite
.setEndpoint(appwriteConfig.endpoint)
.setProject(appwriteConfig.id)
.setKey(appwriteConfig.key);
} catch (error) {
logger.error(`Error connecting to Appwrite: ${ JSON.stringify(error) }`);
process.exit(1);
}
// Trying to give process ability to handle 100K concurrent connections
try {
posix.setrlimit('nofile', { soft: 100000, hard: 100000 });
} catch (error) {
if (cluster.isPrimary) logger.warn('Pool must be run as root to increase resource limits');
} finally {
// Finding which user sudoed through environment variable
const uid = parseInt(process.env.SUDO_UID);
// Setting process’s UID to that user’s
if (uid) {
process.setuid(uid);
logger.info(
'Process limit raised to 100K concurrent connections;' + ' now running as non-root user '
+ process.getuid()
);
}
}
// Broadcasting from primary process to pool workers
if (cluster.isPrimary) {
spawnPoolWorkers();
startCliListener();
// TODO: Move interval to config
setInterval(() => {
if (poolWorkers) {
minerCount = 0;
workerCount = 0;
for (var forkId in poolWorkers) poolWorkers[ forkId ].send({ type: 'minerCount' });
logger.info(`Running ${ Object.keys(poolWorkers).length } pool workers(s)`);
}
}, 15000);
setInterval(() => {
if (poolWorkers) {
for (var forkId in poolWorkers) poolWorkers[ forkId ].send({ type: 'metricsSample' });
}
}, config.get('pool').metricsSampleInterval * 1000);
} else { // Listening for primary from worker
if (process.env.workerType == 'pool') { // In forked worker
new poolWorker(logger);
}
}