socketcluster icon indicating copy to clipboard operation
socketcluster copied to clipboard

How to restart all workers from worker.js

Open hirbod opened this issue 7 years ago • 7 comments

Hi,

I wasn't able to find a documentation what "SIGUSR2" is. How can I restart all workers inside of my worker.js

hirbod avatar May 17 '18 19:05 hirbod

@jondubois may I ask for a litte snippet how to trigger a restart inside of the worker.js for all workers? Currently I am doing some dirty hacks.. (touching a file inside of my app-dir, which force the restart)

hirbod avatar May 17 '18 20:05 hirbod

@Hirbod You can't restart other workers directly from a worker, but you can send a message from a worker to the master process using worker.sendToMaster(data, [callback]) and then from the master process (server.js) you can restart all workers with socketCluster.killWorkers().

jondubois avatar May 18 '18 18:05 jondubois

How can I listen to "sendToMaster" events?

hirbod avatar May 18 '18 20:05 hirbod

@jondubois ?

hirbod avatar Jun 08 '18 21:06 hirbod

@Hirbod kill -SIGUSR2 12345 <--- that's the Master PID

I use PM2 for server process management so you can easily get the master PID if you're using PM2 with the following command. grep 'aster' ~/.pm2/logs/fusion-out-5.log

or wherever your log file is at

happilymarrieddad avatar Jun 08 '18 22:06 happilymarrieddad

PM2 shouldn't be used with socketcluster as far as I know. (socketcluster does that scaling stuff itself). Therefore, I switched to "forever".

hirbod avatar Jun 08 '18 22:06 hirbod

PM2 shouldn't be used with socketcluster as far as I know.

It's totally fine to use SC with PM2. I do like to use PM2 (with SC and not only), because of it's simplistic way to deploy apps to VPS/VDS. Typically, when you use SC with PM2, you just don't use PM2 features for vertical scaling, The rest is good.

As well as much more else, it's up to you to decide who'll control the lifecycle of a SC-based app. You're free to replace/remove sc-hot-reload https://github.com/SocketCluster/socketcluster/blob/master/sample/server.js#L76-L79 Configurate killMasterOnSignal, rebootOnSignal, and so on.

How can I listen to "sendToMaster" events?

Worker, like if we were inside run() method:

this.sendToMaster(payload, callback) // callback is optional

Master:

socketCluster.on('workerMessage', (payload, callback) => {
  console.info(`workerMessage: ${payload}`)
  if (payload === 'banzai') {
    socketCluster.killWorkers()
    socketCluster.killBrokers()
  }
  callback && callback()
})

p.s. 1. I didn't test these pieces of code, mb there is a typo or two :slightly_smiling_face: 2. forever is just fine too.

MegaGM avatar Jun 09 '18 11:06 MegaGM