Files
cloudron-box/src/janitor.js

59 lines
2.1 KiB
JavaScript
Raw Normal View History

'use strict';
const assert = require('node:assert'),
BoxError = require('./boxerror.js'),
2017-04-23 21:53:59 -07:00
debug = require('debug')('box:janitor'),
2019-12-04 13:17:58 -08:00
Docker = require('dockerode'),
2021-06-04 09:28:40 -07:00
safe = require('safetydance'),
tokens = require('./tokens.js');
exports = module.exports = {
2021-05-01 11:21:09 -07:00
cleanupTokens,
cleanupDockerVolumes
};
2019-12-04 13:17:58 -08:00
const gConnection = new Docker({ socketPath: '/var/run/docker.sock' });
2015-10-17 13:57:19 -07:00
2021-06-04 09:28:40 -07:00
async function cleanupTokens() {
debug('Cleaning up expired tokens');
2021-06-04 09:28:40 -07:00
const [error, result] = await safe(tokens.delExpired());
if (error) return debug('cleanupTokens: error removing expired tokens. %o', error);
debug(`Cleaned up ${result} expired tokens`);
}
2021-09-17 09:22:46 -07:00
async function cleanupTmpVolume(containerInfo) {
2015-10-15 14:34:02 -07:00
assert.strictEqual(typeof containerInfo, 'object');
2015-10-14 23:08:36 -07:00
2021-09-17 09:22:46 -07:00
const cmd = 'find /tmp -type f -mtime +10 -exec rm -rf {} +'.split(' '); // 10 day old files
2015-10-14 23:08:36 -07:00
2022-11-23 22:03:18 +01:00
debug(`cleanupTmpVolume ${JSON.stringify(containerInfo.Names)}`);
2015-10-14 23:08:36 -07:00
2021-09-17 09:22:46 -07:00
const [error, execContainer] = await safe(gConnection.getContainer(containerInfo.Id).exec({ Cmd: cmd, AttachStdout: true, AttachStderr: true, Tty: false }));
if (error) throw new BoxError(BoxError.DOCKER_ERROR, `Failed to exec container: ${error.message}`);
2015-10-14 23:08:36 -07:00
2021-09-17 09:22:46 -07:00
const [startError, stream] = await safe(execContainer.start({ hijack: true }));
if (startError) throw new BoxError(BoxError.DOCKER_ERROR, `Failed to start exec container: ${startError.message}`);
2015-10-14 23:08:36 -07:00
2021-09-17 09:22:46 -07:00
gConnection.modem.demuxStream(stream, process.stdout, process.stderr);
2015-10-14 23:08:36 -07:00
2021-09-17 09:22:46 -07:00
return new Promise((resolve, reject) => {
stream.on('error', (error) => reject(new BoxError(BoxError.DOCKER_ERROR, `Failed to cleanup in exec container: ${error.message}`)));
stream.on('end', resolve);
2015-10-14 23:08:36 -07:00
});
}
2021-09-17 09:22:46 -07:00
async function cleanupDockerVolumes() {
2015-10-14 23:08:36 -07:00
debug('Cleaning up docker volumes');
2021-09-17 09:22:46 -07:00
const [error, containers] = await safe(gConnection.listContainers({ all: 0 }));
if (error) throw new BoxError(BoxError.DOCKER_ERROR, error);
2015-10-14 23:08:36 -07:00
2021-09-17 09:22:46 -07:00
for (const container of containers) {
await safe(cleanupTmpVolume(container), { debug }); // intentionally ignore error
}
2022-11-23 22:03:18 +01:00
debug('Cleaned up docker volumes');
2015-10-14 23:08:36 -07:00
}