Files
cloudron-box/src/cloudron.js

353 lines
12 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
initialize: initialize,
uninitialize: uninitialize,
getConfig: getConfig,
getLogs: getLogs,
reboot: reboot,
isRebootRequired: isRebootRequired,
2015-10-27 16:00:31 -07:00
2018-01-29 15:47:26 -08:00
onActivated: onActivated,
prepareDashboardDomain: prepareDashboardDomain,
2018-12-08 18:18:45 -08:00
setDashboardDomain: setDashboardDomain,
setDashboardAndMailDomain: setDashboardAndMailDomain,
2018-12-10 20:20:53 -08:00
renewCerts: renewCerts,
setupDashboard: setupDashboard,
runSystemChecks: runSystemChecks,
};
var apps = require('./apps.js'),
assert = require('assert'),
async = require('async'),
auditSource = require('./auditsource.js'),
backups = require('./backups.js'),
2019-10-22 14:06:19 -07:00
BoxError = require('./boxerror.js'),
clients = require('./clients.js'),
constants = require('./constants.js'),
2017-01-09 11:00:09 -08:00
cron = require('./cron.js'),
debug = require('debug')('box:cloudron'),
domains = require('./domains.js'),
DomainsError = require('./domains.js').DomainsError,
2019-02-04 20:24:28 -08:00
eventlog = require('./eventlog.js'),
2019-05-07 09:34:23 -07:00
custom = require('./custom.js'),
fs = require('fs'),
mail = require('./mail.js'),
notifications = require('./notifications.js'),
os = require('os'),
path = require('path'),
paths = require('./paths.js'),
platform = require('./platform.js'),
reverseProxy = require('./reverseproxy.js'),
safe = require('safetydance'),
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'),
2019-10-22 14:06:19 -07:00
users = require('./users.js');
2018-07-31 11:35:23 -07:00
var REBOOT_CMD = path.join(__dirname, 'scripts/reboot.sh');
2019-10-22 14:06:19 -07:00
const NOOP_CALLBACK = function (error) { if (error) debug(error); };
function initialize(callback) {
assert.strictEqual(typeof callback, 'function');
runStartupTasks();
2019-05-08 15:24:37 -07:00
notifyUpdate(callback);
}
function uninitialize(callback) {
assert.strictEqual(typeof callback, 'function');
async.series([
cron.stopJobs,
platform.stop
], callback);
}
2017-11-22 21:31:30 -08:00
function onActivated(callback) {
assert.strictEqual(typeof callback, 'function');
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)
async.series([
platform.start,
2019-05-08 15:24:37 -07:00
cron.startJobs
], callback);
}
function notifyUpdate(callback) {
assert.strictEqual(typeof callback, 'function');
const version = safe.fs.readFileSync(paths.VERSION_FILE, 'utf8');
if (version === constants.VERSION) return callback();
eventlog.add(eventlog.ACTION_UPDATE_FINISH, auditSource.CRON, { errorMessage: '', oldVersion: version || 'dev', newVersion: constants.VERSION }, function (error) {
2019-10-22 14:06:19 -07:00
if (error) return callback(error);
tasks.setCompletedByType(tasks.TASK_UPDATE, { error: null }, function (error) {
2019-10-22 20:12:44 -07:00
if (error && error.reason !== BoxError.NOT_FOUND) return callback(error); // when hotfixing, task may not exist
safe.fs.writeFileSync(paths.VERSION_FILE, constants.VERSION, 'utf8');
callback();
});
});
}
// each of these tasks can fail. we will add some routes to fix/re-run them
function runStartupTasks() {
// configure nginx to be reachable by IP
reverseProxy.writeDefaultConfig(NOOP_CALLBACK);
// always generate webadmin config since we have no versioning mechanism for the ejs
if (settings.adminDomain()) reverseProxy.writeAdminConfig(settings.adminDomain(), NOOP_CALLBACK);
// check activation state and start the platform
users.isActivated(function (error, activated) {
if (error) return debug(error);
if (!activated) return debug('initialize: not activated yet'); // not activated
2017-11-22 21:31:30 -08:00
onActivated(NOOP_CALLBACK);
2017-11-22 21:31:30 -08:00
});
}
function getConfig(callback) {
assert.strictEqual(typeof callback, 'function');
settings.getAll(function (error, allSettings) {
2019-10-22 14:06:19 -07:00
if (error) return callback(error);
2018-01-02 13:05:30 -08:00
// be picky about what we send out here since this is sent for 'normal' users as well
2018-06-28 17:18:15 -07:00
callback(null, {
apiServerOrigin: settings.apiServerOrigin(),
webServerOrigin: settings.webServerOrigin(),
adminDomain: settings.adminDomain(),
adminFqdn: settings.adminFqdn(),
mailFqdn: settings.mailFqdn(),
version: constants.VERSION,
isDemo: settings.isDemo(),
2018-06-28 17:18:15 -07:00
memory: os.totalmem(),
provider: sysinfo.provider(),
2019-05-07 09:34:23 -07:00
cloudronName: allSettings[settings.CLOUDRON_NAME_KEY],
2019-05-10 15:53:34 -07:00
uiSpec: custom.uiSpec()
});
});
}
function reboot(callback) {
2018-11-25 14:57:17 -08:00
shell.sudo('reboot', [ REBOOT_CMD ], {}, callback);
}
function isRebootRequired(callback) {
assert.strictEqual(typeof callback, 'function');
// https://serverfault.com/questions/92932/how-does-ubuntu-keep-track-of-the-system-restart-required-flag-in-motd
callback(null, fs.existsSync('/var/run/reboot-required'));
}
// called from cron.js
function runSystemChecks() {
async.parallel([
checkBackupConfiguration,
2019-02-19 09:19:56 -08:00
checkMailStatus,
checkRebootRequired
], function (error) {
debug('runSystemChecks: done', error);
});
}
function checkBackupConfiguration(callback) {
assert.strictEqual(typeof callback, 'function');
debug('Checking backup configuration');
backups.checkConfiguration(function (error, message) {
if (error) return callback(error);
notifications.alert(notifications.ALERT_BACKUP_CONFIG, 'Backup configuration is unsafe', message, callback);
});
}
function checkMailStatus(callback) {
assert.strictEqual(typeof callback, 'function');
debug('checking mail status');
mail.checkConfiguration(function (error, message) {
if (error) return callback(error);
notifications.alert(notifications.ALERT_MAIL_STATUS, 'Email is not configured properly', message, callback);
});
}
2019-02-19 09:19:56 -08:00
function checkRebootRequired(callback) {
assert.strictEqual(typeof callback, 'function');
debug('checking if reboot required');
isRebootRequired(function (error, rebootRequired) {
if (error) return callback(error);
notifications.alert(notifications.ALERT_REBOOT, 'Reboot Required', rebootRequired ? 'To finish security updates, a [reboot](/#/system) is necessary.' : '', callback);
2019-02-19 09:19:56 -08:00
});
}
2018-06-11 20:09:38 +02:00
function getLogs(unit, options, callback) {
assert.strictEqual(typeof unit, 'string');
assert(options && typeof options === 'object');
assert.strictEqual(typeof callback, 'function');
assert.strictEqual(typeof options.lines, 'number');
assert.strictEqual(typeof options.format, 'string');
assert.strictEqual(typeof options.follow, 'boolean');
var 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'));
2019-10-22 14:06:19 -07:00
else return callback(new BoxError(BoxError.BAD_FIELD, 'No such unit', { field: 'unit' }));
var cp = spawn('/usr/bin/tail', args);
var transformStream = split(function mapper(line) {
if (format !== 'json') return line + '\n';
var data = line.split(' '); // logs are <ISOtimestamp> <msg>
var 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);
return callback(null, transformStream);
}
function prepareDashboardDomain(domain, auditSource, callback) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof callback, 'function');
debug(`prepareDashboardDomain: ${domain}`);
domains.get(domain, function (error, domainObject) {
2019-10-22 14:06:19 -07:00
if (error && error.reason === DomainsError.NOT_FOUND) return callback(new BoxError(BoxError.BAD_FIELD, 'No such domain', { field: 'domain' }));
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
const fqdn = domains.fqdn(constants.ADMIN_LOCATION, domainObject);
apps.getAll(function (error, result) {
2019-10-22 14:06:19 -07:00
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
const conflict = result.filter(app => app.fqdn === fqdn);
2019-10-22 14:06:19 -07:00
if (conflict.length) return callback(new BoxError(BoxError.BAD_STATE, 'Dashboard location conflicts with an existing app'));
tasks.add(tasks.TASK_PREPARE_DASHBOARD_DOMAIN, [ domain, auditSource ], function (error, taskId) {
2019-10-22 14:06:19 -07:00
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
tasks.startTask(taskId, {}, NOOP_CALLBACK);
callback(null, taskId);
});
});
});
}
// call this only pre activation since it won't start mail server
2019-02-04 20:24:28 -08:00
function setDashboardDomain(domain, auditSource, callback) {
assert.strictEqual(typeof domain, 'string');
2019-02-04 20:24:28 -08:00
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof callback, 'function');
2018-12-08 18:18:45 -08:00
debug(`setDashboardDomain: ${domain}`);
domains.get(domain, function (error, domainObject) {
2019-10-22 14:06:19 -07:00
if (error && error.reason === DomainsError.NOT_FOUND) return callback(new BoxError(BoxError.BAD_FIELD, 'No such domain', { field: 'domain' }));
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
2019-01-16 21:36:48 -08:00
reverseProxy.writeAdminConfig(domain, function (error) {
2019-10-22 14:06:19 -07:00
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
2019-01-16 21:36:48 -08:00
const fqdn = domains.fqdn(constants.ADMIN_LOCATION, domainObject);
async.series([
(done) => settings.setAdmin(domain, fqdn, done),
(done) => clients.addDefaultClients(settings.adminOrigin(), done)
], function (error) {
2019-10-22 14:06:19 -07:00
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
2019-01-16 21:36:48 -08:00
2019-02-04 20:24:28 -08:00
eventlog.add(eventlog.ACTION_DASHBOARD_DOMAIN_UPDATE, auditSource, { domain: domain, fqdn: fqdn });
2019-01-16 21:36:48 -08:00
callback(null);
});
});
});
}
2018-12-10 20:20:53 -08:00
// call this only post activation because it will restart mail server
function setDashboardAndMailDomain(domain, auditSource, callback) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof callback, 'function');
debug(`setDashboardAndMailDomain: ${domain}`);
setDashboardDomain(domain, auditSource, function (error) {
if (error) return callback(error);
mail.onMailFqdnChanged(NOOP_CALLBACK); // this will update dns and re-configure mail server
callback(null);
});
}
function setupDashboard(auditSource, progressCallback, callback) {
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof progressCallback, 'function');
assert.strictEqual(typeof callback, 'function');
async.series([
domains.prepareDashboardDomain.bind(null, settings.adminDomain(), auditSource, progressCallback),
setDashboardDomain.bind(null, settings.adminDomain(), auditSource)
], callback);
}
2018-12-10 20:20:53 -08:00
function renewCerts(options, auditSource, callback) {
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');
assert.strictEqual(typeof callback, 'function');
tasks.add(tasks.TASK_RENEW_CERTS, [ options, auditSource ], function (error, taskId) {
2019-10-22 14:06:19 -07:00
if (error) return callback(new BoxError(BoxError.INTERNAL_ERROR, error));
tasks.startTask(taskId, {}, NOOP_CALLBACK);
callback(null, taskId);
});
2018-12-10 20:20:53 -08:00
}