-
Notifications
You must be signed in to change notification settings - Fork 2
/
init.js
251 lines (246 loc) · 10.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
/*
Copyright 2022 AlphaX Projects (alphax.pro)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var fs = require('fs');
var path = require('path');
var os = require('os');
var cluster = require('cluster');
var async = require('async');
var CliListener = require('./libs/cliListener.js');
var PoolWorker = require('./libs/poolWorker.js');
var PaymentProcessor = require('./libs/paymentProcessor.js');
var Website = require('./libs/server.js');
var algos = require('stratum-pool/lib/algoProperties.js');
const loggerFactory = require('./libs/logger.js');
const logger = loggerFactory.getLogger('init.js', 'system');
JSON.minify = JSON.minify || require("node-json-minify");
if (!fs.existsSync('config.json')) {
console.log('config.json file does not exist. Read the installation/setup instructions.');
return;
}
var portalConfig = JSON.parse(JSON.minify(fs.readFileSync("config.json", { encoding: 'utf8' })));
var poolConfigs;
try {
var posix = require('posix');
try {
posix.setrlimit('nofile', { soft: 100000, hard: 100000 });
} catch (e) {
if (cluster.isMaster) {
logger.warn('POSIX Connection Limit (Safe to ignore) Must be ran as root to increase resource limits');
}
}
finally {
var uid = parseInt(process.env.SUDO_UID);
if (uid) {
process.setuid(uid);
logger.debug('POSIX Connection Limit Raised to 100K concurrent connections, now running as non-root user: %s', process.getuid());
}
}
}
catch (e) {
if (cluster.isMaster) {
logger.debug('POSIX Connection Limit (Safe to ignore) POSIX module not installed and resource (connection) limit was not raised');
}
}
if (cluster.isWorker) {
switch (process.env.workerType) {
case 'pool':
new PoolWorker();
break;
case 'paymentProcessor':
new PaymentProcessor();
break;
case 'website':
new Website();
break;
}
return;
}
var buildPoolConfigs = function () {
var configs = {};
var configDir = 'pools/';
var poolConfigFiles = [];
fs.readdirSync(configDir).forEach(function (file) {
if (!fs.existsSync(configDir + file) || path.extname(configDir + file) !== '.json') return;
var poolOptions = JSON.parse(JSON.minify(fs.readFileSync(configDir + file, { encoding: 'utf8' })));
if (!poolOptions.enabled) return;
poolOptions.fileName = file;
poolConfigFiles.push(poolOptions);
});
for (var i = 0; i < poolConfigFiles.length; i++) {
var ports = Object.keys(poolConfigFiles[i].ports);
for (var f = 0; f < poolConfigFiles.length; f++) {
if (f === i) continue;
var portsF = Object.keys(poolConfigFiles[f].ports);
for (var g = 0; g < portsF.length; g++) {
if (ports.indexOf(portsF[g]) !== -1) {
logger.error(poolConfigFiles[f].fileName, 'Has same configured port of ' + portsF[g] + ' as ' + poolConfigFiles[i].fileName);
process.exit(1);
return;
}
}
if (poolConfigFiles[f].coin === poolConfigFiles[i].coin) {
logger.error(poolConfigFiles[f].fileName, 'Pool has same configured coin file coins/' + poolConfigFiles[f].coin + ' as ' + poolConfigFiles[i].fileName + ' pool');
process.exit(1);
return;
}
}
}
poolConfigFiles.forEach(function (poolOptions) {
poolOptions.coinFileName = poolOptions.coin;
var coinFilePath = 'coins/' + poolOptions.coinFileName;
if (!fs.existsSync(coinFilePath)) {
logger.error('[%s] could not find file %s ', poolOptions.coinFileName, coinFilePath);
return;
}
var coinProfile = JSON.parse(JSON.minify(fs.readFileSync(coinFilePath, { encoding: 'utf8' })));
poolOptions.coin = coinProfile;
poolOptions.coin.name = poolOptions.coin.name.toLowerCase();
if (poolOptions.coin.name in configs) {
logger.error('%s coins/' + poolOptions.coinFileName + ' has same configured coin name '
+ poolOptions.coin.name + ' as coins/'
+ configs[poolOptions.coin.name].coinFileName + ' used by pool config '
+ configs[poolOptions.coin.name].fileName, poolOptions.fileName);
process.exit(1);
return;
}
for (var option in portalConfig.defaultPoolConfigs) {
if (!(option in poolOptions)) {
var toCloneOption = portalConfig.defaultPoolConfigs[option];
var clonedOption = {};
if (toCloneOption.constructor === Object) {
Object.assign(clonedOption, toCloneOption);
} else {
clonedOption = toCloneOption;
}
poolOptions[option] = clonedOption;
}
}
configs[poolOptions.coin.name] = poolOptions;
if (!(coinProfile.algorithm in algos)) {
logger.error('[%s] Cannot run a pool for unsupported algorithm "' + coinProfile.algorithm + '"', coinProfile.name);
delete configs[poolOptions.coin.name];
}
});
return configs;
};
var spawnPoolWorkers = function () {
Object.keys(poolConfigs).forEach(function (coin) {
var p = poolConfigs[coin];
if (!Array.isArray(p.daemons) || p.daemons.length < 1) {
logger.error('[%s] No daemons configured so a pool cannot be started for this coin.', coin);
delete poolConfigs[coin];
}
});
if (Object.keys(poolConfigs).length === 0) {
logger.warn('PoolSpawner: No pool configs exists or are enabled in pool_configs folder. No pools spawned.');
return;
}
var serializedConfigs = JSON.stringify(poolConfigs);
var numForks = (function () {
if (!portalConfig.clustering || !portalConfig.clustering.enabled) {
return 1;
}
if (portalConfig.clustering.forks === 'auto') {
return os.cpus().length;
}
if (!portalConfig.clustering.forks || isNaN(portalConfig.clustering.forks)) {
return 1;
}
return portalConfig.clustering.forks;
})();
var poolWorkers = {};
var createPoolWorker = function (forkId) {
var worker = cluster.fork({
workerType: 'pool',
forkId: forkId,
pools: serializedConfigs,
portalConfig: JSON.stringify(portalConfig)
});
worker.forkId = forkId;
worker.type = 'pool';
poolWorkers[forkId] = worker;
worker.on('exit', function (code, signal) {
logger.error('PoolSpawner: Fork %s died, spawning replacement worker...', forkId);
setTimeout(function () {
createPoolWorker(forkId);
}, 2000);
}).on('message', function (msg) {
switch (msg.type) {
case 'banIP':
Object.keys(cluster.workers).forEach(function (id) {
if (cluster.workers[id].type === 'pool') {
cluster.workers[id].send({ type: 'banIP', ip: msg.ip });
}
});
break;
}
});
};
var i = 0;
var spawnInterval = setInterval(function () {
createPoolWorker(i);
i++;
if (i === numForks) {
clearInterval(spawnInterval);
logger.debug('Master', 'PoolSpawner', 'Spawned ' + Object.keys(poolConfigs).length + ' pool(s) on ' + numForks + ' thread(s)');
}
}, 250);
};
var startPaymentProcessor = function () {
var enabledForAny = false;
for (var pool in poolConfigs) {
var p = poolConfigs[pool];
var enabled = p.enabled && p.paymentProcessing && p.paymentProcessing.enabled;
if (enabled) {
enabledForAny = true;
break;
}
}
if (!enabledForAny)
return;
var worker = cluster.fork({
workerType: 'paymentProcessor',
pools: JSON.stringify(poolConfigs)
});
worker.on('exit', function (code, signal) {
logger.error('Master', 'Payment Processor', 'Payment processor died, spawning replacement...');
setTimeout(function () {
startPaymentProcessor(poolConfigs);
}, 2000);
});
};
var startWebsite = function () {
if (!portalConfig.website.enabled) return;
var worker = cluster.fork({
workerType: 'website',
pools: JSON.stringify(poolConfigs),
portalConfig: JSON.stringify(portalConfig)
});
worker.on('exit', function (code, signal) {
logger.error('Master', 'Website', 'Website process died, spawning replacement...');
setTimeout(function () {
startWebsite(portalConfig, poolConfigs);
}, 2000);
});
};
(function init() {
poolConfigs = buildPoolConfigs();
spawnPoolWorkers();
setTimeout(function () {
startPaymentProcessor();
startWebsite();
}, 2000);
})();