forked from Snipa22/nodejs-pool
-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathinit.js
More file actions
249 lines (227 loc) · 8.82 KB
/
init.js
File metadata and controls
249 lines (227 loc) · 8.82 KB
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
"use strict";
let mysql = require("promise-mysql");
let fs = require("fs");
let cluster = require("cluster");
let argv = require('./parse_args')(process.argv.slice(2));
let config = fs.readFileSync("./config.json");
let coinConfig = fs.readFileSync("./coinConfig.json");
let protobuf = require('protocol-buffers');
let path = require('path');
global.support = require("./lib/common/support.js")();
global.config = JSON.parse(config);
global.mysql = mysql.createPool(global.config.mysql);
global.protos = protobuf(fs.readFileSync('./lib/common/data.proto'));
global.argv = argv;
let comms;
let coinInc;
let activeModule = null;
const { formatLogEvent } = require("./lib/common/logging.js");
function logEvent(label, fields) { console.log(formatLogEvent(label, fields)); }
function logStartup(kind, name) {
console.log("=== STARTING " + kind.toUpperCase() + ": " + name + " ===");
}
function isPrimaryProcess(clusterApi) {
if (!clusterApi) return false;
if (typeof clusterApi.isPrimary === "boolean") return clusterApi.isPrimary;
return clusterApi.isMaster === true;
}
function hasClusterWorkers(clusterApi) {
if (!clusterApi || !clusterApi.workers) return false;
return Object.keys(clusterApi.workers).some(function hasWorker(id) {
return !!clusterApi.workers[id];
});
}
function shutdownErrorMessage(error) {
return error && error.stack ? error.stack : String(error);
}
function stopActiveModule() {
if (!activeModule || typeof activeModule.stop !== "function") return Promise.resolve();
return Promise.resolve(activeModule.stop());
}
function disconnectCluster() {
return new Promise(function onDisconnect(resolve) {
if (!isPrimaryProcess(cluster) || !hasClusterWorkers(cluster) || typeof cluster.disconnect !== "function") {
resolve();
return;
}
try {
cluster.disconnect(resolve);
} catch (_error) {
resolve();
}
});
}
function closeMysql() {
if (!global.mysql || typeof global.mysql.end !== "function") return Promise.resolve();
return Promise.resolve(global.mysql.end());
}
function syncDatabaseEnv() {
return new Promise(function onSync(resolve) {
const env = global.database && global.database.env;
if (!env || typeof env.sync !== "function") {
resolve();
return;
}
try {
env.sync(resolve);
} catch (_error) {
resolve();
}
});
}
function closeDatabaseEnv() {
const env = global.database && global.database.env;
if (!env || typeof env.close !== "function") return;
env.close();
}
function installGracefulShutdown(name) {
let shuttingDown = false;
const kind = argv.hasOwnProperty('module') ? 'module' : 'tool';
async function handleSignal(signal) {
if (shuttingDown) return;
shuttingDown = true;
logEvent("Shutdown", { kind, name, signal, status: "stopping" });
async function runStep(label, fn) {
try {
await fn();
} catch (error) {
console.error(label + " failed: " + shutdownErrorMessage(error));
}
}
await runStep("Module shutdown", stopActiveModule);
await runStep("Cluster disconnect", disconnectCluster);
await runStep("MySQL shutdown", closeMysql);
await runStep("LMDB sync", syncDatabaseEnv);
await runStep("LMDB close", closeDatabaseEnv);
logEvent("Shutdown", { kind, name, signal, status: "stopped" });
process.exit(0);
}
["SIGINT", "SIGTERM"].forEach(function registerSignal(signal) {
process.on(signal, function onSignal() {
handleSignal(signal).catch(function onUnhandled(error) {
console.error("Graceful shutdown failed for " + name + ": " + shutdownErrorMessage(error));
process.exit(1);
});
});
});
process.on("disconnect", function onDisconnect() {
handleSignal("disconnect").catch(function onUnhandled(error) {
console.error("Graceful shutdown failed for " + name + ": " + shutdownErrorMessage(error));
process.exit(1);
});
});
}
function loadPoolModule() {
global.config.ports = [];
return global.mysql.query("SELECT * FROM port_config").then(function(rows){
rows.forEach(function(row){
row.hidden = row.hidden === 1;
row.ssl = row.ssl === 1;
global.config.ports.push({
port: row.poolPort,
difficulty: row.difficulty,
desc: row.portDesc,
portType: row.portType,
hidden: row.hidden,
ssl: row.ssl
});
});
}).then(function(){
return require('./lib/pool.js');
});
}
function loadOptionalLib2Module(relativePath, moduleName) {
const absolutePath = path.join(__dirname, relativePath);
if (!fs.existsSync(absolutePath)) {
throw new Error("Optional module '" + moduleName + "' requires lib2 at " + absolutePath);
}
return require(relativePath);
}
const moduleLoaders = {
pool: loadPoolModule,
block_manager: function () {
const runtime = require('./lib/block_manager.js').createBlockManagerRuntime();
runtime.start();
return runtime;
},
altblock_manager: function () { return loadOptionalLib2Module('./lib2/altblock_manager.js', 'altblock_manager'); },
altblockExchange: function () { return loadOptionalLib2Module('./lib2/altblockExchange.js', 'altblockExchange'); },
payments: function () { return require('./lib/payments.js'); },
api: function () { return require('./lib/api.js'); },
remote_share: function () { return require('./lib/remote_share.js'); },
worker: function () { return require('./lib/worker.js'); },
pool_stats: function () { return require('./lib/pool_stats.js'); },
long_runner: function () { return require('./lib/long_runner.js'); }
};
// Config Table Layout
// <module>.<item>
global.mysql.query("SELECT * FROM config").then(function (rows) {
rows.forEach(function (row){
if (!global.config.hasOwnProperty(row.module)){
global.config[row.module] = {};
}
if (global.config[row.module].hasOwnProperty(row.item)){
return;
}
switch(row.item_type){
case 'int':
global.config[row.module][row.item] = parseInt(row.item_value);
break;
case 'bool':
global.config[row.module][row.item] = (row.item_value === "true");
break;
case 'string':
global.config[row.module][row.item] = row.item_value;
break;
case 'float':
global.config[row.module][row.item] = parseFloat(row.item_value);
break;
}
});
}).then(function(){
global.config['coin'] = JSON.parse(coinConfig)[global.config.coin];
coinInc = require(global.config.coin.funcFile);
global.coinFuncs = new coinInc();
if (argv.module === 'pool'){
comms = require('./lib/pool/remote_uplink');
} else {
comms = require('./lib/common/local_comms');
}
global.database = new comms();
global.database.initEnv();
installGracefulShutdown(argv.hasOwnProperty('module') ? argv.module : (argv.hasOwnProperty('tool') ? argv.tool : 'process'));
global.coinFuncs.blockedAddresses.push(global.config.pool.address);
global.coinFuncs.blockedAddresses.push(global.config.payout.feeAddress);
if (argv.hasOwnProperty('tool') && fs.existsSync('./tools/'+argv.tool+'.js')) {
logStartup("tool", argv.tool);
activeModule = require('./tools/'+argv.tool+'.js');
} else if (argv.hasOwnProperty('module')){
const loader = moduleLoaders[argv.module];
if (!loader) {
console.error("Invalid module provided. Please provide a valid module");
process.exit(1);
}
if (!cluster.isWorker) {
console.log("");
logStartup("module", argv.module);
}
return Promise.resolve().then(function runLoader() {
return loader();
}).then(function(loadedModule) {
activeModule = loadedModule;
}).catch(function onLoaderError(error) {
console.error("Failed to load module " + argv.module + ": " + shutdownErrorMessage(error));
process.exit(1);
});
} else {
console.error("Invalid module/tool provided. Please provide a valid module/tool");
console.error("Valid Modules: " + Object.keys(moduleLoaders).join(", "));
let valid_tools = "Valid Tools: ";
fs.readdirSync('./tools/').forEach(function(line){
valid_tools += path.parse(line).name + ", ";
});
valid_tools = valid_tools.slice(0, -2);
console.error(valid_tools);
process.exit(1);
}
});