160 lines
5.9 KiB
JavaScript
160 lines
5.9 KiB
JavaScript
'use strict';
|
|
|
|
exports = module.exports = {
|
|
add,
|
|
get,
|
|
del,
|
|
list,
|
|
getStatus,
|
|
removePrivateFields
|
|
};
|
|
|
|
const assert = require('assert'),
|
|
BoxError = require('./boxerror.js'),
|
|
collectd = require('./collectd.js'),
|
|
constants = require('./constants.js'),
|
|
database = require('./database.js'),
|
|
debug = require('debug')('box:volumes'),
|
|
ejs = require('ejs'),
|
|
eventlog = require('./eventlog.js'),
|
|
fs = require('fs'),
|
|
mounts = require('./mounts.js'),
|
|
path = require('path'),
|
|
safe = require('safetydance'),
|
|
services = require('./services.js'),
|
|
uuid = require('uuid');
|
|
|
|
const VOLUMES_FIELDS = [ 'id', 'name', 'hostPath', 'creationTime', 'mountType', 'mountOptionsJson' ].join(',');
|
|
|
|
const COLLECTD_CONFIG_EJS = fs.readFileSync(__dirname + '/collectd/volume.ejs', { encoding: 'utf8' });
|
|
const NOOP_CALLBACK = function (error) { if (error) debug(error); };
|
|
|
|
function postProcess(result) {
|
|
assert.strictEqual(typeof result, 'object');
|
|
|
|
result.mountOptions = safe.JSON.parse(result.mountOptionsJson) || {};
|
|
delete result.mountOptionsJson;
|
|
|
|
return result;
|
|
}
|
|
|
|
function validateName(name) {
|
|
assert.strictEqual(typeof name, 'string');
|
|
|
|
if (!/^[-\w^&'@{}[\],$=!#().%+~ ]+$/.test(name)) return new BoxError(BoxError.BAD_FIELD, 'Invalid name');
|
|
|
|
return null;
|
|
}
|
|
|
|
function validateHostPath(hostPath, mountType) {
|
|
assert.strictEqual(typeof hostPath, 'string');
|
|
assert.strictEqual(typeof mountType, 'string');
|
|
|
|
if (path.normalize(hostPath) !== hostPath) return new BoxError(BoxError.BAD_FIELD, 'hostPath must contain a normalized path', { field: 'hostPath' });
|
|
if (!path.isAbsolute(hostPath)) return new BoxError(BoxError.BAD_FIELD, 'backupFolder must be an absolute path', { field: 'hostPath' });
|
|
|
|
if (hostPath === '/') return new BoxError(BoxError.BAD_FIELD, 'hostPath cannot be /', { field: 'hostPath' });
|
|
|
|
if (!hostPath.endsWith('/')) hostPath = hostPath + '/'; // ensure trailing slash for the prefix matching to work
|
|
const allowedPaths = [ '/mnt/', '/media/', '/srv/', '/opt/' ];
|
|
|
|
if (!allowedPaths.some(p => hostPath.startsWith(p))) return new BoxError(BoxError.BAD_FIELD, 'hostPath must be under /mnt, /media, /opt or /srv', { field: 'hostPath' });
|
|
|
|
if (!constants.TEST && mountType === 'noop') { // we expect user to have already mounted this
|
|
const stat = safe.fs.lstatSync(hostPath);
|
|
if (!stat) return new BoxError(BoxError.BAD_FIELD, 'mount point does not exist. Please create it on the server first', { field: 'hostPath' });
|
|
if (!stat.isDirectory()) return new BoxError(BoxError.BAD_FIELD, 'mount point is not a directory', { field: 'hostPath' });
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
async function add(volume, auditSource) {
|
|
assert.strictEqual(typeof volume, 'object');
|
|
assert.strictEqual(typeof auditSource, 'object');
|
|
|
|
const {name, hostPath, mountType, mountOptions} = volume;
|
|
|
|
let error = validateName(name);
|
|
if (error) throw error;
|
|
|
|
error = validateHostPath(hostPath, mountType);
|
|
if (error) throw error;
|
|
|
|
error = mounts.validateMountOptions(mountType, mountOptions);
|
|
if (error) throw error;
|
|
|
|
const id = uuid.v4();
|
|
|
|
if (volume.mountType !== 'noop') await mounts.tryAddMount(volume, { timeout: 10 }); // 10 seconds
|
|
|
|
try {
|
|
await database.query('INSERT INTO volumes (id, name, hostPath, mountType, mountOptionsJson) VALUES (?, ?, ?, ?, ?)', [ id, name, hostPath, mountType, JSON.stringify(mountOptions) ]);
|
|
} catch (error) {
|
|
if (error.code === 'ER_DUP_ENTRY' && error.sqlMessage.indexOf('name') !== -1) throw new BoxError(BoxError.ALREADY_EXISTS, 'name already exists');
|
|
if (error.code === 'ER_DUP_ENTRY' && error.sqlMessage.indexOf('hostPath') !== -1) throw new BoxError(BoxError.ALREADY_EXISTS, 'hostPath already exists');
|
|
if (error.code === 'ER_DUP_ENTRY' && error.sqlMessage.indexOf('PRIMARY') !== -1) throw new BoxError(BoxError.ALREADY_EXISTS, 'id already exists');
|
|
throw error;
|
|
}
|
|
|
|
eventlog.add(eventlog.ACTION_VOLUME_ADD, auditSource, { id, name, hostPath });
|
|
services.rebuildService('sftp', NOOP_CALLBACK);
|
|
|
|
const collectdConf = ejs.render(COLLECTD_CONFIG_EJS, { volumeId: id, hostPath });
|
|
collectd.addProfile(id, collectdConf, NOOP_CALLBACK);
|
|
|
|
return id;
|
|
}
|
|
|
|
async function getStatus(volume) {
|
|
assert.strictEqual(typeof volume, 'object');
|
|
|
|
return await mounts.getStatus(volume.mountType, volume.hostPath); // { state, message }
|
|
}
|
|
|
|
function removePrivateFields(volume) {
|
|
const newVolume = Object.assign({}, volume);
|
|
|
|
if (newVolume.mountType === 'sshfs') {
|
|
newVolume.mountOptions.privateKey = constants.SECRET_PLACEHOLDER;
|
|
} else if (newVolume.mountType === 'cifs') {
|
|
newVolume.mountOptions.password = constants.SECRET_PLACEHOLDER;
|
|
}
|
|
|
|
return newVolume;
|
|
}
|
|
|
|
async function get(id) {
|
|
assert.strictEqual(typeof id, 'string');
|
|
|
|
const result = await database.query(`SELECT ${VOLUMES_FIELDS} FROM volumes WHERE id=?`, [ id ]);
|
|
if (result.length === 0) return null;
|
|
|
|
return postProcess(result[0]);
|
|
}
|
|
|
|
async function list() {
|
|
const results = await database.query(`SELECT ${VOLUMES_FIELDS} FROM volumes ORDER BY name`);
|
|
results.forEach(postProcess);
|
|
return results;
|
|
}
|
|
|
|
async function del(volume, auditSource) {
|
|
assert.strictEqual(typeof volume, 'object');
|
|
assert.strictEqual(typeof auditSource, 'object');
|
|
|
|
try {
|
|
const result = await database.query('DELETE FROM volumes WHERE id=?', [ volume.id ]);
|
|
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Volume not found');
|
|
} catch (error) {
|
|
if (error.code === 'ER_ROW_IS_REFERENCED_2') throw new BoxError(BoxError.CONFLICT, 'Volume is in use');
|
|
throw error;
|
|
}
|
|
|
|
eventlog.add(eventlog.ACTION_VOLUME_REMOVE, auditSource, { volume });
|
|
services.rebuildService('sftp', async function () {
|
|
if (volume.mountType !== 'noop') await safe(mounts.removeMount(volume));
|
|
});
|
|
collectd.removeProfile(volume.id, NOOP_CALLBACK);
|
|
}
|