forked from OriginTrail/ot-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ot-node.js
256 lines (224 loc) · 10.9 KB
/
ot-node.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
const { execSync } = require('child_process');
const DeepExtend = require('deep-extend');
const rc = require('rc');
const fs = require('fs');
const queue = require('fastq');
const AutoUpdater = require('./modules/auto-update/auto-updater-module-interface');
const DependencyInjection = require('./modules/service/dependency-injection');
const Logger = require('./modules/logger/logger');
const constants = require('./modules/constants');
const pjson = require('./package.json');
const configjson = require('./config/config.json');
let updateFilePath;
class OTNode {
constructor(config) {
this.initializeConfiguration(config);
this.logger = new Logger(this.config.logLevel, this.config.telemetryHub.enabled);
}
async start() {
this.logger.info(' ██████╗ ████████╗███╗ ██╗ ██████╗ ██████╗ ███████╗');
this.logger.info('██╔═══██╗╚══██╔══╝████╗ ██║██╔═══██╗██╔══██╗██╔════╝');
this.logger.info('██║ ██║ ██║ ██╔██╗ ██║██║ ██║██║ ██║█████╗');
this.logger.info('██║ ██║ ██║ ██║╚██╗██║██║ ██║██║ ██║██╔══╝');
this.logger.info('╚██████╔╝ ██║ ██║ ╚████║╚██████╔╝██████╔╝███████╗');
this.logger.info(' ╚═════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝');
this.logger.info('======================================================');
this.logger.info(` OriginTrail Node v${pjson.version}`);
this.logger.info('======================================================');
this.logger.info(`Node is running in ${process.env.NODE_ENV} environment`);
this.initializeDependencyContainer();
await this.initializeAutoUpdate();
await this.initializeDataModule();
await this.initializeOperationalDbModule();
await this.initializeValidationModule();
await this.initializeBlockchainModule();
await this.initializeNetworkModule();
await this.initializeCommandExecutor();
await this.initializeTelemetryHubModule();
await this.initializeRpcModule();
// await this.initializeWatchdog();
}
initializeConfiguration(userConfig) {
const defaultConfig = JSON.parse(JSON.stringify(configjson[process.env.NODE_ENV]));
if (userConfig) {
this.config = DeepExtend(defaultConfig, userConfig);
} else {
this.config = rc(pjson.name, defaultConfig);
}
if (!this.config.configFilename) {
// set default user configuration filename
this.config.configFilename = '.origintrail_noderc';
}
if (!this.config.blockchain[0].hubContractAddress
&& this.config.blockchain[0].networkId === defaultConfig.blockchain[0].networkId) {
this.config.blockchain[0].hubContractAddress = configjson[process.env.NODE_ENV]
.blockchain[0].hubContractAddress;
}
}
initializeDependencyContainer() {
this.container = DependencyInjection.initialize();
DependencyInjection.registerValue(this.container, 'config', this.config);
DependencyInjection.registerValue(this.container, 'logger', this.logger);
DependencyInjection.registerValue(this.container, 'constants', constants);
DependencyInjection.registerValue(this.container, 'blockchainQueue', queue);
DependencyInjection.registerValue(this.container, 'tripleStoreQueue', queue);
this.logger.info('Dependency injection module is initialized');
}
async initializeAutoUpdate() {
try {
updateFilePath = `./${this.config.appDataPath}/UPDATED`;
if (fs.existsSync(updateFilePath)) {
this.config.otNodeUpdated = true;
}
if (!this.config.autoUpdate.enabled) {
return;
}
const autoUpdateConfig = {
logger: this.logger,
branch: this.config.autoUpdate.branch,
tempLocation: this.config.autoUpdate.backupDirectory,
executeOnComplete: `touch ${updateFilePath}`,
};
execSync(`mkdir -p ${this.config.autoUpdate.backupDirectory}`);
this.updater = new AutoUpdater(autoUpdateConfig);
await this.updater.initialize();
DependencyInjection.registerValue(this.container, 'updater', this.updater);
this.logger.info('Auto update mechanism initialized');
} catch (e) {
this.logger.error({
msg: `Auto update initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.UPDATE_INITIALIZATION_ERROR,
});
}
}
async initializeDataModule() {
try {
const dataService = this.container.resolve('dataService');
await dataService.initialize();
this.logger.info(`Data module: ${dataService.getName()} implementation`);
} catch (e) {
this.logger.error({
msg: `Data module initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.DATA_MODULE_INITIALIZATION_ERROR,
});
}
}
async initializeOperationalDbModule() {
try {
this.logger.info('Operational database module: sequelize implementation');
// eslint-disable-next-line global-require
const db = require('./models');
if(this.config.otNodeUpdated) {
execSync('npx sequelize --config=./config/sequelizeConfig.js db:migrate');
const fileService = this.container.resolve('fileService');
await fileService.removeFile(updateFilePath);
this.config.otNodeUpdated = false;
}
await db.sequelize.sync();
} catch (e) {
this.logger.error({
msg: `Operational database module initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.OPERATIONALDB_MODULE_INITIALIZATION_ERROR,
});
}
}
async initializeNetworkModule() {
try {
const networkService = this.container.resolve('networkService');
const result = await networkService.initialize();
this.config.network.peerId = result.peerId;
if (!this.config.network.privateKey
&& (this.config.network.privateKey !== result.privateKey)) {
this.config.network.privateKey = result.privateKey;
if (process.env.NODE_ENV !== 'development' && process.env.NODE_ENV !== 'test') {
this.savePrivateKeyInUserConfigurationFile(result.privateKey);
}
}
const rankingService = this.container.resolve('rankingService');
await rankingService.initialize();
this.logger.info(`Network module: ${networkService.getName()} implementation`);
} catch (e) {
this.logger.error({
msg: `Network module initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.NETWORK_INITIALIZATION_ERROR,
});
}
}
async initializeValidationModule() {
try {
const validationService = this.container.resolve('validationService');
await validationService.initialize();
this.logger.info(`Validation module: ${validationService.getName()} implementation`);
} catch (e) {
this.logger.error({
msg: `Validation module initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.VALIDATION_INITIALIZATION_ERROR,
});
}
}
async initializeBlockchainModule() {
try {
const blockchainService = this.container.resolve('blockchainService');
await blockchainService.initialize();
this.logger.info(`Blockchain module: ${blockchainService.getName()} implementation`);
} catch (e) {
this.logger.error({
msg: `Blockchain module initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.BLOCKCHAIN_INITIALIZATION_ERROR,
});
}
}
async initializeCommandExecutor() {
try {
const commandExecutor = this.container.resolve('commandExecutor');
await commandExecutor.init();
commandExecutor.replay();
await commandExecutor.start();
} catch (e) {
this.logger.error({
msg: `Command executor initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.COMMAND_EXECUTOR_INITIALIZATION_ERROR,
});
}
}
async initializeRpcModule() {
try {
const rpcController = this.container.resolve('rpcController');
await rpcController.initialize();
} catch (e) {
this.logger.error({
msg: `RPC service initialization failed. Error message: ${e.message}`,
Event_name: constants.ERROR_TYPE.RPC_INITIALIZATION_ERROR,
});
}
}
async initializeTelemetryHubModule() {
try {
const telemetryHubModuleManager = this.container.resolve('telemetryHubModuleManager');
if (telemetryHubModuleManager.initialize(this.config.telemetryHub, this.logger)) {
this.logger.info(`Telemetry hub module initialized successfully, using ${telemetryHubModuleManager.config.telemetryHub.packages} package(s)`);
}
} catch (e) {
this.logger.error(`Telemetry hub module initialization failed. Error message: ${e.message}`);
}
}
async initializeWatchdog() {
try {
const watchdogService = this.container.resolve('watchdogService');
await watchdogService.initialize();
this.logger.info('Watchdog service initialized');
} catch (e) {
this.logger.warn(`Watchdog service initialization failed. Error message: ${e.message}`);
}
}
savePrivateKeyInUserConfigurationFile(privateKey) {
const configFile = JSON.parse(fs.readFileSync(this.config.configFilename));
configFile.network.privateKey = privateKey;
fs.writeFileSync(this.config.configFilename, JSON.stringify(configFile, null, 2));
}
stop() {
this.logger.info('Stopping node...');
process.exit(0);
}
}
module.exports = OTNode;