From 8c6f9a3b710815953e2e5dc4312dc89503b85b9f Mon Sep 17 00:00:00 2001 From: undefined Date: Sun, 28 Feb 2021 14:36:46 +0800 Subject: [PATCH] judge: add cache cleaner --- packages/hydrojudge/bin/hydrojudge.js | 5 ++- packages/hydrojudge/package.json | 2 +- packages/hydrojudge/src/cache.ts | 44 +++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 packages/hydrojudge/src/cache.ts diff --git a/packages/hydrojudge/bin/hydrojudge.js b/packages/hydrojudge/bin/hydrojudge.js index 45da651f6..7acdbca26 100755 --- a/packages/hydrojudge/bin/hydrojudge.js +++ b/packages/hydrojudge/bin/hydrojudge.js @@ -1,3 +1,6 @@ #!/usr/bin/env node -require('../dist/daemon')(); +const { argv } = require('yargs'); + +if (argv._[0] == 'cache') require('../dist/cache')() +else if (!argv._) require('../dist/daemon')(); \ No newline at end of file diff --git a/packages/hydrojudge/package.json b/packages/hydrojudge/package.json index a2a391d80..116cc168d 100644 --- a/packages/hydrojudge/package.json +++ b/packages/hydrojudge/package.json @@ -1,7 +1,7 @@ { "name": "@hydrooj/hydrojudge", "bin": "bin/hydrojudge.js", - "version": "2.3.16", + "version": "2.3.17", "main": "package.json", "author": "undefined ", "repository": "https://github.com/hydro-dev/Hydro.git", diff --git a/packages/hydrojudge/src/cache.ts b/packages/hydrojudge/src/cache.ts new file mode 100644 index 000000000..5df81edf0 --- /dev/null +++ b/packages/hydrojudge/src/cache.ts @@ -0,0 +1,44 @@ +import path from 'path'; +import fs from 'fs-extra'; +import { argv } from 'yargs'; +import { Logger } from './log'; +import { getConfig } from './config'; + +const logger = new Logger('cache'); + +export = function main() { + const CACHE_DIR = getConfig('cache_dir'); + if (argv._[1] === 'clean') { + fs.emptyDirSync(CACHE_DIR); + logger.info('Cleaned cache.'); + } else if (argv._[1] === 'prune') { + const duration = +argv.duration || 30; + const now = new Date().getTime(); + const hosts = fs.readdirSync(CACHE_DIR); + let cnt = 0; + for (const host of hosts) { + const hostdir = path.resolve(CACHE_DIR, host); + if (!fs.statSync(hostdir).isDirectory()) continue; + const domains = fs.readdirSync(hostdir); + for (const domain of domains) { + const domaindir = path.resolve(hostdir, domain); + if (!fs.statSync(domaindir).isDirectory()) continue; + const problems = fs.readdirSync(domaindir); + for (const problem of problems) { + const problemdir = path.resolve(domaindir, problem); + if (!fs.statSync(problem).isDirectory()) continue; + let lastUsage = 0; + if (fs.existsSync(path.resolve(problemdir, 'lastUsage'))) { + const content = fs.readFileSync(path.resolve(problemdir, 'lastUsage')).toString(); + lastUsage = +content || 0; + } + if (lastUsage + duration * 24 * 3600 * 1000 > now) continue; + fs.removeSync(problemdir); + cnt++; + logger.info('Removed cache %s', problemdir); + } + } + } + logger.info('Done! %d items deleted.', cnt); + } +};