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.

93 lines
2.2 KiB

  1. const cluster = require('cluster')
  2. const Promise = require('bluebird')
  3. const _ = require('lodash')
  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. wiki.logger.info(`Background Worker #${worker.id} was terminated.`)
  61. })
  62. },
  63. /**
  64. * Boot Worker Process
  65. */
  66. bootWorker() {
  67. wiki.logger.info(`Background Worker #${cluster.worker.id} is initializing...`)
  68. require('../worker')
  69. },
  70. /**
  71. * Spawn new Worker process
  72. */
  73. spawnWorker() {
  74. this.workers.push(cluster.fork())
  75. },
  76. /**
  77. * Set Worker count based on config + system capabilities
  78. */
  79. setWorkerLimit() {
  80. const numCPUs = require('os').cpus().length
  81. this.numWorkers = (wiki.config.workers > 0) ? wiki.config.workers : numCPUs
  82. if (this.numWorkers > numCPUs) {
  83. this.numWorkers = numCPUs
  84. }
  85. }
  86. }