Files
cloudron-box/src/cron.js

298 lines
10 KiB
JavaScript
Raw Normal View History

'use strict';
// IMPORTANT: These patterns are together because they spin tasks which acquire a lock
// If the patterns overlap all the time, then the task may not ever get a chance to run!
// If you change this change dashboard patterns in settings.html
const DEFAULT_CLEANUP_BACKUPS_PATTERN = '00 30 1,3,5,23 * * *',
DEFAULT_AUTOUPDATE_PATTERN = '00 00 1,3,5,23 * * *';
exports = module.exports = {
startJobs,
stopJobs,
handleBackupPolicyChanged,
handleTimeZoneChanged,
handleAutoupdatePatternChanged,
handleDynamicDnsChanged,
handleExternalLdapChanged,
DEFAULT_AUTOUPDATE_PATTERN,
};
const appHealthMonitor = require('./apphealthmonitor.js'),
apps = require('./apps.js'),
assert = require('assert'),
AuditSource = require('./auditsource.js'),
backups = require('./backups.js'),
cloudron = require('./cloudron.js'),
constants = require('./constants.js'),
{ CronJob } = require('cron'),
debug = require('debug')('box:cron'),
domains = require('./domains.js'),
2018-01-25 14:03:42 -08:00
dyndns = require('./dyndns.js'),
externalLdap = require('./externalldap.js'),
2016-07-25 12:36:43 -07:00
eventlog = require('./eventlog.js'),
janitor = require('./janitor.js'),
2023-08-04 13:41:13 +05:30
mail = require('./mail.js'),
network = require('./network.js'),
paths = require('./paths.js'),
2023-08-29 06:11:12 +05:30
reverseProxy = require('./reverseproxy.js'),
2021-08-20 09:19:44 -07:00
safe = require('safetydance'),
scheduler = require('./scheduler.js'),
2019-11-21 12:58:06 -08:00
system = require('./system.js'),
2018-07-31 11:35:23 -07:00
updater = require('./updater.js'),
2021-01-31 20:47:33 -08:00
updateChecker = require('./updatechecker.js'),
_ = require('./underscore.js');
2021-01-31 20:47:33 -08:00
const gJobs = {
autoUpdater: null,
2017-11-27 12:40:13 -08:00
backup: null,
2020-08-19 21:39:58 -07:00
updateChecker: null,
systemChecks: null,
2023-08-04 13:41:13 +05:30
mailStatusCheck: null,
2019-08-19 13:50:44 -07:00
diskSpaceChecker: null,
2017-11-27 12:40:13 -08:00
certificateRenew: null,
cleanupBackups: null,
cleanupEventlog: null,
cleanupTokens: null,
dockerVolumeCleaner: null,
2018-11-10 00:18:56 -08:00
dynamicDns: null,
schedulerSync: null,
2022-11-09 15:21:38 +01:00
appHealthMonitor: null,
diskUsage: null,
externalLdapSyncer: null,
checkDomainConfigs: null
2017-11-27 12:40:13 -08:00
};
// cron format
// Seconds: 0-59
// Minutes: 0-59
// Hours: 0-23
// Day of Month: 1-31
// Months: 0-11
// Day of Week: 0-6
function getCronSeed() {
let hour = null;
let minute = null;
const seedData = safe.fs.readFileSync(paths.CRON_SEED_FILE, 'utf8') || '';
const parts = seedData.split(':');
if (parts.length === 2) {
hour = parseInt(parts[0]) || null;
minute = parseInt(parts[1]) || null;
}
if ((hour == null || hour < 0 || hour > 23) || (minute == null || minute < 0 || minute > 60)) {
2022-08-08 20:33:21 +02:00
hour = Math.floor(24 * Math.random());
minute = Math.floor(60 * Math.random());
debug(`getCronSeed: writing new cron seed file with ${hour}:${minute} to ${paths.CRON_SEED_FILE}`);
safe.fs.writeFileSync(paths.CRON_SEED_FILE, `${hour}:${minute}`);
}
return { hour, minute };
}
async function startJobs() {
const { hour, minute } = getCronSeed();
debug(`startJobs: starting cron jobs with hour ${hour} and minute ${minute}`);
2020-10-07 14:47:51 -07:00
gJobs.systemChecks = CronJob.from({
cronTime: `00 ${minute} 2 * * *`, // once a day. if you change this interval, change the notification messages with correct duration
2023-08-04 13:41:13 +05:30
onTick: async () => await safe(system.runSystemChecks(), { debug }),
start: true
});
gJobs.mailStatusCheck = CronJob.from({
2023-08-04 13:41:13 +05:30
cronTime: `00 ${minute} 2 * * *`, // once a day. if you change this interval, change the notification messages with correct duration
onTick: async () => await safe(mail.checkStatus(), { debug }),
start: true
});
gJobs.diskUsage = CronJob.from({
2022-11-09 15:21:38 +01:00
cronTime: `00 ${minute} 3 * * *`, // once a day
2023-08-26 07:57:01 +05:30
onTick: async () => await safe(system.startUpdateDiskUsage(), { debug }),
2022-11-09 15:21:38 +01:00
start: true
});
gJobs.diskSpaceChecker = CronJob.from({
2019-08-19 13:50:44 -07:00
cronTime: '00 30 * * * *', // every 30 minutes. if you change this interval, change the notification messages with correct duration
2021-09-13 11:29:55 -07:00
onTick: async () => await safe(system.checkDiskSpace(), { debug }),
start: true
2019-08-19 13:50:44 -07:00
});
// this is run separately from the update itself so that the user can disable automatic updates but can still get a notification
gJobs.updateCheckerJob = CronJob.from({
cronTime: `00 ${minute} 1,5,9,13,17,21,23 * * *`,
2021-09-13 11:29:55 -07:00
onTick: async () => await safe(updateChecker.checkForUpdates({ automatic: true }), { debug }),
start: true
});
gJobs.cleanupTokens = CronJob.from({
cronTime: '00 */30 * * * *', // every 30 minutes
2021-09-17 09:22:46 -07:00
onTick: async () => await safe(janitor.cleanupTokens(), { debug }),
start: true
});
gJobs.cleanupBackups = CronJob.from({
cronTime: DEFAULT_CLEANUP_BACKUPS_PATTERN,
onTick: async () => await safe(backups.startCleanupTask(AuditSource.CRON), { debug }),
start: true
});
gJobs.cleanupEventlog = CronJob.from({
cronTime: '00 */30 * * * *', // every 30 minutes
2023-02-21 10:38:03 +01:00
onTick: async () => await safe(eventlog.cleanup({ creationTime: new Date(Date.now() - 90 * 60 * 24 * 60 * 1000) }), { debug }), // 90 days ago
start: true
});
gJobs.dockerVolumeCleaner = CronJob.from({
cronTime: '00 00 */12 * * *', // every 12 hours
2021-09-17 09:22:46 -07:00
onTick: async () => await safe(janitor.cleanupDockerVolumes(), { debug }),
start: true
});
gJobs.schedulerSync = CronJob.from({
cronTime: constants.TEST ? '*/10 * * * * *' : '00 */1 * * * *', // every minute
2021-09-13 11:29:55 -07:00
onTick: async () => await safe(scheduler.sync(), { debug }),
start: true
});
// randomized per Cloudron based on hourlySeed
gJobs.certificateRenew = CronJob.from({
cronTime: `00 10 ${hour} * * *`,
2023-08-28 23:55:13 +02:00
onTick: async () => await safe(reverseProxy.startRenewCerts({}, AuditSource.CRON), { debug }),
start: true
});
2017-07-21 16:13:44 +02:00
gJobs.checkDomainConfigs = CronJob.from({
cronTime: `00 ${minute} 5 * * *`, // once a day
onTick: async () => await safe(domains.checkConfigs(AuditSource.CRON), { debug }),
start: true
});
gJobs.appHealthMonitor = CronJob.from({
cronTime: '*/10 * * * * *', // every 10 seconds
2021-09-13 11:29:55 -07:00
onTick: async () => await safe(appHealthMonitor.run(10), { debug }), // 10 is the max run time
start: true
});
await handleBackupPolicyChanged(await backups.getPolicy());
await handleAutoupdatePatternChanged(await updater.getAutoupdatePattern());
await handleDynamicDnsChanged(await network.getDynamicDns());
await handleExternalLdapChanged(await externalLdap.getConfig());
}
async function handleBackupPolicyChanged(value) {
assert.strictEqual(typeof value, 'object');
2023-08-04 11:24:28 +05:30
const tz = await cloudron.getTimeZone();
debug(`backupPolicyChanged: schedule ${value.schedule} (${tz})`);
if (gJobs.backup) gJobs.backup.stop();
2024-01-23 10:19:56 +01:00
gJobs.backup = null;
gJobs.backup = CronJob.from({
cronTime: value.schedule,
onTick: async () => await safe(backups.startBackupTask(AuditSource.CRON), { debug }),
start: true,
timeZone: tz
});
}
async function handleTimeZoneChanged(tz) {
assert.strictEqual(typeof tz, 'string');
debug('handleTimeZoneChanged: recreating all jobs');
await stopJobs();
await scheduler.deleteJobs(); // have to re-create with new tz
await startJobs();
}
async function handleAutoupdatePatternChanged(pattern) {
assert.strictEqual(typeof pattern, 'string');
const tz = await cloudron.getTimeZone();
debug(`autoupdatePatternChanged: pattern - ${pattern} (${tz})`);
if (gJobs.autoUpdater) gJobs.autoUpdater.stop();
2024-01-23 10:19:56 +01:00
gJobs.autoUpdater = null;
if (pattern === constants.AUTOUPDATE_PATTERN_NEVER) return;
gJobs.autoUpdater = CronJob.from({
cronTime: pattern,
2021-08-20 09:19:44 -07:00
onTick: async function() {
const updateInfo = updateChecker.getUpdateInfo();
// do box before app updates. for the off chance that the box logic fixes some app update logic issue
if (updateInfo.box && !updateInfo.box.unstable) {
2024-08-10 11:04:17 +02:00
debug('Starting box autoupdate to %j', updateInfo.box.version);
const [error] = await safe(updater.updateToLatest({ skipBackup: false }, AuditSource.CRON));
if (!error) return; // do not start app updates when a box update got scheduled
debug(`Failed to start box autoupdate task: ${error.message}`);
// fall through to update apps if box update never started (failed ubuntu or avx check)
}
const appUpdateInfo = _.omit(updateInfo, ['box']);
2021-01-31 20:46:55 -08:00
if (Object.keys(appUpdateInfo).length > 0) {
2024-08-10 11:04:17 +02:00
debug('Starting app autoupdate: %j', Object.keys(appUpdateInfo));
const [error] = await safe(apps.autoupdateApps(appUpdateInfo, AuditSource.CRON));
2021-08-31 13:12:14 -07:00
if (error) debug(`Failed to app autoupdate: ${error.message}`);
} else {
debug('No app auto updates available');
}
},
start: true,
timeZone: tz
});
}
function handleDynamicDnsChanged(enabled) {
2017-01-02 13:14:03 +01:00
assert.strictEqual(typeof enabled, 'boolean');
debug('Dynamic DNS setting changed to %s', enabled);
2024-01-23 10:19:56 +01:00
if (gJobs.dynamicDns) gJobs.dynamicDns.stop();
gJobs.dynamicDns = null;
if (!enabled) return;
gJobs.dynamicDns = CronJob.from({
2024-01-23 10:19:56 +01:00
// until we can be smarter about actual IP changes, lets ensure it every 10minutes
cronTime: '00 */10 * * * *',
onTick: async () => { await safe(dyndns.refreshDns(AuditSource.CRON), { debug }); },
start: true
});
2017-01-02 13:14:03 +01:00
}
async function handleExternalLdapChanged(config) {
assert.strictEqual(typeof config, 'object');
2024-01-23 10:19:56 +01:00
if (gJobs.externalLdapSyncer) gJobs.externalLdapSyncer.stop();
gJobs.externalLdapSyncer = null;
if (config.provider === 'noop') return;
gJobs.externalLdapSyncer = CronJob.from({
2024-01-23 10:19:56 +01:00
cronTime: '00 00 */4 * * *', // every 4 hours
onTick: async () => await safe(externalLdap.startSyncer(AuditSource.CRON), { debug }),
start: true
});
}
2021-09-07 09:57:49 -07:00
async function stopJobs() {
for (const job in gJobs) {
2017-11-27 12:40:13 -08:00
if (!gJobs[job]) continue;
gJobs[job].stop();
gJobs[job] = null;
}
}