nginx.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 ');
  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. root: __dirname + '/../templates/'
  134. });
  135. let renderedLocations = '';
  136. const locationRendering = async () => {
  137. for (let i = 0; i < host.locations.length; i++) {
  138. let locationCopy = Object.assign({}, host.locations[i]);
  139. if (locationCopy.forward_host.indexOf('/') > -1) {
  140. const splitted = locationCopy.forward_host.split('/');
  141. locationCopy.forward_host = splitted.shift();
  142. locationCopy.forward_path = `/${splitted.join('/')}`;
  143. }
  144. // eslint-disable-next-line
  145. renderedLocations += await renderer.parseAndRender(template, locationCopy);
  146. }
  147. };
  148. locationRendering().then(() => resolve(renderedLocations));
  149. });
  150. },
  151. /**
  152. * @param {String} host_type
  153. * @param {Object} host
  154. * @returns {Promise}
  155. */
  156. generateConfig: (host_type, host) => {
  157. host_type = host_type.replace(new RegExp('-', 'g'), '_');
  158. if (debug_mode) {
  159. logger.info('Generating ' + host_type + ' Config:', host);
  160. }
  161. let renderEngine = new Liquid({
  162. root: __dirname + '/../templates/'
  163. });
  164. return new Promise((resolve, reject) => {
  165. let template = null;
  166. let filename = internalNginx.getConfigName(host_type, host.id);
  167. try {
  168. template = fs.readFileSync(__dirname + '/../templates/' + host_type + '.conf', {encoding: 'utf8'});
  169. } catch (err) {
  170. reject(new error.ConfigurationError(err.message));
  171. return;
  172. }
  173. let locationsPromise;
  174. let origLocations;
  175. // Manipulate the data a bit before sending it to the template
  176. if (host_type !== 'default') {
  177. host.use_default_location = true;
  178. if (typeof host.advanced_config !== 'undefined' && host.advanced_config) {
  179. host.use_default_location = !internalNginx.advancedConfigHasDefaultLocation(host.advanced_config);
  180. }
  181. }
  182. if (host.locations) {
  183. origLocations = [].concat(host.locations);
  184. locationsPromise = internalNginx.renderLocations(host).then((renderedLocations) => {
  185. host.locations = renderedLocations;
  186. });
  187. // Allow someone who is using / custom location path to use it, and skip the default / location
  188. _.map(host.locations, (location) => {
  189. if (location.path === '/') {
  190. host.use_default_location = false;
  191. }
  192. });
  193. } else {
  194. locationsPromise = Promise.resolve();
  195. }
  196. // Set the IPv6 setting for the host
  197. host.ipv6 = internalNginx.ipv6Enabled();
  198. locationsPromise.then(() => {
  199. renderEngine
  200. .parseAndRender(template, host)
  201. .then((config_text) => {
  202. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  203. if (debug_mode) {
  204. logger.success('Wrote config:', filename, config_text);
  205. }
  206. // Restore locations array
  207. host.locations = origLocations;
  208. resolve(true);
  209. })
  210. .catch((err) => {
  211. if (debug_mode) {
  212. logger.warn('Could not write ' + filename + ':', err.message);
  213. }
  214. reject(new error.ConfigurationError(err.message));
  215. });
  216. });
  217. });
  218. },
  219. /**
  220. * This generates a temporary nginx config listening on port 80 for the domain names listed
  221. * in the certificate setup. It allows the letsencrypt acme challenge to be requested by letsencrypt
  222. * when requesting a certificate without having a hostname set up already.
  223. *
  224. * @param {Object} certificate
  225. * @returns {Promise}
  226. */
  227. generateLetsEncryptRequestConfig: (certificate) => {
  228. if (debug_mode) {
  229. logger.info('Generating LetsEncrypt Request Config:', certificate);
  230. }
  231. let renderEngine = new Liquid({
  232. root: __dirname + '/../templates/'
  233. });
  234. return new Promise((resolve, reject) => {
  235. let template = null;
  236. let filename = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  237. try {
  238. template = fs.readFileSync(__dirname + '/../templates/letsencrypt-request.conf', {encoding: 'utf8'});
  239. } catch (err) {
  240. reject(new error.ConfigurationError(err.message));
  241. return;
  242. }
  243. certificate.ipv6 = internalNginx.ipv6Enabled();
  244. renderEngine
  245. .parseAndRender(template, certificate)
  246. .then((config_text) => {
  247. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  248. if (debug_mode) {
  249. logger.success('Wrote config:', filename, config_text);
  250. }
  251. resolve(true);
  252. })
  253. .catch((err) => {
  254. if (debug_mode) {
  255. logger.warn('Could not write ' + filename + ':', err.message);
  256. }
  257. reject(new error.ConfigurationError(err.message));
  258. });
  259. });
  260. },
  261. /**
  262. * This removes the temporary nginx config file generated by `generateLetsEncryptRequestConfig`
  263. *
  264. * @param {Object} certificate
  265. * @param {Boolean} [throw_errors]
  266. * @returns {Promise}
  267. */
  268. deleteLetsEncryptRequestConfig: (certificate, throw_errors) => {
  269. return new Promise((resolve, reject) => {
  270. try {
  271. let config_file = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  272. if (debug_mode) {
  273. logger.warn('Deleting nginx config: ' + config_file);
  274. }
  275. fs.unlinkSync(config_file);
  276. } catch (err) {
  277. if (debug_mode) {
  278. logger.warn('Could not delete config:', err.message);
  279. }
  280. if (throw_errors) {
  281. reject(err);
  282. }
  283. }
  284. resolve();
  285. });
  286. },
  287. /**
  288. * @param {String} host_type
  289. * @param {Object} [host]
  290. * @param {Boolean} [throw_errors]
  291. * @returns {Promise}
  292. */
  293. deleteConfig: (host_type, host, throw_errors) => {
  294. host_type = host_type.replace(new RegExp('-', 'g'), '_');
  295. return new Promise((resolve, reject) => {
  296. try {
  297. let config_file = internalNginx.getConfigName(host_type, typeof host === 'undefined' ? 0 : host.id);
  298. if (debug_mode) {
  299. logger.warn('Deleting nginx config: ' + config_file);
  300. }
  301. fs.unlinkSync(config_file);
  302. } catch (err) {
  303. if (debug_mode) {
  304. logger.warn('Could not delete config:', err.message);
  305. }
  306. if (throw_errors) {
  307. reject(err);
  308. }
  309. }
  310. resolve();
  311. });
  312. },
  313. /**
  314. * @param {String} host_type
  315. * @param {Array} hosts
  316. * @returns {Promise}
  317. */
  318. bulkGenerateConfigs: (host_type, hosts) => {
  319. let promises = [];
  320. hosts.map(function (host) {
  321. promises.push(internalNginx.generateConfig(host_type, host));
  322. });
  323. return Promise.all(promises);
  324. },
  325. /**
  326. * @param {String} host_type
  327. * @param {Array} hosts
  328. * @param {Boolean} [throw_errors]
  329. * @returns {Promise}
  330. */
  331. bulkDeleteConfigs: (host_type, hosts, throw_errors) => {
  332. let promises = [];
  333. hosts.map(function (host) {
  334. promises.push(internalNginx.deleteConfig(host_type, host, throw_errors));
  335. });
  336. return Promise.all(promises);
  337. },
  338. /**
  339. * @param {string} config
  340. * @returns {boolean}
  341. */
  342. advancedConfigHasDefaultLocation: function (config) {
  343. return !!config.match(/^(?:.*;)?\s*?location\s*?\/\s*?{/im);
  344. },
  345. /**
  346. * @returns {boolean}
  347. */
  348. ipv6Enabled: function () {
  349. if (typeof process.env.DISABLE_IPV6 !== 'undefined') {
  350. const disabled = process.env.DISABLE_IPV6.toLowerCase();
  351. return !(disabled === 'on' || disabled === 'true' || disabled === '1' || disabled === 'yes');
  352. }
  353. return true;
  354. }
  355. };
  356. module.exports = internalNginx;