Files
cloudron-box/src/scheduler.js

158 lines
5.7 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
sync: sync
};
2019-08-30 13:12:49 -07:00
let apps = require('./apps.js'),
assert = require('assert'),
async = require('async'),
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 -> { schedulerConfig (manifest), cronjobs }
var gState = { };
function sync() {
apps.getAll(function (error, allApps) {
if (error) return debug(`sync: error getting app list. ${error.message}`);
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)}`);
2015-10-19 22:41:42 -07:00
async.eachSeries(removedAppIds, function (appId, iteratorDone) {
stopJobs(appId, gState[appId], iteratorDone);
2015-10-19 22:41:42 -07:00
}, function (error) {
if (error) debug(`sync: error stopping jobs of removed apps: ${error.message}`);
gState = _.omit(gState, removedAppIds);
2015-10-19 22:41:42 -07:00
async.eachSeries(allApps, function (app, iteratorDone) {
var appState = gState[app.id] || null;
2017-03-26 21:55:31 -07:00
var schedulerConfig = app.manifest.addons ? app.manifest.addons.scheduler : null;
2015-10-20 00:02:25 -07:00
if (!appState && !schedulerConfig) return iteratorDone(); // nothing changed
2015-10-20 10:16:59 -07:00
if (appState && _.isEqual(appState.schedulerConfig, schedulerConfig) && appState.cronJobs) {
return iteratorDone(); // nothing changed
}
stopJobs(app.id, appState, function (error) {
if (error) debug(`sync: error stopping jobs of ${app.id} : ${error.message}`);
if (!schedulerConfig) {
delete gState[app.id];
return iteratorDone();
}
gState[app.id] = {
schedulerConfig: schedulerConfig,
2018-02-27 13:50:29 -08:00
cronJobs: createCronJobs(app, schedulerConfig)
};
iteratorDone();
});
});
2015-10-19 19:04:53 -07:00
});
});
}
function killContainer(containerName, callback) {
2018-02-27 13:50:29 -08:00
assert.strictEqual(typeof containerName, 'string');
assert.strictEqual(typeof callback, 'function');
async.series([
docker.stopContainerByName.bind(null, containerName),
docker.deleteContainerByName.bind(null, containerName)
], function (error) {
if (error) debug(`killContainer: failed to kill task with name ${containerName} : ${error.message}`);
callback(error);
});
}
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) {
2015-10-20 10:16:59 -07:00
if (appState.cronJobs && appState.cronJobs[taskName]) { // could be null across restarts
appState.cronJobs[taskName].stop();
}
2018-02-27 13:50:29 -08:00
killContainer(`${appId}-${taskName}`, iteratorDone);
2015-10-19 22:41:42 -07:00
}, callback);
}
2018-02-27 13:50:29 -08:00
function createCronJobs(app, schedulerConfig) {
assert.strictEqual(typeof app, 'object');
2015-10-20 09:44:46 -07:00
assert(schedulerConfig && typeof schedulerConfig === 'object');
const appId = app.id;
2015-10-19 22:41:42 -07:00
var jobs = { };
Object.keys(schedulerConfig).forEach(function (taskName) {
var task = schedulerConfig[taskName];
const randomSecond = Math.floor(60*Math.random()); // don't start all crons to decrease memory pressure
var cronTime = (constants.TEST ? '*/5 ' : `${randomSecond} `) + task.schedule; // time ticks faster in tests
2015-10-20 11:33:19 -07:00
2015-10-19 22:41:42 -07:00
var cronJob = new CronJob({
2015-10-20 11:33:19 -07:00
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;
});
2015-10-19 22:41:42 -07:00
return jobs;
}
2018-02-27 13:50:29 -08:00
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
apps.get(appId, function (error, app) {
if (error) return callback(error);
2019-08-30 13:12:49 -07:00
if (app.installationState !== apps.ISTATE_INSTALLED || app.runState !== apps.RSTATE_RUNNING || app.health !== apps.HEALTH_HEALTHY) {
return callback();
}
2018-02-27 13:50:29 -08:00
const containerName = `${app.id}-${taskName}`;
docker.inspectByName(containerName, function (err, data) {
if (!err && data && data.State.Running === true) {
const jobStartTime = new Date(data.State.StartedAt); // iso 8601
2020-05-24 11:35:31 -07:00
if (new Date() - jobStartTime < JOB_MAX_TIME) return callback();
}
2015-10-20 00:02:25 -07:00
killContainer(containerName, function (error) {
2015-11-22 21:17:17 -08:00
if (error) return callback(error);
2018-02-27 13:50:29 -08:00
const cmd = gState[appId].schedulerConfig[taskName].command;
2015-11-22 21:17:17 -08:00
// NOTE: if you change container name here, fix addons.js to return correct container names
docker.createSubcontainer(app, containerName, [ '/bin/sh', '-c', cmd ], { } /* options */, function (error, container) {
if (error) return callback(error);
docker.startContainer(container.id, callback);
});
2015-10-20 00:02:25 -07:00
});
});
});
}