nginx.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. // Set the IPv6 setting for the host
  195. host.ipv6 = internalNginx.ipv6Enabled();
  196. locationsPromise.then(() => {
  197. renderEngine
  198. .parseAndRender(template, host)
  199. .then((config_text) => {
  200. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  201. if (debug_mode) {
  202. logger.success('Wrote config:', filename, config_text);
  203. }
  204. // Restore locations array
  205. host.locations = origLocations;
  206. resolve(true);
  207. })
  208. .catch((err) => {
  209. if (debug_mode) {
  210. logger.warn('Could not write ' + filename + ':', err.message);
  211. }
  212. reject(new error.ConfigurationError(err.message));
  213. });
  214. });
  215. });
  216. },
  217. /**
  218. * This generates a temporary nginx config listening on port 80 for the domain names listed
  219. * in the certificate setup. It allows the letsencrypt acme challenge to be requested by letsencrypt
  220. * when requesting a certificate without having a hostname set up already.
  221. *
  222. * @param {Object} certificate
  223. * @returns {Promise}
  224. */
  225. generateLetsEncryptRequestConfig: (certificate) => {
  226. if (debug_mode) {
  227. logger.info('Generating LetsEncrypt Request Config:', certificate);
  228. }
  229. let renderEngine = new Liquid({
  230. root: __dirname + '/../templates/'
  231. });
  232. return new Promise((resolve, reject) => {
  233. let template = null;
  234. let filename = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  235. try {
  236. template = fs.readFileSync(__dirname + '/../templates/letsencrypt-request.conf', {encoding: 'utf8'});
  237. } catch (err) {
  238. reject(new error.ConfigurationError(err.message));
  239. return;
  240. }
  241. certificate.ipv6 = internalNginx.ipv6Enabled();
  242. renderEngine
  243. .parseAndRender(template, certificate)
  244. .then((config_text) => {
  245. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  246. if (debug_mode) {
  247. logger.success('Wrote config:', filename, config_text);
  248. }
  249. resolve(true);
  250. })
  251. .catch((err) => {
  252. if (debug_mode) {
  253. logger.warn('Could not write ' + filename + ':', err.message);
  254. }
  255. reject(new error.ConfigurationError(err.message));
  256. });
  257. });
  258. },
  259. /**
  260. * This removes the temporary nginx config file generated by `generateLetsEncryptRequestConfig`
  261. *
  262. * @param {Object} certificate
  263. * @param {Boolean} [throw_errors]
  264. * @returns {Promise}
  265. */
  266. deleteLetsEncryptRequestConfig: (certificate, throw_errors) => {
  267. return new Promise((resolve, reject) => {
  268. try {
  269. let config_file = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  270. if (debug_mode) {
  271. logger.warn('Deleting nginx config: ' + config_file);
  272. }
  273. fs.unlinkSync(config_file);
  274. } catch (err) {
  275. if (debug_mode) {
  276. logger.warn('Could not delete config:', err.message);
  277. }
  278. if (throw_errors) {
  279. reject(err);
  280. }
  281. }
  282. resolve();
  283. });
  284. },
  285. /**
  286. * @param {String} host_type
  287. * @param {Object} [host]
  288. * @param {Boolean} [throw_errors]
  289. * @returns {Promise}
  290. */
  291. deleteConfig: (host_type, host, throw_errors) => {
  292. host_type = host_type.replace(new RegExp('-', 'g'), '_');
  293. return new Promise((resolve, reject) => {
  294. try {
  295. let config_file = internalNginx.getConfigName(host_type, typeof host === 'undefined' ? 0 : host.id);
  296. if (debug_mode) {
  297. logger.warn('Deleting nginx config: ' + config_file);
  298. }
  299. fs.unlinkSync(config_file);
  300. } catch (err) {
  301. if (debug_mode) {
  302. logger.warn('Could not delete config:', err.message);
  303. }
  304. if (throw_errors) {
  305. reject(err);
  306. }
  307. }
  308. resolve();
  309. });
  310. },
  311. /**
  312. * @param {String} host_type
  313. * @param {Array} hosts
  314. * @returns {Promise}
  315. */
  316. bulkGenerateConfigs: (host_type, hosts) => {
  317. let promises = [];
  318. hosts.map(function (host) {
  319. promises.push(internalNginx.generateConfig(host_type, host));
  320. });
  321. return Promise.all(promises);
  322. },
  323. /**
  324. * @param {String} host_type
  325. * @param {Array} hosts
  326. * @param {Boolean} [throw_errors]
  327. * @returns {Promise}
  328. */
  329. bulkDeleteConfigs: (host_type, hosts, throw_errors) => {
  330. let promises = [];
  331. hosts.map(function (host) {
  332. promises.push(internalNginx.deleteConfig(host_type, host, throw_errors));
  333. });
  334. return Promise.all(promises);
  335. },
  336. /**
  337. * @param {string} config
  338. * @returns {boolean}
  339. */
  340. advancedConfigHasDefaultLocation: function (config) {
  341. return !!config.match(/^(?:.*;)?\s*?location\s*?\/\s*?{/im);
  342. },
  343. /**
  344. * @returns {boolean}
  345. */
  346. ipv6Enabled: function () {
  347. if (typeof process.env.DISABLE_IPV6 !== 'undefined') {
  348. const disabled = process.env.DISABLE_IPV6.toLowerCase();
  349. return !(disabled === 'on' || disabled === 'true' || disabled === '1' || disabled === 'yes');
  350. }
  351. return true;
  352. }
  353. };
  354. module.exports = internalNginx;