nginx.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. const _ = require('lodash');
  2. const fs = require('fs');
  3. const logger = require('../logger').nginx;
  4. const utils = require('../lib/utils');
  5. const error = require('../lib/error');
  6. const { Liquid } = require('liquidjs');
  7. const debug_mode = process.env.NODE_ENV !== 'production' || !!process.env.DEBUG;
  8. const internalNginx = {
  9. /**
  10. * This will:
  11. * - test the nginx config first to make sure it's OK
  12. * - create / recreate the config for the host
  13. * - test again
  14. * - IF OK: update the meta with online status
  15. * - IF BAD: update the meta with offline status and remove the config entirely
  16. * - then reload nginx
  17. *
  18. * @param {Object|String} model
  19. * @param {String} host_type
  20. * @param {Object} host
  21. * @returns {Promise}
  22. */
  23. configure: (model, host_type, host) => {
  24. let combined_meta = {};
  25. return internalNginx.test()
  26. .then(() => {
  27. // Nginx is OK
  28. // We're deleting this config regardless.
  29. return internalNginx.deleteConfig(host_type, host); // Don't throw errors, as the file may not exist at all
  30. })
  31. .then(() => {
  32. return internalNginx.generateConfig(host_type, host);
  33. })
  34. .then(() => {
  35. // Test nginx again and update meta with result
  36. return internalNginx.test()
  37. .then(() => {
  38. // nginx is ok
  39. combined_meta = _.assign({}, host.meta, {
  40. nginx_online: true,
  41. nginx_err: null
  42. });
  43. return model
  44. .query()
  45. .where('id', host.id)
  46. .patch({
  47. meta: combined_meta
  48. });
  49. })
  50. .catch((err) => {
  51. // Remove the error_log line because it's a docker-ism false positive that doesn't need to be reported.
  52. // It will always look like this:
  53. // nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (6: No such device or address)
  54. let valid_lines = [];
  55. let err_lines = err.message.split('\n');
  56. err_lines.map(function (line) {
  57. if (line.indexOf('/var/log/nginx/error.log') === -1) {
  58. valid_lines.push(line);
  59. }
  60. });
  61. if (debug_mode) {
  62. logger.error('Nginx test failed:', valid_lines.join('\n'));
  63. }
  64. // config is bad, update meta and delete config
  65. combined_meta = _.assign({}, host.meta, {
  66. nginx_online: false,
  67. nginx_err: valid_lines.join('\n')
  68. });
  69. return model
  70. .query()
  71. .where('id', host.id)
  72. .patch({
  73. meta: combined_meta
  74. })
  75. .then(() => {
  76. return internalNginx.deleteConfig(host_type, host, true);
  77. });
  78. });
  79. })
  80. .then(() => {
  81. return internalNginx.reload();
  82. })
  83. .then(() => {
  84. return combined_meta;
  85. });
  86. },
  87. /**
  88. * @returns {Promise}
  89. */
  90. test: () => {
  91. if (debug_mode) {
  92. logger.info('Testing Nginx configuration');
  93. }
  94. return utils.exec('/usr/sbin/nginx -t -g "error_log off;"');
  95. },
  96. /**
  97. * @returns {Promise}
  98. */
  99. reload: () => {
  100. return internalNginx.test()
  101. .then(() => {
  102. logger.info('Reloading Nginx');
  103. return utils.exec('/usr/sbin/nginx -s reload');
  104. });
  105. },
  106. /**
  107. * @param {String} host_type
  108. * @param {Integer} host_id
  109. * @returns {String}
  110. */
  111. getConfigName: (host_type, host_id) => {
  112. host_type = host_type.replace(new RegExp('-', 'g'), '_');
  113. if (host_type === 'default') {
  114. return '/data/nginx/default_host/site.conf';
  115. }
  116. return '/data/nginx/' + host_type + '/' + host_id + '.conf';
  117. },
  118. /**
  119. * Generates custom locations
  120. * @param {Object} host
  121. * @returns {Promise}
  122. */
  123. renderLocations: (host) => {
  124. return new Promise((resolve, reject) => {
  125. let template;
  126. try {
  127. template = fs.readFileSync(__dirname + '/../templates/_location.conf', {encoding: 'utf8'});
  128. } catch (err) {
  129. reject(new error.ConfigurationError(err.message));
  130. return;
  131. }
  132. let renderer = new Liquid();
  133. let renderedLocations = '';
  134. const locationRendering = async () => {
  135. for (let i = 0; i < host.locations.length; i++) {
  136. let locationCopy = Object.assign({}, host.locations[i]);
  137. if (locationCopy.forward_host.indexOf('/') > -1) {
  138. const splitted = locationCopy.forward_host.split('/');
  139. locationCopy.forward_host = splitted.shift();
  140. locationCopy.forward_path = `/${splitted.join('/')}`;
  141. }
  142. // eslint-disable-next-line
  143. renderedLocations += await renderer.parseAndRender(template, locationCopy);
  144. }
  145. };
  146. locationRendering().then(() => resolve(renderedLocations));
  147. });
  148. },
  149. /**
  150. * @param {String} host_type
  151. * @param {Object} host
  152. * @returns {Promise}
  153. */
  154. generateConfig: (host_type, host) => {
  155. host_type = host_type.replace(new RegExp('-', 'g'), '_');
  156. if (debug_mode) {
  157. logger.info('Generating ' + host_type + ' Config:', host);
  158. }
  159. let renderEngine = new Liquid({
  160. root: __dirname + '/../templates/'
  161. });
  162. return new Promise((resolve, reject) => {
  163. let template = null;
  164. let filename = internalNginx.getConfigName(host_type, host.id);
  165. try {
  166. template = fs.readFileSync(__dirname + '/../templates/' + host_type + '.conf', {encoding: 'utf8'});
  167. } catch (err) {
  168. reject(new error.ConfigurationError(err.message));
  169. return;
  170. }
  171. let locationsPromise;
  172. let origLocations;
  173. // Manipulate the data a bit before sending it to the template
  174. if (host_type !== 'default') {
  175. host.use_default_location = true;
  176. if (typeof host.advanced_config !== 'undefined' && host.advanced_config) {
  177. host.use_default_location = !internalNginx.advancedConfigHasDefaultLocation(host.advanced_config);
  178. }
  179. }
  180. if (host.locations) {
  181. origLocations = [].concat(host.locations);
  182. locationsPromise = internalNginx.renderLocations(host).then((renderedLocations) => {
  183. host.locations = renderedLocations;
  184. });
  185. // Allow someone who is using / custom location path to use it, and skip the default / location
  186. _.map(host.locations, (location) => {
  187. if (location.path === '/') {
  188. host.use_default_location = false;
  189. }
  190. });
  191. } else {
  192. locationsPromise = Promise.resolve();
  193. }
  194. locationsPromise.then(() => {
  195. renderEngine
  196. .parseAndRender(template, host)
  197. .then((config_text) => {
  198. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  199. if (debug_mode) {
  200. logger.success('Wrote config:', filename, config_text);
  201. }
  202. // Restore locations array
  203. host.locations = origLocations;
  204. resolve(true);
  205. })
  206. .catch((err) => {
  207. if (debug_mode) {
  208. logger.warn('Could not write ' + filename + ':', err.message);
  209. }
  210. reject(new error.ConfigurationError(err.message));
  211. });
  212. });
  213. });
  214. },
  215. /**
  216. * This generates a temporary nginx config listening on port 80 for the domain names listed
  217. * in the certificate setup. It allows the letsencrypt acme challenge to be requested by letsencrypt
  218. * when requesting a certificate without having a hostname set up already.
  219. *
  220. * @param {Object} certificate
  221. * @returns {Promise}
  222. */
  223. generateLetsEncryptRequestConfig: (certificate) => {
  224. if (debug_mode) {
  225. logger.info('Generating LetsEncrypt Request Config:', certificate);
  226. }
  227. let renderEngine = new Liquid({
  228. root: __dirname + '/../templates/'
  229. });
  230. return new Promise((resolve, reject) => {
  231. let template = null;
  232. let filename = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  233. try {
  234. template = fs.readFileSync(__dirname + '/../templates/letsencrypt-request.conf', {encoding: 'utf8'});
  235. } catch (err) {
  236. reject(new error.ConfigurationError(err.message));
  237. return;
  238. }
  239. renderEngine
  240. .parseAndRender(template, certificate)
  241. .then((config_text) => {
  242. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  243. if (debug_mode) {
  244. logger.success('Wrote config:', filename, config_text);
  245. }
  246. resolve(true);
  247. })
  248. .catch((err) => {
  249. if (debug_mode) {
  250. logger.warn('Could not write ' + filename + ':', err.message);
  251. }
  252. reject(new error.ConfigurationError(err.message));
  253. });
  254. });
  255. },
  256. /**
  257. * This removes the temporary nginx config file generated by `generateLetsEncryptRequestConfig`
  258. *
  259. * @param {Object} certificate
  260. * @param {Boolean} [throw_errors]
  261. * @returns {Promise}
  262. */
  263. deleteLetsEncryptRequestConfig: (certificate, throw_errors) => {
  264. return new Promise((resolve, reject) => {
  265. try {
  266. let config_file = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  267. if (debug_mode) {
  268. logger.warn('Deleting nginx config: ' + config_file);
  269. }
  270. fs.unlinkSync(config_file);
  271. } catch (err) {
  272. if (debug_mode) {
  273. logger.warn('Could not delete config:', err.message);
  274. }
  275. if (throw_errors) {
  276. reject(err);
  277. }
  278. }
  279. resolve();
  280. });
  281. },
  282. /**
  283. * @param {String} host_type
  284. * @param {Object} [host]
  285. * @param {Boolean} [throw_errors]
  286. * @returns {Promise}
  287. */
  288. deleteConfig: (host_type, host, throw_errors) => {
  289. host_type = host_type.replace(new RegExp('-', 'g'), '_');
  290. return new Promise((resolve, reject) => {
  291. try {
  292. let config_file = internalNginx.getConfigName(host_type, typeof host === 'undefined' ? 0 : host.id);
  293. if (debug_mode) {
  294. logger.warn('Deleting nginx config: ' + config_file);
  295. }
  296. fs.unlinkSync(config_file);
  297. } catch (err) {
  298. if (debug_mode) {
  299. logger.warn('Could not delete config:', err.message);
  300. }
  301. if (throw_errors) {
  302. reject(err);
  303. }
  304. }
  305. resolve();
  306. });
  307. },
  308. /**
  309. * @param {String} host_type
  310. * @param {Array} hosts
  311. * @returns {Promise}
  312. */
  313. bulkGenerateConfigs: (host_type, hosts) => {
  314. let promises = [];
  315. hosts.map(function (host) {
  316. promises.push(internalNginx.generateConfig(host_type, host));
  317. });
  318. return Promise.all(promises);
  319. },
  320. /**
  321. * @param {String} host_type
  322. * @param {Array} hosts
  323. * @param {Boolean} [throw_errors]
  324. * @returns {Promise}
  325. */
  326. bulkDeleteConfigs: (host_type, hosts, throw_errors) => {
  327. let promises = [];
  328. hosts.map(function (host) {
  329. promises.push(internalNginx.deleteConfig(host_type, host, throw_errors));
  330. });
  331. return Promise.all(promises);
  332. },
  333. /**
  334. * @param {string} config
  335. * @returns {boolean}
  336. */
  337. advancedConfigHasDefaultLocation: function (config) {
  338. return !!config.match(/^(?:.*;)?\s*?location\s*?\/\s*?{/im);
  339. }
  340. };
  341. module.exports = internalNginx;