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.

91 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)) {
  37. this.postBootMaster()
  38. } else {
  39. wiki.logger.info('Starting configuration manager...')
  40. require('../configure')()
  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. postBootMaster() {
  52. require('../master')().then(() => {
  53. _.times(this.numWorker, this.spawnWorker)
  54. wiki.queue.uplClearTemp.add({}, {
  55. repeat: { cron: '*/15 * * * *' }
  56. })
  57. })
  58. cluster.on('exit', (worker, code, signal) => {
  59. wiki.logger.info(`Background Worker #${worker.id} was terminated.`)
  60. })
  61. },
  62. /**
  63. * Boot Worker Process
  64. */
  65. bootWorker() {
  66. wiki.logger.info(`Background Worker #${cluster.worker.id} is initializing...`)
  67. require('../worker')
  68. },
  69. /**
  70. * Spawn new Worker process
  71. */
  72. spawnWorker() {
  73. this.workers.push(cluster.fork())
  74. },
  75. /**
  76. * Set Worker count based on config + system capabilities
  77. */
  78. setWorkerLimit() {
  79. const numCPUs = require('os').cpus().length
  80. this.numWorkers = (wiki.config.workers > 0) ? wiki.config.workers : numCPUs
  81. if (this.numWorkers > numCPUs) {
  82. this.numWorkers = numCPUs
  83. }
  84. }
  85. }