Skip to content

Commit 103414d

Browse files
authored
fix(cli-repl): delete log files older than 30 days MONGOSH-830 (#950)
1 parent ec09a8c commit 103414d

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

packages/cli-repl/src/cli-repl.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { MongoshInternalError } from '@mongosh/errors';
2+
import bson from 'bson';
23
import { once } from 'events';
34
import { promises as fs } from 'fs';
45
import http from 'http';
@@ -276,6 +277,22 @@ describe('CliRepl', () => {
276277
await onerror;
277278
});
278279

280+
it('removes old log files', async() => {
281+
const oldlogfile = path.join(tmpdir.path, '60a0064774d771e863d9a1e1_log');
282+
const newerlogfile = path.join(tmpdir.path, `${new bson.ObjectId()}_log`);
283+
await fs.writeFile(oldlogfile, 'ignoreme');
284+
await fs.writeFile(newerlogfile, 'ignoreme');
285+
cliRepl = new CliRepl(cliReplOptions);
286+
await cliRepl.start('', {});
287+
await fs.stat(newerlogfile);
288+
try {
289+
await fs.stat(oldlogfile);
290+
expect.fail('missed exception');
291+
} catch (err) {
292+
expect(err.code).to.equal('ENOENT');
293+
}
294+
});
295+
279296
it('verifies the Node.js version', async() => {
280297
const origVersionCheckEnvVar = process.env.MONGOSH_SKIP_NODE_VERSION_CHECK;
281298
delete process.env.MONGOSH_SKIP_NODE_VERSION_CHECK;

packages/cli-repl/src/cli-repl.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ class CliRepl {
279279
*/
280280
async openLogStream(): Promise<Writable> {
281281
const path = this.shellHomeDirectory.localPath(`${this.logId}_log`);
282+
await this.cleanupOldLogfiles();
282283
try {
283284
const stream = createWriteStream(path, { mode: 0o600 });
284285
await once(stream, 'ready');
@@ -294,6 +295,29 @@ class CliRepl {
294295
}
295296
}
296297

298+
async cleanupOldLogfiles(): Promise<void> {
299+
const dir = this.shellHomeDirectory.localPath('');
300+
let dirHandle;
301+
try {
302+
dirHandle = await fs.opendir(dir);
303+
} catch {
304+
return;
305+
}
306+
for await (const dirent of dirHandle) {
307+
if (!dirent.isFile()) continue;
308+
const { id } = dirent.name.match(/^(?<id>[a-f0-9]{24})_log$/i)?.groups ?? {};
309+
if (!id) continue;
310+
// Delete files older than 30 days
311+
if (new bson.ObjectId(id).generationTime < (Date.now() / 1000) - 30 * 86400) {
312+
try {
313+
await fs.unlink(path.join(dir, dirent.name));
314+
} catch (err) {
315+
this.bus.emit('mongosh:error', err);
316+
}
317+
}
318+
}
319+
}
320+
297321
warnAboutInaccessibleFile(err: Error, path?: string): void {
298322
this.bus.emit('mongosh:error', err);
299323
if (this.warnedAboutInaccessibleFiles) {

0 commit comments

Comments
 (0)