Refactor nginx config functions, some don't need to report errors, save error'd config files as .err for debugging later

This commit is contained in:
Jamie Curnow 2023-03-17 11:34:27 +10:00
parent 5b7682f13c
commit 00aeef75b6
No known key found for this signature in database
GPG Key ID: FFBB624C43388E9E

View File

@ -29,7 +29,9 @@ const internalNginx = {
.then(() => { .then(() => {
// Nginx is OK // Nginx is OK
// We're deleting this config regardless. // We're deleting this config regardless.
return internalNginx.deleteConfig(host_type, host); // Don't throw errors, as the file may not exist at all // Don't throw errors, as the file may not exist at all
// Delete the .err file too
return internalNginx.deleteConfig(host_type, host, false, true);
}) })
.then(() => { .then(() => {
return internalNginx.generateConfig(host_type, host); return internalNginx.generateConfig(host_type, host);
@ -80,6 +82,9 @@ const internalNginx = {
.patch({ .patch({
meta: combined_meta meta: combined_meta
}) })
.then(() => {
internalNginx.renameConfigAsError(host_type, host)
})
.then(() => { .then(() => {
return internalNginx.deleteConfig(host_type, host, true); return internalNginx.deleteConfig(host_type, host, true);
}); });
@ -121,13 +126,10 @@ const internalNginx = {
* @returns {String} * @returns {String}
*/ */
getConfigName: (host_type, host_id) => { getConfigName: (host_type, host_id) => {
host_type = host_type.replace(new RegExp('-', 'g'), '_');
if (host_type === 'default') { if (host_type === 'default') {
return '/data/nginx/default_host/site.conf'; return '/data/nginx/default_host/site.conf';
} }
return '/data/nginx/' + internalNginx.getFileFriendlyHostType(host_type) + '/' + host_id + '.conf';
return '/data/nginx/' + host_type + '/' + host_id + '.conf';
}, },
/** /**
@ -155,12 +157,12 @@ const internalNginx = {
const locationRendering = async () => { const locationRendering = async () => {
for (let i = 0; i < host.locations.length; i++) { for (let i = 0; i < host.locations.length; i++) {
let locationCopy = Object.assign({}, {access_list_id: host.access_list_id}, {certificate_id: host.certificate_id}, let locationCopy = Object.assign({}, {access_list_id: host.access_list_id}, {certificate_id: host.certificate_id},
{ssl_forced: host.ssl_forced}, {caching_enabled: host.caching_enabled}, {block_exploits: host.block_exploits}, {ssl_forced: host.ssl_forced}, {caching_enabled: host.caching_enabled}, {block_exploits: host.block_exploits},
{allow_websocket_upgrade: host.allow_websocket_upgrade}, {http2_support: host.http2_support}, {allow_websocket_upgrade: host.allow_websocket_upgrade}, {http2_support: host.http2_support},
{hsts_enabled: host.hsts_enabled}, {hsts_subdomains: host.hsts_subdomains}, {access_list: host.access_list}, {hsts_enabled: host.hsts_enabled}, {hsts_subdomains: host.hsts_subdomains}, {access_list: host.access_list},
{certificate: host.certificate}, host.locations[i]); {certificate: host.certificate}, host.locations[i]);
if (locationCopy.forward_host.indexOf('/') > -1) { if (locationCopy.forward_host.indexOf('/') > -1) {
const splitted = locationCopy.forward_host.split('/'); const splitted = locationCopy.forward_host.split('/');
@ -177,7 +179,7 @@ const internalNginx = {
}; };
locationRendering().then(() => resolve(renderedLocations)); locationRendering().then(() => resolve(renderedLocations));
}); });
}, },
@ -187,10 +189,10 @@ const internalNginx = {
* @returns {Promise} * @returns {Promise}
*/ */
generateConfig: (host_type, host) => { generateConfig: (host_type, host) => {
host_type = host_type.replace(new RegExp('-', 'g'), '_'); const nice_host_type = internalNginx.getFileFriendlyHostType(host_type);
if (debug_mode) { if (debug_mode) {
logger.info('Generating ' + host_type + ' Config:', host); logger.info('Generating ' + nice_host_type + ' Config:', JSON.stringify(host, null, 2));
} }
// logger.info('host = ' + JSON.stringify(host, null, 2)); // logger.info('host = ' + JSON.stringify(host, null, 2));
@ -201,10 +203,10 @@ const internalNginx = {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let template = null; let template = null;
let filename = internalNginx.getConfigName(host_type, host.id); let filename = internalNginx.getConfigName(nice_host_type, host.id);
try { try {
template = fs.readFileSync(__dirname + '/../templates/' + host_type + '.conf', {encoding: 'utf8'}); template = fs.readFileSync(__dirname + '/../templates/' + nice_host_type + '.conf', {encoding: 'utf8'});
} catch (err) { } catch (err) {
reject(new error.ConfigurationError(err.message)); reject(new error.ConfigurationError(err.message));
return; return;
@ -214,7 +216,7 @@ const internalNginx = {
let origLocations; let origLocations;
// Manipulate the data a bit before sending it to the template // Manipulate the data a bit before sending it to the template
if (host_type !== 'default') { if (nice_host_type !== 'default') {
host.use_default_location = true; host.use_default_location = true;
if (typeof host.advanced_config !== 'undefined' && host.advanced_config) { if (typeof host.advanced_config !== 'undefined' && host.advanced_config) {
host.use_default_location = !internalNginx.advancedConfigHasDefaultLocation(host.advanced_config); host.use_default_location = !internalNginx.advancedConfigHasDefaultLocation(host.advanced_config);
@ -319,33 +321,39 @@ const internalNginx = {
}); });
}, },
/**
* A simple wrapper around unlinkSync that writes to the logger
*
* @param {String} filename
*/
deleteFile: (filename) => {
logger.debug('Deleting file: ' + filename);
try {
fs.unlinkSync(filename);
} catch (err) {
logger.debug('Could not delete file:', JSON.stringify(err, null, 2));
};
},
/**
*
* @param {String} host_type
* @returns String
*/
getFileFriendlyHostType: (host_type) => {
return host_type.replace(new RegExp('-', 'g'), '_');
},
/** /**
* This removes the temporary nginx config file generated by `generateLetsEncryptRequestConfig` * This removes the temporary nginx config file generated by `generateLetsEncryptRequestConfig`
* *
* @param {Object} certificate * @param {Object} certificate
* @param {Boolean} [throw_errors]
* @returns {Promise} * @returns {Promise}
*/ */
deleteLetsEncryptRequestConfig: (certificate, throw_errors) => { deleteLetsEncryptRequestConfig: (certificate) => {
return new Promise((resolve, reject) => { const config_file = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
try { return new Promise((resolve/*, reject*/) => {
let config_file = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf'; internalNginx.deleteFile(config_file);
if (debug_mode) {
logger.warn('Deleting nginx config: ' + config_file);
}
fs.unlinkSync(config_file);
} catch (err) {
if (debug_mode) {
logger.warn('Could not delete config:', err.message);
}
if (throw_errors) {
reject(err);
}
}
resolve(); resolve();
}); });
}, },
@ -353,35 +361,42 @@ const internalNginx = {
/** /**
* @param {String} host_type * @param {String} host_type
* @param {Object} [host] * @param {Object} [host]
* @param {Boolean} [throw_errors] * @param {Boolean} [delete_err_file]
* @returns {Promise} * @returns {Promise}
*/ */
deleteConfig: (host_type, host, throw_errors) => { deleteConfig: (host_type, host, delete_err_file) => {
host_type = host_type.replace(new RegExp('-', 'g'), '_'); const config_file = internalNginx.getConfigName(internalNginx.getFileFriendlyHostType(host_type), typeof host === 'undefined' ? 0 : host.id);
const config_file_err = config_file + '.err';
return new Promise((resolve, reject) => { return new Promise((resolve/*, reject*/) => {
try { internalNginx.deleteFile(config_file);
let config_file = internalNginx.getConfigName(host_type, typeof host === 'undefined' ? 0 : host.id); if (delete_err_file) {
internalNginx.deleteFile(config_file_err);
if (debug_mode) {
logger.warn('Deleting nginx config: ' + config_file);
}
fs.unlinkSync(config_file);
} catch (err) {
if (debug_mode) {
logger.warn('Could not delete config:', err.message);
}
if (throw_errors) {
reject(err);
}
} }
resolve(); resolve();
}); });
}, },
/**
* @param {String} host_type
* @param {Object} [host]
* @returns {Promise}
*/
renameConfigAsError: (host_type, host) => {
const config_file = internalNginx.getConfigName(internalNginx.getFileFriendlyHostType(host_type), typeof host === 'undefined' ? 0 : host.id);
const config_file_err = config_file + '.err';
return new Promise((resolve/*, reject*/) => {
fs.unlink(config_file, () => {
// ignore result, continue
fs.rename(config_file, config_file_err, () => {
// also ignore result, as this is a debugging informative file anyway
resolve();
});
});
});
},
/** /**
* @param {String} host_type * @param {String} host_type
* @param {Array} hosts * @param {Array} hosts
@ -399,13 +414,12 @@ const internalNginx = {
/** /**
* @param {String} host_type * @param {String} host_type
* @param {Array} hosts * @param {Array} hosts
* @param {Boolean} [throw_errors]
* @returns {Promise} * @returns {Promise}
*/ */
bulkDeleteConfigs: (host_type, hosts, throw_errors) => { bulkDeleteConfigs: (host_type, hosts) => {
let promises = []; let promises = [];
hosts.map(function (host) { hosts.map(function (host) {
promises.push(internalNginx.deleteConfig(host_type, host, throw_errors)); promises.push(internalNginx.deleteConfig(host_type, host, true));
}); });
return Promise.all(promises); return Promise.all(promises);