File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 1
1
import { MongoshInternalError } from '@mongosh/errors' ;
2
+ import bson from 'bson' ;
2
3
import { once } from 'events' ;
3
4
import { promises as fs } from 'fs' ;
4
5
import http from 'http' ;
@@ -276,6 +277,22 @@ describe('CliRepl', () => {
276
277
await onerror ;
277
278
} ) ;
278
279
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
+
279
296
it ( 'verifies the Node.js version' , async ( ) => {
280
297
const origVersionCheckEnvVar = process . env . MONGOSH_SKIP_NODE_VERSION_CHECK ;
281
298
delete process . env . MONGOSH_SKIP_NODE_VERSION_CHECK ;
Original file line number Diff line number Diff line change @@ -279,6 +279,7 @@ class CliRepl {
279
279
*/
280
280
async openLogStream ( ) : Promise < Writable > {
281
281
const path = this . shellHomeDirectory . localPath ( `${ this . logId } _log` ) ;
282
+ await this . cleanupOldLogfiles ( ) ;
282
283
try {
283
284
const stream = createWriteStream ( path , { mode : 0o600 } ) ;
284
285
await once ( stream , 'ready' ) ;
@@ -294,6 +295,29 @@ class CliRepl {
294
295
}
295
296
}
296
297
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 - f 0 - 9 ] { 24 } ) _ l o g $ / 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
+
297
321
warnAboutInaccessibleFile ( err : Error , path ?: string ) : void {
298
322
this . bus . emit ( 'mongosh:error' , err ) ;
299
323
if ( this . warnedAboutInaccessibleFiles ) {
You can’t perform that action at this time.
0 commit comments