Files
cloudron-box/src/platform.js

323 lines
12 KiB
JavaScript
Raw Normal View History

2016-05-24 09:40:26 -07:00
'use strict';
exports = module.exports = {
start: start,
stop: stop,
handleCertChanged: handleCertChanged
2016-05-24 09:40:26 -07:00
};
var apps = require('./apps.js'),
2016-05-24 10:58:18 -07:00
assert = require('assert'),
2016-05-28 01:56:32 -07:00
async = require('async'),
config = require('./config.js'),
2016-05-24 09:40:26 -07:00
debug = require('debug')('box:platform'),
fs = require('fs'),
hat = require('./hat.js'),
2016-05-24 13:10:18 -07:00
infra = require('./infra_version.js'),
locker = require('./locker.js'),
mail = require('./mail.js'),
os = require('os'),
2016-05-24 09:40:26 -07:00
paths = require('./paths.js'),
reverseProxy = require('./reverseproxy.js'),
2016-05-24 13:10:18 -07:00
safe = require('safetydance'),
semver = require('semver'),
settings = require('./settings.js'),
2016-05-24 13:16:31 -07:00
shell = require('./shell.js'),
taskmanager = require('./taskmanager.js'),
util = require('util'),
_ = require('underscore');
2016-05-24 09:40:26 -07:00
var gPlatformReadyTimer = null;
var NOOP_CALLBACK = function (error) { if (error) debug(error); };
function start(callback) {
assert.strictEqual(typeof callback, 'function');
2016-09-03 11:46:57 -07:00
if (process.env.BOX_ENV === 'test' && !process.env.TEST_CREATE_INFRA) return callback();
2016-05-24 09:40:26 -07:00
debug('initializing addon infrastructure');
2016-05-24 13:10:18 -07:00
var existingInfra = { version: 'none' };
if (fs.existsSync(paths.INFRA_VERSION_FILE)) {
2016-05-24 13:10:18 -07:00
existingInfra = safe.JSON.parse(fs.readFileSync(paths.INFRA_VERSION_FILE, 'utf8'));
if (!existingInfra) existingInfra = { version: 'corrupt' };
}
// short-circuit for the restart case
if (_.isEqual(infra, existingInfra)) {
2016-05-24 13:10:18 -07:00
debug('platform is uptodate at version %s', infra.version);
updateAddons(function (error) {
if (error) return callback(error);
emitPlatformReady();
callback();
});
return;
}
2016-05-24 13:10:18 -07:00
debug('Updating infrastructure from %s to %s', existingInfra.version, infra.version);
var error = locker.lock(locker.OP_PLATFORM_START);
if (error) return callback(error);
2016-05-28 01:56:32 -07:00
async.series([
2016-07-25 00:39:57 -07:00
stopContainers.bind(null, existingInfra),
startAddons.bind(null, existingInfra),
2016-05-28 01:56:32 -07:00
removeOldImages,
startApps.bind(null, existingInfra),
fs.writeFile.bind(fs, paths.INFRA_VERSION_FILE, JSON.stringify(infra, null, 4)),
updateAddons
], function (error) {
if (error) return callback(error);
2016-06-21 10:37:12 -05:00
locker.unlock(locker.OP_PLATFORM_START);
emitPlatformReady();
callback();
});
2016-06-21 10:37:12 -05:00
}
function stop(callback) {
2016-06-21 10:37:12 -05:00
clearTimeout(gPlatformReadyTimer);
gPlatformReadyTimer = null;
exports.events = null;
taskmanager.pauseTasks(callback);
2016-06-21 10:37:12 -05:00
}
function updateAddons(callback) {
settings.getPlatformConfig(function (error, platformConfig) {
if (error) return callback(error);
for (var containerName of [ 'mysql', 'postgresql', 'mail', 'mongodb' ]) {
const containerConfig = platformConfig[containerName];
if (!containerConfig) continue;
if (!containerConfig.memory || !containerConfig.memorySwap) continue;
const cmd = `docker update --memory ${containerConfig.memory} --memory-swap ${containerConfig.memorySwap} ${containerName}`;
shell.execSync(`update${containerName}`, cmd);
}
2018-05-17 09:16:32 -07:00
callback();
});
}
function emitPlatformReady() {
// give some time for the platform to "settle". For example, mysql might still be initing the
// database dir and we cannot call service scripts until that's done.
// TODO: make this smarter to not wait for 15secs for the crash-restart case
gPlatformReadyTimer = setTimeout(function () {
debug('emitting platform ready');
gPlatformReadyTimer = null;
taskmanager.resumeTasks();
}, 15000);
}
2016-05-28 01:56:32 -07:00
function removeOldImages(callback) {
2016-05-24 13:16:31 -07:00
debug('removing old addon images');
for (var imageName in infra.images) {
if (imageName === 'redis') continue; // see #223
2016-05-24 13:16:31 -07:00
var image = infra.images[imageName];
2016-06-08 15:05:43 +02:00
debug('cleaning up images of %j', image);
2016-05-24 13:16:31 -07:00
var cmd = 'docker images "%s" | tail -n +2 | awk \'{ print $1 ":" $2 }\' | grep -v "%s" | xargs --no-run-if-empty docker rmi';
shell.execSync('removeOldImagesSync', util.format(cmd, image.repo, image.tag));
}
2016-05-28 01:56:32 -07:00
callback();
2016-05-24 13:16:31 -07:00
}
2016-07-25 00:39:57 -07:00
function stopContainers(existingInfra, callback) {
// TODO: be nice and stop addons cleanly (example, shutdown commands)
2016-07-25 00:39:57 -07:00
// always stop addons to restart them on any infra change, regardless of minor or major update
if (existingInfra.version !== infra.version) {
2016-07-25 09:38:31 -07:00
debug('stopping all containers for infra upgrade');
2016-07-25 00:39:57 -07:00
shell.execSync('stopContainers', 'docker ps -qa | xargs --no-run-if-empty docker rm -f');
} else {
assert(typeof infra.images, 'object');
var changedAddons = [ ];
for (var imageName in infra.images) {
if (imageName === 'redis') continue; // see #223
2016-07-25 09:38:31 -07:00
if (infra.images[imageName].tag !== existingInfra.images[imageName].tag) changedAddons.push(imageName);
2016-07-25 00:39:57 -07:00
}
2016-07-25 09:38:31 -07:00
debug('stopping addons for incremental infra update: %j', changedAddons);
// ignore error if container not found (and fail later) so that this code works across restarts
shell.execSync('stopContainers', 'docker rm -f ' + changedAddons.join(' ') + ' || true');
2016-07-25 00:39:57 -07:00
}
2016-05-28 01:56:32 -07:00
callback();
}
2016-05-24 10:58:18 -07:00
2016-06-14 15:49:24 -07:00
function startGraphite(callback) {
const tag = infra.images.graphite.tag;
const dataDir = paths.PLATFORM_DATA_DIR;
2016-06-14 15:49:24 -07:00
const cmd = `docker run --restart=always -d --name="graphite" \
--net cloudron \
--net-alias graphite \
2018-06-06 13:41:46 +02:00
--log-driver syslog \
--log-opt syslog-address=udp://127.0.0.1:2514 \
--log-opt syslog-format=rfc5424 \
--log-opt tag=graphite \
2016-06-14 15:49:24 -07:00
-m 75m \
--memory-swap 150m \
2017-04-25 15:21:23 +00:00
--dns 172.18.0.1 \
--dns-search=. \
2016-06-14 15:49:24 -07:00
-p 127.0.0.1:2003:2003 \
-p 127.0.0.1:2004:2004 \
-p 127.0.0.1:8000:8000 \
-v "${dataDir}/graphite:/app/data" \
--read-only -v /tmp -v /run "${tag}"`;
shell.execSync('startGraphite', cmd);
callback();
}
function startMysql(callback) {
const tag = infra.images.mysql.tag;
const dataDir = paths.PLATFORM_DATA_DIR;
2016-06-17 09:46:07 -05:00
const rootPassword = hat(8 * 128);
const memoryLimit = (1 + Math.round(os.totalmem()/(1024*1024*1024)/4)) * 256;
2016-06-14 15:49:24 -07:00
if (!safe.fs.writeFileSync(paths.ADDON_CONFIG_DIR + '/mysql_vars.sh',
'MYSQL_ROOT_PASSWORD=' + rootPassword +'\nMYSQL_ROOT_HOST=172.18.0.1', 'utf8')) {
2016-06-14 15:49:24 -07:00
return callback(new Error('Could not create mysql var file:' + safe.error.message));
}
const cmd = `docker run --restart=always -d --name="mysql" \
--net cloudron \
--net-alias mysql \
2018-06-06 13:41:46 +02:00
--log-driver syslog \
--log-opt syslog-address=udp://127.0.0.1:2514 \
--log-opt syslog-format=rfc5424 \
--log-opt tag=mysql \
-m ${memoryLimit}m \
--memory-swap ${memoryLimit * 2}m \
2017-04-25 15:21:23 +00:00
--dns 172.18.0.1 \
--dns-search=. \
2016-06-14 15:49:24 -07:00
-v "${dataDir}/mysql:/var/lib/mysql" \
-v "${dataDir}/addons/mysql_vars.sh:/etc/mysql/mysql_vars.sh:ro" \
--read-only -v /tmp -v /run "${tag}"`;
shell.execSync('startMysql', cmd);
setTimeout(callback, 5000);
2016-06-14 15:49:24 -07:00
}
function startPostgresql(callback) {
const tag = infra.images.postgresql.tag;
const dataDir = paths.PLATFORM_DATA_DIR;
2016-06-17 09:46:07 -05:00
const rootPassword = hat(8 * 128);
const memoryLimit = (1 + Math.round(os.totalmem()/(1024*1024*1024)/4)) * 256;
2016-06-14 15:49:24 -07:00
if (!safe.fs.writeFileSync(paths.ADDON_CONFIG_DIR + '/postgresql_vars.sh', 'POSTGRESQL_ROOT_PASSWORD=' + rootPassword, 'utf8')) {
2016-06-14 15:49:24 -07:00
return callback(new Error('Could not create postgresql var file:' + safe.error.message));
}
const cmd = `docker run --restart=always -d --name="postgresql" \
--net cloudron \
--net-alias postgresql \
2018-06-06 13:41:46 +02:00
--log-driver syslog \
--log-opt syslog-address=udp://127.0.0.1:2514 \
--log-opt syslog-format=rfc5424 \
--log-opt tag=postgresql \
-m ${memoryLimit}m \
--memory-swap ${memoryLimit * 2}m \
2017-04-25 15:21:23 +00:00
--dns 172.18.0.1 \
--dns-search=. \
2016-06-14 15:49:24 -07:00
-v "${dataDir}/postgresql:/var/lib/postgresql" \
-v "${dataDir}/addons/postgresql_vars.sh:/etc/postgresql/postgresql_vars.sh:ro" \
--read-only -v /tmp -v /run "${tag}"`;
shell.execSync('startPostgresql', cmd);
setTimeout(callback, 5000);
2016-06-14 15:49:24 -07:00
}
function startMongodb(callback) {
const tag = infra.images.mongodb.tag;
const dataDir = paths.PLATFORM_DATA_DIR;
2016-06-17 09:46:07 -05:00
const rootPassword = hat(8 * 128);
const memoryLimit = (1 + Math.round(os.totalmem()/(1024*1024*1024)/4)) * 200;
2016-06-14 15:49:24 -07:00
if (!safe.fs.writeFileSync(paths.ADDON_CONFIG_DIR + '/mongodb_vars.sh', 'MONGODB_ROOT_PASSWORD=' + rootPassword, 'utf8')) {
2016-06-14 15:49:24 -07:00
return callback(new Error('Could not create mongodb var file:' + safe.error.message));
}
const cmd = `docker run --restart=always -d --name="mongodb" \
--net cloudron \
--net-alias mongodb \
2018-06-06 13:41:46 +02:00
--log-driver syslog \
--log-opt syslog-address=udp://127.0.0.1:2514 \
--log-opt syslog-format=rfc5424 \
--log-opt tag=mongodb \
-m ${memoryLimit}m \
--memory-swap ${memoryLimit * 2}m \
2017-04-25 15:21:23 +00:00
--dns 172.18.0.1 \
--dns-search=. \
2016-06-14 15:49:24 -07:00
-v "${dataDir}/mongodb:/var/lib/mongodb" \
-v "${dataDir}/addons/mongodb_vars.sh:/etc/mongodb_vars.sh:ro" \
--read-only -v /tmp -v /run "${tag}"`;
shell.execSync('startMongodb', cmd);
setTimeout(callback, 5000);
2016-06-14 15:49:24 -07:00
}
2016-07-25 00:39:57 -07:00
function startAddons(existingInfra, callback) {
var startFuncs = [ ];
// always start addons on any infra change, regardless of minor or major update
2016-07-25 09:38:31 -07:00
if (existingInfra.version !== infra.version) {
debug('startAddons: no existing infra or infra upgrade. starting all addons');
startFuncs.push(startGraphite, startMysql, startPostgresql, startMongodb, mail.startMail);
2016-07-25 09:38:31 -07:00
} else {
assert.strictEqual(typeof existingInfra.images, 'object');
2016-07-25 00:39:57 -07:00
if (infra.images.graphite.tag !== existingInfra.images.graphite.tag) startFuncs.push(startGraphite);
if (infra.images.mysql.tag !== existingInfra.images.mysql.tag) startFuncs.push(startMysql);
if (infra.images.postgresql.tag !== existingInfra.images.postgresql.tag) startFuncs.push(startPostgresql);
if (infra.images.mongodb.tag !== existingInfra.images.mongodb.tag) startFuncs.push(startMongodb);
if (infra.images.mail.tag !== existingInfra.images.mail.tag) startFuncs.push(mail.startMail);
2016-07-25 10:18:35 -07:00
debug('startAddons: existing infra. incremental addon create %j', startFuncs.map(function (f) { return f.name; }));
2016-07-25 00:39:57 -07:00
}
2016-06-14 15:49:24 -07:00
2016-07-25 00:39:57 -07:00
async.series(startFuncs, callback);
2016-06-14 15:49:24 -07:00
}
function startApps(existingInfra, callback) {
// Infra version change strategy:
// * no existing version - restore apps
// * major versions - restore apps
// * minor versions - reconfigure apps
if (existingInfra.version === infra.version) {
debug('startApp: apps are already uptodate');
callback();
} else if (existingInfra.version === 'none' || !semver.valid(existingInfra.version) || semver.major(existingInfra.version) !== semver.major(infra.version)) {
debug('startApps: restoring installed apps');
apps.restoreInstalledApps(callback);
} else {
debug('startApps: reconfiguring installed apps');
reverseProxy.removeAppConfigs(); // should we change the cert location, nginx will not start
apps.configureInstalledApps(callback);
}
}
function handleCertChanged(cn) {
assert.strictEqual(typeof cn, 'string');
2018-01-28 14:19:28 -08:00
if (cn === '*.' + config.adminDomain() || cn === config.adminFqdn()) {
mail.startMail(NOOP_CALLBACK);
}
}