Files
cloudron-box/src/scheduler.js

170 lines
6.9 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
sync,
suspendJobs,
resumeJobs
};
2019-08-30 13:12:49 -07:00
let apps = require('./apps.js'),
assert = require('assert'),
async = require('async'),
BoxError = require('./boxerror.js'),
constants = require('./constants.js'),
CronJob = require('cron').CronJob,
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'),
_ = require('underscore');
// appId -> { containerId, schedulerConfig (manifest), cronjobs }
let gState = { };
let 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 suspendJobs(appId) {
debug(`suspendJobs: ${appId}`);
gSuspendedAppIds.add(appId);
}
function resumeJobs(appId) {
debug(`resumeJobs: ${appId}`);
gSuspendedAppIds.delete(appId);
}
function runTask(appId, taskName, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof taskName, 'string');
assert.strictEqual(typeof callback, 'function');
const JOB_MAX_TIME = 30 * 60 * 1000; // 30 minutes
const containerName = `${appId}-${taskName}`;
2015-10-20 10:16:59 -07:00
if (gSuspendedAppIds.has(appId)) return callback();
apps.get(appId, function (error, app) {
if (error) return callback(error);
if (app.installationState !== apps.ISTATE_INSTALLED || app.runState !== apps.RSTATE_RUNNING || app.health !== apps.HEALTH_HEALTHY) return callback();
2020-08-18 21:40:10 -07:00
docker.inspectByName(containerName, function (error, data) {
if (!error && data && data.State.Running === true) {
const jobStartTime = new Date(data.State.StartedAt); // iso 8601
if (new Date() - jobStartTime < JOB_MAX_TIME) return callback();
}
docker.restartContainer(containerName, callback);
2015-10-19 19:04:53 -07:00
});
});
}
function createJobs(app, schedulerConfig, callback) {
assert.strictEqual(typeof app, 'object');
assert(schedulerConfig && typeof schedulerConfig === 'object');
2018-02-27 13:50:29 -08:00
assert.strictEqual(typeof callback, 'function');
const appId = app.id;
let jobs = { };
async.eachSeries(Object.keys(schedulerConfig), function (taskName, iteratorDone) {
const task = schedulerConfig[taskName];
const randomSecond = Math.floor(60*Math.random()); // don't start all crons to decrease memory pressure
const cronTime = (constants.TEST ? '*/5 ' : `${randomSecond} `) + task.schedule; // time ticks faster in tests
const containerName = `${app.id}-${taskName}`;
const cmd = schedulerConfig[taskName].command;
2020-08-18 23:53:14 -07:00
// stopJobs only deletes jobs since previous run. This means that when box code restarts, none of the containers
// are removed. The deleteContainer here ensures we re-create the cron containers with the latest config
docker.deleteContainer(containerName, function ( /* ignoredError */) {
docker.createSubcontainer(app, containerName, [ '/bin/sh', '-c', cmd ], { } /* options */, function (error) {
if (error && error.reason !== BoxError.ALREADY_EXISTS) return iteratorDone(error);
debug(`createJobs: ${taskName} (${app.fqdn}) will run in container ${containerName}`);
2020-09-01 11:14:29 -07:00
var cronJob = new CronJob({
cronTime: cronTime, // at this point, the pattern has been validated
onTick: () => runTask(appId, taskName, (error) => { // 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
});
jobs[taskName] = cronJob;
iteratorDone();
});
});
}, function (error) {
callback(error, jobs);
});
}
function stopJobs(appId, appState, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appState, 'object');
2015-10-20 12:49:02 -07:00
assert.strictEqual(typeof callback, 'function');
if (!appState) return callback();
async.eachSeries(Object.keys(appState.schedulerConfig), function (taskName, iteratorDone) {
if (appState.cronJobs && appState.cronJobs[taskName]) appState.cronJobs[taskName].stop();
2015-10-20 10:16:59 -07:00
const containerName = `${appId}-${taskName}`;
docker.deleteContainer(containerName, function (error) {
if (error) debug(`stopJobs: failed to delete task container with name ${containerName} : ${error.message}`);
iteratorDone();
});
}, callback);
}
function sync() {
apps.getAll(function (error, allApps) {
if (error) return debug(`sync: error getting app list. ${error.message}`);
2015-10-19 22:41:42 -07:00
var allAppIds = allApps.map(function (app) { return app.id; });
var removedAppIds = _.difference(Object.keys(gState), allAppIds);
if (removedAppIds.length !== 0) debug(`sync: stopping jobs of removed apps ${JSON.stringify(removedAppIds)}`);
async.eachSeries(removedAppIds, function (appId, iteratorDone) {
debug(`sync: removing jobs of ${appId}`);
stopJobs(appId, gState[appId], iteratorDone);
}, function (error) {
if (error) debug(`sync: error stopping jobs of removed apps: ${error.message}`);
gState = _.omit(gState, removedAppIds);
async.eachSeries(allApps, function (app, iteratorDone) {
var appState = gState[app.id] || null;
var schedulerConfig = app.manifest.addons ? app.manifest.addons.scheduler : null;
if (!appState && !schedulerConfig) return iteratorDone(); // nothing to do
if (appState && appState.cronJobs) { // we had created jobs for this app previously
if (_.isEqual(appState.schedulerConfig, schedulerConfig) && appState.containerId === app.containerId) return iteratorDone(); // nothing changed
}
2020-09-09 20:09:16 -07:00
debug(`sync: adding jobs of ${app.id} (${app.fqdn})`);
stopJobs(app.id, appState, function (error) {
if (error) debug(`sync: error stopping jobs of ${app.id} : ${error.message}`);
if (!schedulerConfig) { // updated app version removed scheduler addon
delete gState[app.id];
return iteratorDone();
}
2015-10-20 00:02:25 -07:00
createJobs(app, schedulerConfig, function (error, cronJobs) {
if (error) return iteratorDone(error); // if docker is down, the next sync() will recreate everything for this app
2015-11-22 21:17:17 -08:00
gState[app.id] = { containerId: app.containerId, schedulerConfig, cronJobs };
iteratorDone();
});
});
}, function (error) {
2020-09-01 11:14:29 -07:00
if (error) return debug('sync: error creating jobs', error.message);
2015-10-20 00:02:25 -07:00
});
});
});
}