forked from pointnetwork/pointnetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoint
More file actions
executable file
·274 lines (223 loc) · 9.46 KB
/
point
File metadata and controls
executable file
·274 lines (223 loc) · 9.46 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
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
#!/usr/bin/env node
// Check Node.js version
const m = process.version.match(/(\d+)\.(\d+)\.(\d+)/);
const [major, minor, patch] = m.slice(1).map(_ => parseInt(_));
if (major < 14) {
console.error('\x1b[41m%s\x1b[0m', "You are not using the latest Node.JS version supported by this application. Execute `nvm use` to switch to the app's version.");
process.exit(1);
}
// Load first dependencies
const { Command } = require('commander');
const { homedir } = require('os');
const { exec } = require("child_process");
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const pino = require('pino');
const multistream = require('pino-multi-stream').multistream;
const npid = require('npid');
const mkdirp = require('mkdirp');
const DB = require('./db');
const program = new Command();
// Disable https://nextjs.org/telemetry
process.env['NEXT_TELEMETRY_DISABLED'] = '1'
// TODO: Enabled this option for backward-compatibility support, but remove later to support newer syntax
program.storeOptionsAsProperties();
program.version(`
0.0 alpha
`); // todo
program.description(`
Point Network
https://pointnetwork.io/
Licensed under MIT license.
`);
// Print disclaimer
require('./resources/disclaimer').output();
// NOTE: After changing parameters here, update the documentation
program.command('go', { isDefault: true }).description('start the node').action(() => { program.go = true; });
program.option('--config <file>', 'path to the configuration file');
program.option('--datadir <path>', 'path to the data directory', path.join(homedir(), '.point/'));
program.option('-v, --verbose', 'force the logger to show debug level messages', false);
program.command('attach').description('attach to the running point process').action(() => program.attach = true);
program.command('makemigration').description('[dev mode] auto create db migrations from models').action(() => program.makemigration = true);
program.command('migrate').description('[dev mode] run migrations').action(() => program.migrate = true);
program.command('migrate:undo').description('[dev mode] undo migration').action(() => program.migrate = program.migrate_undo = true);
program.command('demo').description('dump demo configs to ~/.point').action(() => program.demo = true);
program.command('debug-destroy-everything').description('destroys everything in datadir: database and files. dangerous!').action(() => program.debug_destroy_everything = true);
program.command('deploy <path>')
.description('deploy a website')
.action((path, cmd) => { program.deploy = path; program.deploy_contracts = !!cmd.contracts; })
.option('--contracts', '(re)deploy contracts too', false);
// program.option('--shutdown', 'sends the shutdown signal to the daemon'); // todo
// program.option('--daemon', 'sends the daemon to the background'); // todo
// program.option('--rpc <method> [params]', 'send a command to the daemon'); // todo
program.parse(process.argv);
// todo: mix other param arguments into config, like here:
// let argv;
// let config = rc('kadence', options(program.datadir), argv);
if (! program.config) {
program.config = path.join(program.datadir, 'config.json');
}
ctx = {};
ctx.datadir = ctx.datapath = program.datadir;
ctx.configPath = program.config;
ctx.basepath = __dirname;
ctx.exit = (code = 1) => { process.exit(code); }; // todo: use graceful _exit() function here below. and why 1?
ctx.die = (err) => { ctx.log.fatal(err); ctx.exit(1); };
// --------------- Dump Demo Configs ----------------- //
// Must be placed before we're checking for existence of any configs!
if (program.demo) {
require('./resources/demo');
return;
}
// ------------------- Init Config ----------------- //
if (! fs.existsSync(ctx.datadir)) mkdirp.sync(ctx.datadir);
if (! fs.existsSync(ctx.configPath)) throw Error('Cannot find configuration file '+ctx.configPath);
const environment = process.env.DB_ENV || 'development';
const config = JSON.parse(fs.readFileSync(ctx.configPath, 'utf-8'));
const defaultConfig = require(path.resolve(__dirname, 'resources', 'defaultConfig.json'));
const dbConfig = { "db": require(path.resolve(__dirname, 'resources', 'sequelizeConfig.json'))[environment] }; // todo: the todo is about 'development' part
ctx.config = _.merge(defaultConfig, dbConfig, config);
if (program.verbose) ctx.config.log.level = 'debug';
// ------------------- Init Logger ----------------- //
const logFilePath = path.join(ctx.datadir, 'point.log');
const level = pino.levels.values[ ctx.config.log.level ];
const formatters = {
level: (label) => {
return { level: label };
},
}
const options = {
enabled: ctx.config.log.enabled,
formatters,
level
};
let streams = [];
const outStream = pino({ prettyPrint: { colorize: true } });
streams.push({
level: options.level,
stream: outStream[pino.symbols.streamSym]
});
streams.push({
level: options.level,
stream: fs.createWriteStream(path.resolve(logFilePath))
});
ctx.log = pino(options, multistream(streams));
// ----------------- Console Mode -------------------- //
if (program.attach) {
const Console = require('./console');
const console = new Console();
console.start();
return;
}
// -------------------- Deployer --------------------- //
if (program.deploy) {
if (program.deploy.length === 0) return ctx.die('error: missing path');
const Deploy = require('./core/deploy');
const deploy = new Deploy(ctx);
deploy.deploy(program.deploy, program.deploy_contracts);
return;
}
// ---------------- Migration Modes ---------------- //
if (program.makemigration) {
// A little hack: prepare sequelize-auto-migrations for reading from the current datadir config
process.argv = ['./point', 'makemigration', '--models-path', './db/models', '--migrations-path', './db/migrations', '--name', 'automigration'];
const SequelizeFactory = require('./db/models');
SequelizeFactory.init(ctx);
require('./node_modules/sequelize-auto-migrations/bin/makemigration.js');
return;
}
if (program.migrate) {
const seq_cmd = (program.migrate_undo) ? 'db:migrate:undo' : 'db:migrate';
exec(`npx sequelize-cli ${seq_cmd} --env ${process.env.DB_ENV || ctx.config.db.database}`, (error, stdout, stderr) => {
if (error) return console.log(`error: ${error.message}`);
if (stderr) return console.log(`stderr: ${stderr}`);
console.log(`${stdout}`);
});
return;
}
// ------------------ Remove Everything ------------ //
if (program.debug_destroy_everything) {
// todo: remove in prod, dangerous
ctx.db = new DB(ctx);
DB.__debugClearCompletely(ctx); // async!
return;
}
// ------------ Main Cycle After This Block ---------- //
if (! program.go || program.args.length > 0) {
program.help();
ctx.die();
}
// ---------------------- PID ------------------------ //
const pidFilePath = path.join(ctx.datadir, 'point.pid');
try {
npid.create(pidFilePath).removeOnExit();
} catch (err) {
ctx.log.fatal('Failed to create PID file, is point already running? File path: '+pidFilePath);
process.exit(1);
}
// ------------------ Gracefully exit ---------------- //
let exiting = false;
async function _exit(sig) {
if (exiting) return;
exiting = true;
let errors = [];
ctx.log.info('Received signal '+sig+', shutting down...');
try {
if (ctx.db && ctx.db.shutdown) await ctx.db.shutdown();
} catch(e) {
errors.push('Error while shutting down database: ' + e);
}
if (errors.length) {
for (let e of errors) ctx.log.error(e);
} else {
ctx.log.info('Successfully shut down.');
}
process.exit(1);
// todo: shut down everything else
}
const sigs = ['exit', 'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'];
sigs.forEach(function (sig) {
process.on(sig, function () {
_exit(sig);
});
});
process.on('uncaughtException', (err) => {
ctx.log.error(err.message);
ctx.log.debug(err.stack);
if (err.message.includes('This socket has been ended by the other party')) {
// todo: where is it coming from?
/*
[1632829385722] ERROR (5912 on Serges-MacBook-Pro.local): This socket has been ended by the other party
[1632829385722] DEBUG (5912 on Serges-MacBook-Pro.local): Error: This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:457:14)
at Socket.ondata (internal/streams/readable.js:726:22)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
*/
// do nothing
return;
}
npid.remove(pidFilePath);
process.exit(1);
});
process.on('unhandledRejection', (err, second) => {
npid.remove(pidFilePath);
if (err.message && err.message.includes && err.message.includes('Invalid JSON RPC response')) ctx.log.debug('>>> Are you sure you have a web3 connection? Such as Ganache, Ethereum etc. <<<');
ctx.log.debug(err, second);
ctx.log.error('Unhandled Rejection: ' + err.message);
ctx.log.debug(err.stack);
process.exit(1);
});
// -------------------- Init DB ---------------------- //
ctx.db = new DB(ctx);
setImmediate(async() => {
await ctx.db.init();
})
// ------------------- Start Point ------------------- //
const Point = require('./core');
point = new Point(ctx);
point.start();