-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
log_rotator.ts
352 lines (288 loc) · 10.4 KB
/
log_rotator.ts
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import * as chokidar from 'chokidar';
import fs from 'fs';
import { Server } from '@hapi/hapi';
import { throttle } from 'lodash';
import { tmpdir } from 'os';
import { basename, dirname, join, sep } from 'path';
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
import { promisify } from 'util';
import { LegacyLoggingConfig } from '../schema';
const mkdirAsync = promisify(fs.mkdir);
const readdirAsync = promisify(fs.readdir);
const renameAsync = promisify(fs.rename);
const statAsync = promisify(fs.stat);
const unlinkAsync = promisify(fs.unlink);
const writeFileAsync = promisify(fs.writeFile);
export class LogRotator {
private readonly config: LegacyLoggingConfig;
private readonly log: Server['log'];
public logFilePath: string;
public everyBytes: number;
public keepFiles: number;
public running: boolean;
private logFileSize: number;
public isRotating: boolean;
public throttledRotate: () => void;
public stalker: chokidar.FSWatcher | null;
public usePolling: boolean;
public pollingInterval: number;
private stalkerUsePollingPolicyTestTimeout: NodeJS.Timeout | null;
public shouldUsePolling: boolean;
constructor(config: LegacyLoggingConfig, server: Server) {
this.config = config;
this.log = server.log.bind(server);
this.logFilePath = config.dest;
this.everyBytes = config.rotate.everyBytes;
this.keepFiles = config.rotate.keepFiles;
this.running = false;
this.logFileSize = 0;
this.isRotating = false;
this.throttledRotate = throttle(async () => await this._rotate(), 5000);
this.stalker = null;
this.usePolling = config.rotate.usePolling;
this.pollingInterval = config.rotate.pollingInterval;
this.shouldUsePolling = false;
this.stalkerUsePollingPolicyTestTimeout = null;
}
async start() {
if (this.running) {
return;
}
this.running = true;
// create exit listener for cleanup purposes
this._createExitListener();
// call rotate on startup
await this._callRotateOnStartup();
// init log file size monitor
await this._startLogFileSizeMonitor();
}
stop = () => {
if (!this.running) {
return;
}
// cleanup exit listener
this._deleteExitListener();
// stop log file size monitor
this._stopLogFileSizeMonitor();
this.running = false;
};
async _shouldUsePolling() {
try {
// Setup a test file in order to try the fs env
// and understand if we need to usePolling or not
const tempFileDir = tmpdir();
const tempFile = join(tempFileDir, 'kbn_log_rotation_use_polling_test_file.log');
await mkdirAsync(tempFileDir, { recursive: true });
await writeFileAsync(tempFile, '');
// setup fs.watch for the temp test file
const testWatcher = fs.watch(tempFile, { persistent: false });
// await writeFileAsync(tempFile, 'test');
const usePollingTest$ = new Observable<boolean>((observer) => {
// observable complete function
const completeFn = (completeStatus: boolean) => {
if (this.stalkerUsePollingPolicyTestTimeout) {
clearTimeout(this.stalkerUsePollingPolicyTestTimeout);
}
testWatcher.close();
observer.next(completeStatus);
observer.complete();
};
// setup conditions that would fire the observable
this.stalkerUsePollingPolicyTestTimeout = setTimeout(
() => completeFn(true),
this.config.rotate.pollingPolicyTestTimeout || 15000
);
testWatcher.on('change', () => completeFn(false));
testWatcher.on('error', () => completeFn(true));
// fire test watcher events
setTimeout(() => {
fs.writeFileSync(tempFile, 'test');
}, 0);
});
// wait for the first observable result and consider it as the result
// for our use polling test
const usePollingTestResult = await usePollingTest$.pipe(first()).toPromise();
// delete the temp file used for the test
await unlinkAsync(tempFile);
return usePollingTestResult;
} catch {
return true;
}
}
async _startLogFileSizeMonitor() {
this.usePolling = this.config.rotate.usePolling;
this.shouldUsePolling = await this._shouldUsePolling();
if (this.usePolling && !this.shouldUsePolling) {
this.log(
['warning', 'logging:rotate'],
'Looks like your current environment support a faster algorithm then polling. You can try to disable `usePolling`'
);
}
if (!this.usePolling && this.shouldUsePolling) {
this.log(
['error', 'logging:rotate'],
'Looks like within your current environment you need to use polling in order to enable log rotator. Please enable `usePolling`'
);
}
this.stalker = chokidar.watch(this.logFilePath, {
ignoreInitial: true,
awaitWriteFinish: false,
useFsEvents: false,
usePolling: this.usePolling,
interval: this.pollingInterval,
binaryInterval: this.pollingInterval,
alwaysStat: true,
atomic: false,
});
this.stalker.on('change', this._logFileSizeMonitorHandler);
}
_logFileSizeMonitorHandler = async (filename: string, stats: fs.Stats) => {
if (!filename || !stats) {
return;
}
this.logFileSize = stats.size || 0;
await this.throttledRotate();
};
_stopLogFileSizeMonitor() {
if (!this.stalker) {
return;
}
this.stalker.close();
if (this.stalkerUsePollingPolicyTestTimeout) {
clearTimeout(this.stalkerUsePollingPolicyTestTimeout);
}
}
_createExitListener() {
process.on('exit', this.stop);
}
_deleteExitListener() {
process.removeListener('exit', this.stop);
}
async _getLogFileSizeAndCreateIfNeeded() {
try {
const logFileStats = await statAsync(this.logFilePath);
return logFileStats.size;
} catch {
// touch the file to make the watcher being able to register
// change events
await writeFileAsync(this.logFilePath, '');
return 0;
}
}
async _callRotateOnStartup() {
this.logFileSize = await this._getLogFileSizeAndCreateIfNeeded();
await this._rotate();
}
_shouldRotate() {
// should rotate evaluation
// 1. should rotate if current log size exceeds
// the defined one on everyBytes
// 2. should not rotate if is already rotating or if any
// of the conditions on 1. do not apply
if (this.isRotating) {
return false;
}
return this.logFileSize >= this.everyBytes;
}
async _rotate() {
if (!this._shouldRotate()) {
return;
}
await this._rotateNow();
}
async _rotateNow() {
// rotate process
// 1. get rotated files metadata (list of log rotated files present on the log folder, numerical sorted)
// 2. delete last file
// 3. rename all files to the correct index +1
// 4. rename + compress current log into 1
// 5. send SIGHUP to reload log config
// rotate process is starting
this.isRotating = true;
// get rotated files metadata
const foundRotatedFiles = await this._readRotatedFilesMetadata();
// delete number of rotated files exceeding the keepFiles limit setting
const rotatedFiles: string[] = await this._deleteFoundRotatedFilesAboveKeepFilesLimit(
foundRotatedFiles
);
// delete last file
await this._deleteLastRotatedFile(rotatedFiles);
// rename all files to correct index + 1
// and normalize numbering if by some reason
// (for example log file deletion) that numbering
// was interrupted
await this._renameRotatedFilesByOne(rotatedFiles);
// rename current log into 0
await this._rotateCurrentLogFile();
// send SIGHUP to reload log configuration
this._sendReloadLogConfigSignal();
// Reset log file size
this.logFileSize = 0;
// rotate process is finished
this.isRotating = false;
}
async _readRotatedFilesMetadata() {
const logFileBaseName = basename(this.logFilePath);
const logFilesFolder = dirname(this.logFilePath);
const foundLogFiles: string[] = await readdirAsync(logFilesFolder);
return (
foundLogFiles
.filter((file) => new RegExp(`${logFileBaseName}\\.\\d`).test(file))
// we use .slice(-1) here in order to retrieve the last number match in the read filenames
.sort((a, b) => Number(a.match(/(\d+)/g)!.slice(-1)) - Number(b.match(/(\d+)/g)!.slice(-1)))
.map((filename) => `${logFilesFolder}${sep}${filename}`)
);
}
async _deleteFoundRotatedFilesAboveKeepFilesLimit(foundRotatedFiles: string[]) {
if (foundRotatedFiles.length <= this.keepFiles) {
return foundRotatedFiles;
}
const finalRotatedFiles = foundRotatedFiles.slice(0, this.keepFiles);
const rotatedFilesToDelete = foundRotatedFiles.slice(
finalRotatedFiles.length,
foundRotatedFiles.length
);
await Promise.all(
rotatedFilesToDelete.map((rotatedFilePath: string) => unlinkAsync(rotatedFilePath))
);
return finalRotatedFiles;
}
async _deleteLastRotatedFile(rotatedFiles: string[]) {
if (rotatedFiles.length < this.keepFiles) {
return;
}
const lastFilePath: string = rotatedFiles.pop() as string;
await unlinkAsync(lastFilePath);
}
async _renameRotatedFilesByOne(rotatedFiles: string[]) {
const logFileBaseName = basename(this.logFilePath);
const logFilesFolder = dirname(this.logFilePath);
for (let i = rotatedFiles.length - 1; i >= 0; i--) {
const oldFilePath = rotatedFiles[i];
const newFilePath = `${logFilesFolder}${sep}${logFileBaseName}.${i + 1}`;
await renameAsync(oldFilePath, newFilePath);
}
}
async _rotateCurrentLogFile() {
const newFilePath = `${this.logFilePath}.0`;
await renameAsync(this.logFilePath, newFilePath);
}
_sendReloadLogConfigSignal() {
if (!process.env.isDevCliChild || !process.send) {
process.emit('SIGHUP', 'SIGHUP');
return;
}
// Send a special message to the cluster manager
// so it can forward it correctly
// It will only run when we are under cluster mode (not under a production environment)
process.send(['RELOAD_LOGGING_CONFIG_FROM_SERVER_WORKER']);
}
}