kernel.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. WIKI.queue.start()
  54. cluster.on('exit', (worker, code, signal) => {
  55. if (!global.DEV) {
  56. WIKI.logger.info(`Background Worker #${worker.id} was terminated.`)
  57. }
  58. })
  59. },
  60. /**
  61. * Boot Worker Process
  62. */
  63. bootWorker() {
  64. WIKI.logger.info(`Background Worker #${cluster.worker.id} is initializing...`)
  65. require('../worker')
  66. },
  67. /**
  68. * Spawn new Worker process
  69. */
  70. spawnWorker() {
  71. this.workers.push(cluster.fork())
  72. },
  73. /**
  74. * Set Worker count based on config + system capabilities
  75. */
  76. setWorkerLimit() {
  77. const numCPUs = require('os').cpus().length
  78. this.numWorkers = (WIKI.config.workers > 0) ? WIKI.config.workers : numCPUs
  79. if (this.numWorkers > numCPUs) {
  80. this.numWorkers = numCPUs
  81. }
  82. }
  83. }