-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserver.js
181 lines (151 loc) · 4.85 KB
/
server.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
/* eslint no-console: 0, no-sync: 0 */
'use strict';
// Set the global variable "ezpaarse"
require('./lib/global.js');
const config = require('./lib/config.js');
const socketIO = require('./lib/socketio.js');
const mongo = require('./lib/mongo.js');
const castor = require('./lib/castor.js');
const http = require('http');
const path = require('path');
const Reaper = require('tmp-reaper');
const parserlist = require('./lib/parserlist.js');
const ecFilter = require('./lib/ecfilter.js');
const logger = require('./lib/logger.js');
const lsof = require('lsof');
const fs = require('fs-extra');
const pkg = require('./package.json');
const app = require('./app');
const jobsCache = require('./lib/cache-jobs');
// to have a nice unix process name
process.title = pkg.name.toLowerCase();
const { argv } = require('yargs')
.option('pid', {
alias: 'pidFile',
describe: 'the location of the ezpaarse pid file',
default: path.resolve(__dirname, 'ezpaarse.pid')
})
.option('lsof', {
boolean: true,
describe: 'periodically prints the number of opened file descriptors'
})
.option('memory', {
boolean: true,
describe: 'periodically prints the memory usage'
});
fs.ensureDirSync(path.resolve(__dirname, 'tmp'));
// Setup cleaning jobs for the temporary folder
if (config.EZPAARSE_TMP_CYCLE && config.EZPAARSE_TMP_LIFETIME) {
new Reaper({
recursive: true,
threshold: config.EZPAARSE_TMP_LIFETIME,
every: config.EZPAARSE_TMP_CYCLE
}).watch(path.resolve(__dirname, 'tmp'))
.on('error', err => {
logger.error(`[Temp. cleaner] ${err}`);
})
.start();
} else {
let err = 'Temporary folder won\'t be automatically cleaned, ';
err += 'fill TMP_CYCLE and TMP_LIFETIME in the configuration file.';
logger.warn(err);
}
if (argv.pidFile) {
// write pid to ezpaarse.pid file
fs.writeFileSync(argv.pidFile, process.pid.toString());
}
if (argv.lsof) {
(function checklsof() {
lsof.raw(process.pid, function (data) {
data = data.filter(function (element) {
return /^(?:DIR|REG)$/i.test(element.type);
});
logger.info(`${data.length} file descriptors`);
setTimeout(checklsof, 5000);
});
})();
}
if (argv.memory) {
(function checkMemory() {
const memoryUsage = Math.round(process.memoryUsage().rss / 1024 / 1024 * 100) / 100;
logger.info(`Memory usage: ${memoryUsage} MiB`);
setTimeout(checkMemory, 5000);
})();
}
start().then(() => {
if (typeof process.send === 'function') {
process.send('ready');
}
logger.info(`Listening on http://localhost:${app.get('port')}`);
castor.start();
});
/**
* Init and start the server
*/
async function start () {
logger.info(`${pkg.name} v${pkg.version} | PID: ${process.pid} | Mode: ${app.get('env')}`);
logger.info(`Node version: ${process.version}`);
await connectToMongo();
const nbRobots = await new Promise((resolve, reject) => {
ecFilter.init((err, nbRobots) => {
if (err) { reject(err); }
else { resolve(nbRobots); }
});
});
try {
await parserlist.init();
} catch (e) {
logger.error(`Failed to initialize parser list: ${e.message}`);
process.exit(1);
}
const nbDomains = parserlist.sizeOf('domains');
const nbPlatforms = parserlist.sizeOf('platforms');
logger.info(`Domains: ${nbDomains} | Platforms: ${nbPlatforms} | Robot hosts: ${nbRobots}`);
const server = http.createServer(app);
server.requestTimeout = 0;
socketIO.listen(server);
return new Promise(resolve => server.listen(app.get('port'), resolve));
}
/**
* Connect to MongoDB and check that version matches requirements
*/
async function connectToMongo () {
try {
await mongo.connect(config.EZPAARSE_MONGO_URL);
} catch (err) {
logger.error(`Cannot connect to MongoDB at ${config.EZPAARSE_MONGO_URL}`);
process.exit(1);
}
try {
// drop and create index for jobs cache
await jobsCache.createIndex(config.EZPAARSE_TMP_LIFETIME);
} catch (err) {
logger.error('Cannot create index `createdAt` in `treatments` collection');
process.exit(1);
}
let mongoVersion;
try {
const info = await mongo.serverStatus();
mongoVersion = info.version;
} catch (err) {
logger.error('Cannot fetch MongoDB version');
process.exit(1);
}
logger.info(`MongoDB version: ${mongoVersion}`);
const versions = /^([0-9]+)\.([0-9]+)/.exec(mongoVersion);
const major = parseInt(versions[1]);
const minor = parseInt(versions[2]);
if (major < 3 || (major === 3 && minor < 2)) {
logger.error('MongoDB server outdated, please install version 3.2.0 or higher');
process.exit(1);
}
}
/**
* To handled CTRL+C events
*/
function shutdown() {
logger.info('Got a stop signal, shutting down...');
process.exit(0);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);