Files
cloudron-box/src/cloudron.js

353 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,
2020-08-15 22:54:32 -07:00
runSystemChecks
};
const apps = require('./apps.js'),
appstore = require('./appstore.js'),
assert = require('assert'),
AuditSource = require('./auditsource.js'),
backups = require('./backups.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-17 14:04:29 -07:00
delay = require('delay'),
2021-08-13 17:22:28 -07:00
dns = require('./dns.js'),
dockerProxy = require('./dockerproxy.js'),
domains = require('./domains.js'),
2019-02-04 20:24:28 -08:00
eventlog = require('./eventlog.js'),
fs = require('fs'),
mail = require('./mail.js'),
notifications = require('./notifications.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'),
spawn = require('child_process').spawn,
split = require('split'),
sysinfo = require('./sysinfo.js'),
2018-12-10 20:20:53 -08:00
tasks = require('./tasks.js'),
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
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
await delay(30000);
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
// this configures collectd to collect backup storage metrics if filesystem is used. This is also triggerd when the settings change with the rest api
tasks.push(async function () {
const backupConfig = await settings.getBackupConfig();
await backups.configureCollectd(backupConfig);
});
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
2022-01-16 10:16:14 -08:00
const domainObject = await domains.get(settings.dashboardDomain());
await reverseProxy.writeDashboardConfig(domainObject);
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}`);
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];
const allSettings = await settings.list();
// be picky about what we send out here since this is sent for 'normal' users as well
return {
apiServerOrigin: settings.apiServerOrigin(),
webServerOrigin: settings.webServerOrigin(),
adminDomain: settings.dashboardDomain(),
adminFqdn: settings.dashboardFqdn(),
mailFqdn: settings.mailFqdn(),
version: constants.VERSION,
ubuntuVersion,
isDemo: settings.isDemo(),
cloudronName: allSettings[settings.CLOUDRON_NAME_KEY],
footer: branding.renderFooter(allSettings[settings.FOOTER_KEY] || constants.FOOTER),
features: appstore.getFeatures(),
profileLocked: allSettings[settings.PROFILE_CONFIG_KEY].lockUserProfiles,
mandatory2FA: allSettings[settings.PROFILE_CONFIG_KEY].mandatory2FA
};
}
async function reboot() {
await notifications.alert(notifications.ALERT_REBOOT, 'Reboot Required', '');
const [error] = await safe(shell.promises.sudo('reboot', [ REBOOT_CMD ], {}));
if (error) debug('reboot: could not reboot', 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 message = await mail.checkConfiguration();
await notifications.alert(notifications.ALERT_MAIL_STATUS, 'Email is not configured properly', message);
}
async function checkRebootRequired() {
const rebootRequired = await isRebootRequired();
await notifications.alert(notifications.ALERT_REBOOT, 'Reboot Required', rebootRequired ? 'To finish ubuntu security updates, a reboot is necessary.' : '');
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.');
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');
assert.strictEqual(typeof options.lines, 'number');
assert.strictEqual(typeof options.format, 'string');
assert.strictEqual(typeof options.follow, 'boolean');
2022-04-14 17:41:41 -05:00
const lines = options.lines === -1 ? '+1' : options.lines,
format = options.format || 'json',
follow = options.follow;
2018-06-11 20:09:38 +02:00
debug('Getting logs for %s as %s', unit, format);
let args = [ '--lines=' + lines ];
if (follow) args.push('--follow');
// need to handle box.log without subdir
if (unit === 'box') args.push(path.join(paths.LOG_DIR, 'box.log'));
2019-03-01 15:45:44 -08:00
else if (unit.startsWith('crash-')) args.push(path.join(paths.CRASH_LOG_DIR, unit.slice(6) + '.log'));
else throw new BoxError(BoxError.BAD_FIELD, `No such unit '${unit}'`);
2021-09-07 09:57:49 -07:00
const cp = spawn('/usr/bin/tail', args);
2021-09-07 09:57:49 -07:00
const transformStream = split(function mapper(line) {
if (format !== 'json') return line + '\n';
2021-09-07 09:57:49 -07:00
const data = line.split(' '); // logs are <ISOtimestamp> <msg>
let timestamp = (new Date(data[0])).getTime();
if (isNaN(timestamp)) timestamp = 0;
return JSON.stringify({
realtimeTimestamp: timestamp * 1000,
message: line.slice(data[0].length+1),
source: unit
}) + '\n';
});
transformStream.close = cp.kill.bind(cp, 'SIGKILL'); // closing stream kills the child process
cp.stdout.pipe(transformStream);
2021-09-07 09:57:49 -07:00
return transformStream;
}
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 domainObject = await domains.get(domain);
if (!domain) throw new BoxError(BoxError.NOT_FOUND, 'No such domain');
2021-08-20 09:19:44 -07:00
const fqdn = dns.fqdn(constants.DASHBOARD_LOCATION, domainObject);
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');
2021-08-20 09:19:44 -07:00
const taskId = await tasks.add(tasks.TASK_SETUP_DNS_AND_CERT, [ constants.DASHBOARD_LOCATION, 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}`);
2021-08-19 13:24:38 -07:00
const domainObject = await domains.get(domain);
if (!domain) throw new BoxError(BoxError.NOT_FOUND, 'No such domain');
2022-01-16 10:16:14 -08:00
await reverseProxy.writeDashboardConfig(domainObject);
2021-08-19 13:24:38 -07:00
const fqdn = dns.fqdn(constants.DASHBOARD_LOCATION, domainObject);
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);
safe(services.rebuildService('turn', auditSource), { debug }); // to update the realm variable
}
2021-07-12 23:35:30 -07:00
async function renewCerts(options, auditSource) {
2018-12-11 12:00:47 +01:00
assert.strictEqual(typeof options, 'object');
2018-12-10 20:20:53 -08:00
assert.strictEqual(typeof auditSource, 'object');
2021-07-12 23:35:30 -07:00
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 domainObject = await domains.get(domain);
const dashboardFqdn = dns.fqdn(subdomain, domainObject);
const ipv4 = await sysinfo.getServerIPv4();
2022-02-15 12:31:55 -08:00
const ipv6 = await sysinfo.getServerIPv6();
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}` });
await reverseProxy.ensureCertificate(dns.fqdn(subdomain, domainObject), domain, 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;
}