You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.3 KiB

  1. const _ = require('lodash')
  2. const cluster = require('cluster')
  3. const Promise = require('bluebird')
  4. /* global WIKI */
  5. module.exports = {
  6. numWorkers: 1,
  7. workers: [],
  8. init() {
  9. if (cluster.isMaster) {
  10. WIKI.logger.info('=======================================')
  11. WIKI.logger.info('= WIKI.js =============================')
  12. WIKI.logger.info('=======================================')
  13. WIKI.redis = require('./redis').init()
  14. WIKI.queue = require('./queue').init()
  15. this.setWorkerLimit()
  16. this.bootMaster()
  17. } else {
  18. this.bootWorker()
  19. }
  20. },
  21. /**
  22. * Pre-Master Boot Sequence
  23. */
  24. preBootMaster() {
  25. return Promise.mapSeries([
  26. () => { return WIKI.db.onReady },
  27. () => { return WIKI.configSvc.loadFromDb() },
  28. () => { return WIKI.queue.clean() }
  29. ], fn => { return fn() })
  30. },
  31. /**
  32. * Boot Master Process
  33. */
  34. bootMaster() {
  35. this.preBootMaster().then(sequenceResults => {
  36. if (_.every(sequenceResults, rs => rs === true) && WIKI.config.configMode !== 'setup') {
  37. this.postBootMaster()
  38. } else {
  39. WIKI.logger.info('Starting configuration manager...')
  40. require('../setup')()
  41. }
  42. return true
  43. }).catch(err => {
  44. WIKI.logger.error(err)
  45. process.exit(1)
  46. })
  47. },
  48. /**
  49. * Post-Master Boot Sequence
  50. */
  51. async postBootMaster() {
  52. await require('../master')()
  53. _.times(this.numWorkers, () => {
  54. this.spawnWorker()
  55. })
  56. WIKI.queue.uplClearTemp.add({}, {
  57. repeat: { cron: '*/15 * * * *' }
  58. })
  59. cluster.on('exit', (worker, code, signal) => {
  60. if (!global.DEV) {
  61. WIKI.logger.info(`Background Worker #${worker.id} was terminated.`)
  62. }
  63. })
  64. },
  65. /**
  66. * Boot Worker Process
  67. */
  68. bootWorker() {
  69. WIKI.logger.info(`Background Worker #${cluster.worker.id} is initializing...`)
  70. require('../worker')
  71. },
  72. /**
  73. * Spawn new Worker process
  74. */
  75. spawnWorker() {
  76. this.workers.push(cluster.fork())
  77. },
  78. /**
  79. * Set Worker count based on config + system capabilities
  80. */
  81. setWorkerLimit() {
  82. const numCPUs = require('os').cpus().length
  83. this.numWorkers = (WIKI.config.workers > 0) ? WIKI.config.workers : numCPUs
  84. if (this.numWorkers > numCPUs) {
  85. this.numWorkers = numCPUs
  86. }
  87. }
  88. }