Files
cloudron-box/src/scheduler.js

169 lines
6.4 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
sync,
deleteJobs,
suspendAppJobs,
resumeAppJobs
};
2021-06-03 12:20:44 -07:00
const apps = require('./apps.js'),
assert = require('assert'),
BoxError = require('./boxerror.js'),
cloudron = require('./cloudron.js'),
constants = require('./constants.js'),
{ CronJob } = require('cron'),
2017-04-23 21:53:59 -07:00
debug = require('debug')('box:scheduler'),
2015-10-19 22:42:13 -07:00
docker = require('./docker.js'),
2021-08-25 19:41:46 -07:00
safe = require('safetydance'),
_ = require('underscore');
const gState = {}; // appId -> { containerId, schedulerConfig (manifest+crontab), cronjobs }
2022-05-20 09:38:17 -07:00
const gSuspendedAppIds = new Set(); // suspended because some apptask is running
2020-11-25 22:25:36 -08:00
// TODO: this should probably also stop existing jobs to completely prevent race but the code is not re-entrant
function suspendAppJobs(appId) {
debug(`suspendAppJobs: ${appId}`);
gSuspendedAppIds.add(appId);
}
function resumeAppJobs(appId) {
debug(`resumeAppJobs: ${appId}`);
gSuspendedAppIds.delete(appId);
}
2021-08-25 19:41:46 -07:00
async function runTask(appId, taskName) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof taskName, 'string');
const JOB_MAX_TIME = 30 * 60 * 1000; // 30 minutes
const containerName = `${appId}-${taskName}`;
2015-10-20 10:16:59 -07:00
2021-08-25 19:41:46 -07:00
if (gSuspendedAppIds.has(appId)) return;
2021-08-25 19:41:46 -07:00
const app = await apps.get(appId);
if (!app) throw new BoxError(BoxError.NOT_FOUND, 'App not found');
2021-08-25 19:41:46 -07:00
if (app.installationState !== apps.ISTATE_INSTALLED || app.runState !== apps.RSTATE_RUNNING || app.health !== apps.HEALTH_HEALTHY) return;
2021-08-31 07:59:07 -07:00
const [error, data] = await safe(docker.inspect(containerName));
if (!error && data?.State?.Running === true) {
2021-08-25 19:41:46 -07:00
const jobStartTime = new Date(data.State.StartedAt); // iso 8601
if ((new Date() - jobStartTime) < JOB_MAX_TIME) return;
debug(`runTask: ${containerName} is running too long, restarting`);
2021-08-25 19:41:46 -07:00
}
2021-08-25 19:41:46 -07:00
await docker.restartContainer(containerName);
}
2021-08-25 19:41:46 -07:00
async function createJobs(app, schedulerConfig) {
assert.strictEqual(typeof app, 'object');
assert(schedulerConfig && typeof schedulerConfig === 'object');
2018-02-27 13:50:29 -08:00
const appId = app.id;
const jobs = {};
const tz = await cloudron.getTimeZone();
2021-08-25 19:41:46 -07:00
for (const taskName of Object.keys(schedulerConfig)) {
const { schedule, command } = schedulerConfig[taskName];
const containerName = `${app.id}-${taskName}`;
// stopJobs only deletes jobs since previous sync. This means that when box code restarts, none of the containers
2020-08-18 23:53:14 -07:00
// are removed. The deleteContainer here ensures we re-create the cron containers with the latest config
2021-08-25 19:41:46 -07:00
await safe(docker.deleteContainer(containerName)); // ignore error
const [error] = await safe(docker.createSubcontainer(app, containerName, [ '/bin/sh', '-c', command ], {} /* options */), { debug });
2021-08-25 19:41:46 -07:00
if (error && error.reason !== BoxError.ALREADY_EXISTS) continue;
debug(`createJobs: ${taskName} (${app.fqdn}) will run in container ${containerName}`);
let cronTime;
if (schedule === '@service') {
cronTime = new Date(Date.now() + 2*1000); // 2 seconds from now
} else {
// random is so that all crons start at once to decrease memory pressure
cronTime = (constants.TEST ? '*/5 ' : `${Math.floor(60*Math.random())} `) + schedule; // time ticks faster in tests
}
const cronJob = CronJob.from({
cronTime,
2021-08-25 19:41:46 -07:00
onTick: async () => {
const [error] = await safe(runTask(appId, taskName)); // put the app id in closure, so we don't use the outdated app object by mistake
if (error) debug(`could not run task ${taskName} : ${error.message}`);
},
start: true,
timeZone: tz
2021-08-25 19:41:46 -07:00
});
2021-08-25 19:41:46 -07:00
jobs[taskName] = cronJob;
}
2021-08-25 19:41:46 -07:00
return jobs;
}
async function deleteAppJobs(appId, appState) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appState, 'object');
2021-08-25 19:41:46 -07:00
if (!appState) return;
2021-08-25 19:41:46 -07:00
for (const taskName of Object.keys(appState.schedulerConfig)) {
if (appState.cronJobs && appState.cronJobs[taskName]) appState.cronJobs[taskName].stop();
2015-10-20 10:16:59 -07:00
const containerName = `${appId}-${taskName}`;
2021-08-25 19:41:46 -07:00
const [error] = await safe(docker.deleteContainer(containerName));
if (error) debug(`deleteAppJobs: failed to delete task container with name ${containerName} : ${error.message}`);
}
}
async function deleteJobs() {
for (const appId of Object.keys(gState)) {
debug(`deleteJobs: removing jobs of ${appId}`);
const [error] = await safe(deleteAppJobs(appId, gState[appId]));
if (error) debug(`deleteJobs: error stopping jobs of removed app ${appId}: ${error.message}`);
delete gState[appId];
2021-08-25 19:41:46 -07:00
}
}
2021-08-25 19:41:46 -07:00
async function sync() {
2021-06-03 12:20:44 -07:00
if (constants.TEST) return;
2021-08-25 19:41:46 -07:00
const allApps = await apps.list();
const allAppIds = allApps.map(app => app.id);
2021-08-25 19:41:46 -07:00
const removedAppIds = _.difference(Object.keys(gState), allAppIds);
if (removedAppIds.length !== 0) debug(`sync: stopping jobs of removed apps ${JSON.stringify(removedAppIds)}`);
2021-08-25 19:41:46 -07:00
for (const appId of removedAppIds) {
debug(`sync: removing jobs of ${appId}`);
const [error] = await safe(deleteAppJobs(appId, gState[appId]));
2021-08-25 19:41:46 -07:00
if (error) debug(`sync: error stopping jobs of removed app ${appId}: ${error.message}`);
2022-05-20 09:38:17 -07:00
delete gState[appId];
2021-08-25 19:41:46 -07:00
}
2021-08-25 19:41:46 -07:00
for (const app of allApps) {
const appState = gState[app.id] || null;
const schedulerConfig = apps.getSchedulerConfig(app);
2021-08-25 19:41:46 -07:00
if (!appState && !schedulerConfig) continue; // nothing to do
if (appState && appState.cronJobs) { // we had created jobs for this app previously
if (_.isEqual(appState.schedulerConfig, schedulerConfig) && appState.containerId === app.containerId) continue; // nothing changed
}
debug(`sync: clearing jobs of ${app.id} (${app.fqdn})`);
const [error] = await safe(deleteAppJobs(app.id, appState));
2021-08-25 19:41:46 -07:00
if (error) debug(`sync: error stopping jobs of ${app.id} : ${error.message}`);
2015-10-20 00:02:25 -07:00
2021-08-25 19:41:46 -07:00
if (!schedulerConfig) { // updated app version removed scheduler addon
delete gState[app.id];
continue;
}
2015-11-22 21:17:17 -08:00
if (gSuspendedAppIds.has(app.id)) continue; // do not create jobs of suspended apps
2021-08-25 19:41:46 -07:00
const cronJobs = await createJobs(app, schedulerConfig); // if docker is down, the next sync() will recreate everything for this app
gState[app.id] = { containerId: app.containerId, schedulerConfig, cronJobs };
}
}