Files
cloudron-box/src/scheduler.js
T

170 lines
6.4 KiB
JavaScript
Raw Normal View History

import apps from './apps.js';
import assert from 'node:assert';
import BoxError from './boxerror.js';
2026-02-14 15:43:24 +01:00
import cloudron from './cloudron.js';
import constants from './constants.js';
import { CronJob } from 'cron';
import debugModule from 'debug';
2026-02-14 15:43:24 +01:00
import docker from './docker.js';
import safe from 'safetydance';
2026-02-14 15:43:24 +01:00
import _ from './underscore.js';
const debug = debugModule('box:scheduler');
2015-10-18 08:40:24 -07:00
2022-05-20 09:31:58 -07:00
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
2015-10-18 08:40:24 -07:00
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);
}
2015-10-18 08:40:24 -07:00
2021-08-25 19:41:46 -07:00
async function runTask(appId, taskName) {
2020-08-18 19:08:37 -07:00
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof taskName, 'string');
2020-08-18 19:08:37 -07:00
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);
2015-10-18 08:40:24 -07:00
}
2021-08-25 19:41:46 -07:00
async function createJobs(app, schedulerConfig) {
2020-08-18 19:08:37 -07:00
assert.strictEqual(typeof app, 'object');
assert(schedulerConfig && typeof schedulerConfig === 'object');
2018-02-27 13:50:29 -08:00
2020-08-18 19:08:37 -07:00
const appId = app.id;
2022-05-20 09:31:58 -07:00
const jobs = {};
const tz = await cloudron.getTimeZone();
2020-08-18 19:08:37 -07:00
2021-08-25 19:41:46 -07:00
for (const taskName of Object.keys(schedulerConfig)) {
2022-05-20 09:31:58 -07:00
const { schedule, command } = schedulerConfig[taskName];
2020-08-18 19:08:37 -07:00
const containerName = `${app.id}-${taskName}`;
2022-05-20 09:31:58 -07:00
// 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
2022-05-20 09:31:58 -07:00
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}`);
2022-05-20 09:31:58 -07:00
let cronTime;
if (schedule === '@service') {
2022-05-20 09:31:58 -07:00
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
}
2024-04-19 18:19:41 +02:00
const cronJob = CronJob.from({
2022-05-20 09:31:58 -07:00
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
});
2020-08-18 19:08:37 -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) {
2015-10-18 08:40:24 -07:00
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appState, 'object');
2015-10-18 08:40:24 -07:00
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
2020-08-18 19:08:37 -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
}
2020-08-18 19:08:37 -07:00
}
2015-10-18 08:40:24 -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();
2015-10-18 08:40:24 -07:00
2021-09-27 14:21:42 -07:00
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)}`);
2015-10-18 08:40:24 -07:00
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;
2021-09-27 14:21:42 -07:00
const schedulerConfig = apps.getSchedulerConfig(app);
2015-10-18 08:40:24 -07:00
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
}
2020-08-18 21:15:54 -07:00
debug(`sync: clearing jobs of ${app.id} (${app.fqdn})`);
2015-12-23 13:23:47 -08:00
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
2024-03-12 17:54:51 +01: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 };
}
2015-10-18 08:40:24 -07:00
}
2026-02-14 15:43:24 +01:00
export default {
sync,
deleteJobs,
suspendAppJobs,
resumeAppJobs
};