Files
cloudron-box/src/scheduler.js

170 lines
6.4 KiB
JavaScript
Raw Normal View History

Migrate codebase from CommonJS to ES Modules - Convert all require()/module.exports to import/export across 260+ files - Add "type": "module" to package.json to enable ESM by default - Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible - Convert eslint.config.js to ESM with sourceType: "module" - Replace __dirname/__filename with import.meta.dirname/import.meta.filename - Replace require.main === module with process.argv[1] === import.meta.filename - Remove 'use strict' directives (implicit in ESM) - Convert dynamic require() in switch statements to static import lookup maps (dns.js, domains.js, backupformats.js, backupsites.js, network.js) - Extract self-referencing exports.CONSTANT patterns into standalone const declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.) - Lazify SERVICES object in services.js to avoid circular dependency TDZ issues - Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests - Add _setMockApp() to ldapserver.js for ESM-safe test mocking - Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests - Convert backupupload.js to use dynamic imports so --check exits before loading the module graph (which requires BOX_ENV) - Update check-install to use ESM import for infra_version.js - Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations) - All 1315 tests passing Migration stats (AI-assisted using Cursor with Claude): - Wall clock time: ~3-4 hours - Assistant completions: ~80-100 - Estimated token usage: ~1-2M tokens Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
import apps from './apps.js';
import assert from 'node:assert';
import BoxError from './boxerror.js';
import cloudron from './cloudron.js';
Migrate codebase from CommonJS to ES Modules - Convert all require()/module.exports to import/export across 260+ files - Add "type": "module" to package.json to enable ESM by default - Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible - Convert eslint.config.js to ESM with sourceType: "module" - Replace __dirname/__filename with import.meta.dirname/import.meta.filename - Replace require.main === module with process.argv[1] === import.meta.filename - Remove 'use strict' directives (implicit in ESM) - Convert dynamic require() in switch statements to static import lookup maps (dns.js, domains.js, backupformats.js, backupsites.js, network.js) - Extract self-referencing exports.CONSTANT patterns into standalone const declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.) - Lazify SERVICES object in services.js to avoid circular dependency TDZ issues - Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests - Add _setMockApp() to ldapserver.js for ESM-safe test mocking - Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests - Convert backupupload.js to use dynamic imports so --check exits before loading the module graph (which requires BOX_ENV) - Update check-install to use ESM import for infra_version.js - Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations) - All 1315 tests passing Migration stats (AI-assisted using Cursor with Claude): - Wall clock time: ~3-4 hours - Assistant completions: ~80-100 - Estimated token usage: ~1-2M tokens Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
import constants from './constants.js';
import { CronJob } from 'cron';
import logger from './logger.js';
import docker from './docker.js';
2026-04-01 09:40:28 +02:00
import safe from '@cloudron/safetydance';
import _ from './underscore.js';
Migrate codebase from CommonJS to ES Modules - Convert all require()/module.exports to import/export across 260+ files - Add "type": "module" to package.json to enable ESM by default - Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible - Convert eslint.config.js to ESM with sourceType: "module" - Replace __dirname/__filename with import.meta.dirname/import.meta.filename - Replace require.main === module with process.argv[1] === import.meta.filename - Remove 'use strict' directives (implicit in ESM) - Convert dynamic require() in switch statements to static import lookup maps (dns.js, domains.js, backupformats.js, backupsites.js, network.js) - Extract self-referencing exports.CONSTANT patterns into standalone const declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.) - Lazify SERVICES object in services.js to avoid circular dependency TDZ issues - Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests - Add _setMockApp() to ldapserver.js for ESM-safe test mocking - Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests - Convert backupupload.js to use dynamic imports so --check exits before loading the module graph (which requires BOX_ENV) - Update check-install to use ESM import for infra_version.js - Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations) - All 1315 tests passing Migration stats (AI-assisted using Cursor with Claude): - Wall clock time: ~3-4 hours - Assistant completions: ~80-100 - Estimated token usage: ~1-2M tokens Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01:00
2026-03-12 23:23:23 +05:30
const { log } = logger('scheduler');
Migrate codebase from CommonJS to ES Modules - Convert all require()/module.exports to import/export across 260+ files - Add "type": "module" to package.json to enable ESM by default - Add migrations/package.json with "type": "commonjs" to keep db-migrate compatible - Convert eslint.config.js to ESM with sourceType: "module" - Replace __dirname/__filename with import.meta.dirname/import.meta.filename - Replace require.main === module with process.argv[1] === import.meta.filename - Remove 'use strict' directives (implicit in ESM) - Convert dynamic require() in switch statements to static import lookup maps (dns.js, domains.js, backupformats.js, backupsites.js, network.js) - Extract self-referencing exports.CONSTANT patterns into standalone const declarations (apps.js, services.js, locks.js, users.js, mail.js, etc.) - Lazify SERVICES object in services.js to avoid circular dependency TDZ issues - Add clearMailQueue() to mailer.js for ESM-safe queue clearing in tests - Add _setMockApp() to ldapserver.js for ESM-safe test mocking - Add _setMockResolve() wrapper to dig.js for ESM-safe DNS mocking in tests - Convert backupupload.js to use dynamic imports so --check exits before loading the module graph (which requires BOX_ENV) - Update check-install to use ESM import for infra_version.js - Convert scripts/ (hotfix, release, remote_hotfix.js, find-unused-translations) - All 1315 tests passing Migration stats (AI-assisted using Cursor with Claude): - Wall clock time: ~3-4 hours - Assistant completions: ~80-100 - Estimated token usage: ~1-2M tokens Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 09:53:14 +01: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
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) {
log(`suspendAppJobs: ${appId}`);
gSuspendedAppIds.add(appId);
}
function resumeAppJobs(appId) {
log(`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;
log(`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: log });
2021-08-25 19:41:46 -07:00
if (error && error.reason !== BoxError.ALREADY_EXISTS) continue;
log(`createJobs: ${taskName} (${app.fqdn}) will run in container ${containerName}`);
2021-08-25 19:41:46 -07:00
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 () => {
2026-02-18 08:18:37 +01:00
const [taskError] = await safe(runTask(appId, taskName)); // put the app id in closure, so we don't use the outdated app object by mistake
if (taskError) log(`could not run task ${taskName} : ${taskError.message}`);
2021-08-25 19:41:46 -07:00
},
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) log(`deleteAppJobs: failed to delete task container with name ${containerName} : ${error.message}`);
}
}
async function deleteJobs() {
for (const appId of Object.keys(gState)) {
log(`deleteJobs: removing jobs of ${appId}`);
const [error] = await safe(deleteAppJobs(appId, gState[appId]));
if (error) log(`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) log(`sync: stopping jobs of removed apps ${JSON.stringify(removedAppIds)}`);
2021-08-25 19:41:46 -07:00
for (const appId of removedAppIds) {
log(`sync: removing jobs of ${appId}`);
const [error] = await safe(deleteAppJobs(appId, gState[appId]));
if (error) log(`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
}
log(`sync: clearing jobs of ${app.id} (${app.fqdn})`);
const [error] = await safe(deleteAppJobs(app.id, appState));
if (error) log(`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 };
}
}
export default {
sync,
deleteJobs,
suspendAppJobs,
resumeAppJobs
};