manager.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const EventEmitter = require('events');
  3. // worker manager to record agent and worker forked by egg-cluster
  4. // can do some check stuff here to monitor the healthy
  5. class Manager extends EventEmitter {
  6. constructor() {
  7. super();
  8. this.workers = new Map();
  9. this.agent = null;
  10. }
  11. setAgent(agent) {
  12. this.agent = agent;
  13. }
  14. deleteAgent() {
  15. this.agent = null;
  16. }
  17. setWorker(worker) {
  18. this.workers.set(worker.process.pid, worker);
  19. }
  20. getWorker(pid) {
  21. return this.workers.get(pid);
  22. }
  23. deleteWorker(pid) {
  24. this.workers.delete(pid);
  25. }
  26. listWorkerIds() {
  27. return Array.from(this.workers.keys());
  28. }
  29. getListeningWorkerIds() {
  30. const keys = [];
  31. for (const id of this.workers.keys()) {
  32. if (this.getWorker(id).state === 'listening') {
  33. keys.push(id);
  34. }
  35. }
  36. return keys;
  37. }
  38. count() {
  39. return {
  40. agent: (this.agent && this.agent.status === 'started') ? 1 : 0,
  41. worker: this.listWorkerIds().length,
  42. };
  43. }
  44. // check agent and worker must both alive
  45. // if exception appear 3 times, emit an exception event
  46. startCheck() {
  47. this.exception = 0;
  48. this.timer = setInterval(() => {
  49. const count = this.count();
  50. if (count.agent && count.worker) {
  51. this.exception = 0;
  52. return;
  53. }
  54. this.exception++;
  55. if (this.exception >= 3) {
  56. this.emit('exception', count);
  57. clearInterval(this.timer);
  58. }
  59. }, 10000);
  60. }
  61. }
  62. module.exports = Manager;