Files
cloudron-box/src/cloudron.js

357 lines
13 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
2020-08-15 22:54:32 -07:00
initialize,
uninitialize,
getConfig,
getLogs,
2020-08-15 22:54:32 -07:00
reboot,
isRebootRequired,
2015-10-27 16:00:31 -07:00
2020-08-15 22:54:32 -07:00
onActivated,
2018-01-29 15:47:26 -08:00
setupDnsAndCert,
2020-08-15 22:54:32 -07:00
prepareDashboardDomain,
setDashboardDomain,
updateDashboardDomain,
renewCerts,
syncDnsRecords,
2022-10-12 10:26:21 +02:00
updateDiskUsage,
2023-01-23 17:56:01 +01:00
runSystemChecks,
getBlockDevices
};
const apps = require('./apps.js'),
appstore = require('./appstore.js'),
assert = require('assert'),
AuditSource = require('./auditsource.js'),
2019-10-22 14:06:19 -07:00
BoxError = require('./boxerror.js'),
branding = require('./branding.js'),
constants = require('./constants.js'),
2017-01-09 11:00:09 -08:00
cron = require('./cron.js'),
debug = require('debug')('box:cloudron'),
2021-08-13 17:22:28 -07:00
dns = require('./dns.js'),
dockerProxy = require('./dockerproxy.js'),
2019-02-04 20:24:28 -08:00
eventlog = require('./eventlog.js'),
fs = require('fs'),
logs = require('./logs.js'),
mail = require('./mail.js'),
network = require('./network.js'),
notifications = require('./notifications.js'),
oidc = require('./oidc.js'),
path = require('path'),
paths = require('./paths.js'),
platform = require('./platform.js'),
reverseProxy = require('./reverseproxy.js'),
safe = require('safetydance'),
services = require('./services.js'),
settings = require('./settings.js'),
shell = require('./shell.js'),
2018-12-10 20:20:53 -08:00
tasks = require('./tasks.js'),
2023-05-14 10:53:50 +02:00
timers = require('timers/promises'),
2021-09-17 09:22:46 -07:00
users = require('./users.js');
const REBOOT_CMD = path.join(__dirname, 'scripts/reboot.sh');
2021-06-03 11:42:32 -07:00
async function initialize() {
safe(runStartupTasks(), { debug }); // background
2019-05-08 15:24:37 -07:00
2021-06-03 11:42:32 -07:00
await notifyUpdate();
}
2021-09-07 09:57:49 -07:00
async function uninitialize() {
await cron.stopJobs();
await dockerProxy.stop();
2021-09-07 09:57:49 -07:00
await platform.stopAllTasks();
}
2021-09-17 09:22:46 -07:00
async function onActivated(options) {
2021-02-24 15:03:49 -08:00
assert.strictEqual(typeof options, 'object');
2017-11-22 21:31:30 -08:00
debug('onActivated: running post activation tasks');
2017-11-22 21:31:30 -08:00
// Starting the platform after a user is available means:
// 1. mail bounces can now be sent to the cloudron owner
// 2. the restore code path can run without sudo (since mail/ is non-root)
2021-09-17 09:22:46 -07:00
await platform.start(options);
await cron.startJobs();
await dockerProxy.start(); // this relies on the 'cloudron' docker network interface to be available
await oidc.start(); // this requires dashboardFqdn to be set
2021-09-17 09:22:46 -07:00
// disable responding to api calls via IP to not leak domain info. this is carefully placed as the last item, so it buys
// the UI some time to query the dashboard domain in the restore code path
2023-05-14 10:53:50 +02:00
await timers.setTimeout(30000);
2021-09-17 09:22:46 -07:00
await reverseProxy.writeDefaultConfig({ activated :true });
}
2021-06-03 11:42:32 -07:00
async function notifyUpdate() {
const version = safe.fs.readFileSync(paths.VERSION_FILE, 'utf8');
2021-06-03 11:42:32 -07:00
if (version === constants.VERSION) return;
if (!version) {
await eventlog.add(eventlog.ACTION_INSTALL_FINISH, AuditSource.CRON, { version: constants.VERSION });
} else {
await eventlog.add(eventlog.ACTION_UPDATE_FINISH, AuditSource.CRON, { errorMessage: '', oldVersion: version || 'dev', newVersion: constants.VERSION });
const [error] = await safe(tasks.setCompletedByType(tasks.TASK_UPDATE, { error: null }));
if (error && error.reason !== BoxError.NOT_FOUND) throw error; // when hotfixing, task may not exist
}
2021-07-12 23:35:30 -07:00
safe.fs.writeFileSync(paths.VERSION_FILE, constants.VERSION, 'utf8');
}
// each of these tasks can fail. we will add some routes to fix/re-run them
2021-09-17 09:22:46 -07:00
async function runStartupTasks() {
const tasks = [];
2021-09-17 09:22:46 -07:00
// stop all the systemd tasks
tasks.push(platform.stopAllTasks);
2021-09-17 09:22:46 -07:00
// always generate webadmin config since we have no versioning mechanism for the ejs
tasks.push(async function () {
if (!settings.dashboardDomain()) return;
2020-09-02 17:32:31 -07:00
await reverseProxy.writeDashboardConfig(settings.dashboardDomain());
2021-09-17 09:22:46 -07:00
});
tasks.push(async function () {
2020-09-02 17:32:31 -07:00
// check activation state and start the platform
2021-09-17 09:22:46 -07:00
const activated = await users.isActivated();
// configure nginx to be reachable by IP when not activated. for the moment, the IP based redirect exists even after domain is setup
// just in case user forgot or some network error happenned in the middle (then browser refresh takes you to activation page)
// we remove the config as a simple security measure to not expose IP <-> domain
if (!activated) {
debug('runStartupTasks: not activated. generating IP based redirection config');
return await reverseProxy.writeDefaultConfig({ activated: false });
}
2017-11-22 21:31:30 -08:00
2021-09-17 09:22:46 -07:00
await onActivated({});
2017-11-22 21:31:30 -08:00
});
2021-09-17 09:22:46 -07:00
// we used to run tasks in parallel but simultaneous nginx reloads was causing issues
for (let i = 0; i < tasks.length; i++) {
const [error] = await safe(tasks[i]());
if (error) debug(`Startup task at index ${i} failed: ${error.message} ${error.stack}`);
2021-09-17 09:22:46 -07:00
}
2017-11-22 21:31:30 -08:00
}
async function getConfig() {
2021-05-18 14:37:11 -07:00
const release = safe.fs.readFileSync('/etc/lsb-release', 'utf-8');
if (release === null) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
2021-05-18 14:37:11 -07:00
const ubuntuVersion = release.match(/DISTRIB_DESCRIPTION="(.*)"/)[1];
2023-08-03 09:03:47 +05:30
const profileConfig = await users.getProfileConfig();
// be picky about what we send out here since this is sent for 'normal' users as well
return {
apiServerOrigin: settings.apiServerOrigin(),
webServerOrigin: settings.webServerOrigin(),
consoleServerOrigin: settings.consoleServerOrigin(),
adminDomain: settings.dashboardDomain(),
adminFqdn: settings.dashboardFqdn(),
mailFqdn: settings.mailFqdn(),
version: constants.VERSION,
ubuntuVersion,
isDemo: settings.isDemo(),
cloudronName: await branding.getCloudronName(),
footer: await branding.renderFooter(),
features: appstore.getFeatures(),
2023-08-03 09:03:47 +05:30
profileLocked: profileConfig.lockUserProfiles,
mandatory2FA: profileConfig.mandatory2FA,
};
}
async function reboot() {
2023-03-26 14:18:37 +02:00
await notifications.clearAlert(notifications.ALERT_REBOOT, 'Reboot Required');
const [error] = await safe(shell.promises.sudo('reboot', [ REBOOT_CMD ], {}));
if (error) debug('reboot: could not reboot. %o', error);
}
async function isRebootRequired() {
// https://serverfault.com/questions/92932/how-does-ubuntu-keep-track-of-the-system-restart-required-flag-in-motd
return fs.existsSync('/var/run/reboot-required');
}
2021-09-17 09:22:46 -07:00
async function runSystemChecks() {
2021-06-17 13:51:29 -07:00
debug('runSystemChecks: checking status');
2021-09-17 09:22:46 -07:00
const checks = [
checkMailStatus(),
checkRebootRequired(),
checkUbuntuVersion()
];
await Promise.allSettled(checks);
}
2021-08-17 15:45:57 -07:00
async function checkMailStatus() {
const result = await mail.checkConfiguration();
if (result.status) {
await notifications.clearAlert(notifications.ALERT_MAIL_STATUS, 'Email is not configured properly');
} else {
await notifications.alert(notifications.ALERT_MAIL_STATUS, 'Email is not configured properly', result.message, { persist: true });
}
}
async function checkRebootRequired() {
const rebootRequired = await isRebootRequired();
2023-03-26 14:18:37 +02:00
if (rebootRequired) {
await notifications.alert(notifications.ALERT_REBOOT, 'Reboot Required', 'To finish ubuntu security updates, a reboot is necessary.', { persist: true });
2023-03-26 14:18:37 +02:00
} else {
await notifications.clearAlert(notifications.ALERT_REBOOT, 'Reboot Required');
}
2019-02-19 09:19:56 -08:00
}
async function checkUbuntuVersion() {
2021-05-18 14:37:11 -07:00
const isXenial = fs.readFileSync('/etc/lsb-release', 'utf-8').includes('16.04');
if (!isXenial) return;
2021-05-18 14:37:11 -07:00
await notifications.alert(notifications.ALERT_UPDATE_UBUNTU, 'Ubuntu upgrade required', 'Ubuntu 16.04 has reached end of life and will not receive security and maintenance updates. Please follow https://docs.cloudron.io/guides/upgrade-ubuntu-18/ to upgrade to Ubuntu 18 at the earliest.', { persist: true });
2021-05-18 14:37:11 -07:00
}
2021-09-07 09:57:49 -07:00
async function getLogs(unit, options) {
2018-06-11 20:09:38 +02:00
assert.strictEqual(typeof unit, 'string');
assert(options && typeof options === 'object');
debug(`Getting logs for ${unit}`);
let logFile = '';
if (unit === 'box') logFile = path.join(paths.LOG_DIR, 'box.log'); // box.log is at the top
else throw new BoxError(BoxError.BAD_FIELD, `No such unit '${unit}'`);
const cp = logs.tail([logFile], { lines: options.lines, follow: options.follow });
const logStream = new logs.LogStream({ format: options.format || 'json', source: unit });
logStream.close = cp.kill.bind(cp, 'SIGKILL'); // hook for caller. closing stream kills the child process
cp.stdout.pipe(logStream);
return logStream;
}
2021-08-20 09:19:44 -07:00
async function prepareDashboardDomain(domain, auditSource) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
debug(`prepareDashboardDomain: ${domain}`);
2021-08-20 09:19:44 -07:00
if (settings.isDemo()) throw new BoxError(BoxError.CONFLICT, 'Not allowed in demo mode');
const fqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domain);
2021-08-30 14:00:50 -07:00
const result = await apps.list();
if (result.some(app => app.fqdn === fqdn)) throw new BoxError(BoxError.BAD_STATE, 'Dashboard location conflicts with an existing app');
2022-07-14 15:18:17 +05:30
const taskId = await tasks.add(tasks.TASK_SETUP_DNS_AND_CERT, [ constants.DASHBOARD_SUBDOMAIN, domain, auditSource ]);
2021-09-17 09:22:46 -07:00
tasks.startTask(taskId, {});
2021-08-20 09:19:44 -07:00
return taskId;
}
// call this only pre activation since it won't start mail server
2021-08-19 13:24:38 -07:00
async function setDashboardDomain(domain, auditSource) {
assert.strictEqual(typeof domain, 'string');
2019-02-04 20:24:28 -08:00
assert.strictEqual(typeof auditSource, 'object');
2018-12-08 18:18:45 -08:00
debug(`setDashboardDomain: ${domain}`);
await reverseProxy.writeDashboardConfig(domain);
const fqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domain);
2021-08-19 13:24:38 -07:00
await settings.setDashboardLocation(domain, fqdn);
2019-01-16 21:36:48 -08:00
await safe(appstore.updateCloudron({ domain }), { debug });
2021-08-19 13:24:38 -07:00
await eventlog.add(eventlog.ACTION_DASHBOARD_DOMAIN_UPDATE, auditSource, { domain, fqdn });
}
2018-12-10 20:20:53 -08:00
// call this only post activation because it will restart mail server
2021-08-19 13:24:38 -07:00
async function updateDashboardDomain(domain, auditSource) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
debug(`updateDashboardDomain: ${domain}`);
2021-08-19 13:24:38 -07:00
if (settings.isDemo()) throw new BoxError(BoxError.CONFLICT, 'Not allowed in demo mode');
2021-08-19 13:24:38 -07:00
await setDashboardDomain(domain, auditSource);
// mark apps using oidc addon to be reconfigured
const [, installedApps] = await safe(apps.list());
await safe(apps.configureInstalledApps(installedApps.filter((a) => !!a.manifest.addons.oidc), auditSource));
await safe(services.rebuildService('turn', auditSource), { debug }); // to update the realm variable
await oidc.stop();
await oidc.start();
}
async function renewCerts(options, auditSource) {
assert.strictEqual(typeof options, 'object');
2018-12-10 20:20:53 -08:00
assert.strictEqual(typeof auditSource, 'object');
const taskId = await tasks.add(tasks.TASK_CHECK_CERTS, [ options, auditSource ]);
2021-09-17 09:22:46 -07:00
tasks.startTask(taskId, {});
2021-07-12 23:35:30 -07:00
return taskId;
2018-12-10 20:20:53 -08:00
}
async function setupDnsAndCert(subdomain, domain, auditSource, progressCallback) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof progressCallback, 'function');
const dashboardFqdn = dns.fqdn(subdomain, domain);
const ipv4 = await network.getIPv4();
const ipv6 = await network.getIPv6();
progressCallback({ percent: 20, message: `Updating DNS of ${dashboardFqdn}` });
await dns.upsertDnsRecords(subdomain, domain, 'A', [ ipv4 ]);
2022-02-15 12:31:55 -08:00
if (ipv6) await dns.upsertDnsRecords(subdomain, domain, 'AAAA', [ ipv6 ]);
progressCallback({ percent: 40, message: `Waiting for DNS of ${dashboardFqdn}` });
await dns.waitForDnsRecord(subdomain, domain, 'A', ipv4, { interval: 30000, times: 50000 });
2022-02-15 12:31:55 -08:00
if (ipv6) await dns.waitForDnsRecord(subdomain, domain, 'AAAA', ipv6, { interval: 30000, times: 50000 });
progressCallback({ percent: 60, message: `Getting certificate of ${dashboardFqdn}` });
const location = { subdomain, domain, fqdn: dashboardFqdn, type: apps.LOCATION_TYPE_DASHBOARD, certificate: null };
await reverseProxy.ensureCertificate(location, {}, auditSource);
}
2021-07-12 23:35:30 -07:00
async function syncDnsRecords(options) {
assert.strictEqual(typeof options, 'object');
2021-07-12 23:35:30 -07:00
const taskId = await tasks.add(tasks.TASK_SYNC_DNS_RECORDS, [ options ]);
2021-09-17 09:22:46 -07:00
tasks.startTask(taskId, {});
2021-07-12 23:35:30 -07:00
return taskId;
}
2022-10-12 10:26:21 +02:00
async function updateDiskUsage() {
const taskId = await tasks.add(tasks.TASK_UPDATE_DISK_USAGE, []);
tasks.startTask(taskId, {});
return taskId;
}
2023-01-23 17:56:01 +01:00
async function getBlockDevices() {
2023-05-08 11:30:21 +02:00
const info = safe.JSON.parse(safe.child_process.execSync('lsblk --paths --json --list --fs', { encoding: 'utf8' }));
if (!info) throw new BoxError(BoxError.INTERNAL_ERROR, safe.error.message);
2023-01-23 17:56:01 +01:00
const devices = info.blockdevices.filter(d => d.fstype === 'ext4' || d.fstype === 'xfs');
2023-01-23 17:56:01 +01:00
debug(`getBlockDevices: Found ${devices.length} devices. ${devices.map(d => d.name).join(', ')}`);
return devices.map(function (d) {
return {
path: d.name,
size: d.fsavail || 0,
type: d.fstype,
mountpoint: d.mountpoints ? d.mountpoints[0] : d.mountpoint // we only support one mountpoint here old lsblk only exposed one via .mountpoint
2023-01-23 17:56:01 +01:00
};
});
}