wikijs-fork/server/core/kernel.js

96 lines
2.3 KiB
JavaScript
Raw Normal View History

const _ = require('lodash')
2017-10-08 02:44:35 +00:00
const cluster = require('cluster')
const Promise = require('bluebird')
/* global WIKI */
2017-10-08 02:44:35 +00:00
module.exports = {
numWorkers: 1,
workers: [],
init() {
if (cluster.isMaster) {
WIKI.logger.info('=======================================')
WIKI.logger.info('= WIKI.js =============================')
WIKI.logger.info('=======================================')
2017-10-08 02:44:35 +00:00
WIKI.redis = require('./redis').init()
WIKI.queue = require('./queue').init()
2017-10-08 02:44:35 +00:00
this.setWorkerLimit()
this.bootMaster()
} else {
this.bootWorker()
}
},
/**
* Pre-Master Boot Sequence
*/
preBootMaster() {
return Promise.mapSeries([
() => { return WIKI.db.onReady },
() => { return WIKI.configSvc.loadFromDb() },
() => { return WIKI.queue.clean() }
2017-10-08 02:44:35 +00:00
], fn => { return fn() })
},
/**
* Boot Master Process
*/
bootMaster() {
this.preBootMaster().then(sequenceResults => {
if (_.every(sequenceResults, rs => rs === true) && WIKI.config.configMode !== 'setup') {
2017-10-08 02:44:35 +00:00
this.postBootMaster()
} else {
WIKI.logger.info('Starting configuration manager...')
2017-12-24 05:34:47 +00:00
require('../setup')()
2017-10-08 02:44:35 +00:00
}
return true
}).catch(err => {
WIKI.logger.error(err)
2017-10-08 02:44:35 +00:00
process.exit(1)
})
},
/**
* Post-Master Boot Sequence
*/
2017-12-24 05:34:47 +00:00
async postBootMaster() {
await require('../master')()
2017-10-08 02:44:35 +00:00
2017-12-24 05:34:47 +00:00
_.times(this.numWorkers, () => {
this.spawnWorker()
})
WIKI.queue.uplClearTemp.add({}, {
2017-12-24 05:34:47 +00:00
repeat: { cron: '*/15 * * * *' }
2017-10-08 02:44:35 +00:00
})
cluster.on('exit', (worker, code, signal) => {
2018-01-27 05:20:49 +00:00
if (!global.DEV) {
WIKI.logger.info(`Background Worker #${worker.id} was terminated.`)
2018-01-27 05:20:49 +00:00
}
2017-10-08 02:44:35 +00:00
})
},
/**
* Boot Worker Process
*/
bootWorker() {
WIKI.logger.info(`Background Worker #${cluster.worker.id} is initializing...`)
2017-10-08 02:44:35 +00:00
require('../worker')
},
/**
* Spawn new Worker process
*/
spawnWorker() {
this.workers.push(cluster.fork())
},
/**
* Set Worker count based on config + system capabilities
*/
setWorkerLimit() {
const numCPUs = require('os').cpus().length
this.numWorkers = (WIKI.config.workers > 0) ? WIKI.config.workers : numCPUs
2017-10-08 02:44:35 +00:00
if (this.numWorkers > numCPUs) {
this.numWorkers = numCPUs
}
}
}