15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
const path = require('path');
const EventEmitter = require('events');
const { fork } = require('child_process');
const serialize = require('serialize-javascript');
const Log = require('../../log');
const Ps = require('../../ps');
const Channel = require('../../const/channel');
const Helper = require('../../utils/helper');
 
class ForkProcess {
  constructor(host, opt = {}) {
    
    let cwd = Ps.getHomeDir();
    let appPath = path.join(__dirname, 'app.js');
    if (Ps.isPackaged()) {
      // todo fork的cwd目录为什么要在app.asar外 ?
      cwd = path.join(Ps.getHomeDir(), '..');
    }
 
    // TODO Object.assign 只能单层对象结构,多层的对象会直接覆盖
    let options = Object.assign({
      processArgs: {},
      processOptions: { 
        cwd: cwd,
        env: Ps.allEnv(), 
        stdio: 'ignore' // pipe
      }
    }, opt);
 
    this.emitter = new EventEmitter();
    this.host = host;
    this.args = [];
    this.sleeping = false;
 
    // 传递给子进程的参数
    this.args.push(JSON.stringify(options.processArgs));
 
    this.child = fork(appPath, this.args, options.processOptions);
    this.pid = this.child.pid;
    this._init();
  }
 
  /**
   * 初始化事件监听
   */
  _init() {
    const { messageLog } = this.host.config;
    this.child.on('message', (m) => {
      if (messageLog == true) {
        Log.coreLogger.info(`[ee-core] [jobs/child] received a message from child-process, message: ${serialize(m)}`);
      }
      
      if (m.channel == Channel.process.showException) {
        Log.coreLogger.error(`${m.data}`);
      }
 
      // 收到子进程消息,转发到 event 
      if (m.channel == Channel.process.sendToMain) {
        this._eventEmit(m);
      }
    });
 
    this.child.on('exit', (code, signal) => {
      let data = {
        pid: this.pid
      }
      this.host.emit(Channel.events.childProcessExit, data);
      Log.coreLogger.info(`[ee-core] [jobs/child] received a exit from child-process, code:${code}, signal:${signal}, pid:${this.pid}`);
    });
 
    this.child.on('error', (err) => {
      let data = {
        pid: this.pid
      }
      this.host.emit(Channel.events.childProcessError, data);
      Log.coreLogger.error(`[ee-core] [jobs/child] received a error from child-process, error: ${err}, pid:${this.pid}`);
    });
  }
 
  /**
   * event emit
   */
  _eventEmit(m) {
    switch (m.eventReceiver) {
      case Channel.receiver.forkProcess:
        this.emitter.emit(m.event, m.data);
        break;
      case Channel.receiver.childJob:
        this.host.emit(m.event, m.data);
        break;    
      default:
        this.host.emit(m.event, m.data);
        this.emitter.emit(m.event, m.data);
        break;
    }
  }
  
  /**
   * 分发任务
   */
  dispatch(cmd, jobPath = '', params = {}) {
    // 消息对象
    const mid = Helper.getRandomString();
    let msg = {
      mid,
      cmd,
      jobPath,
      jobParams: params
    }
 
    // todo 是否会发生监听未完成时,接收不到消息?
    // 发消息到子进程
    this.child.send(msg);
  }
 
  /**
   * kill
   */
  kill(timeout = 1000) {
    this.child.kill('SIGINT');
    setTimeout(() => {
      if (this.child.killed) return;
      this.child.kill('SIGKILL');
    }, timeout)
  }
 
  /**
   * sleep (仅Unix平台)
   */
  sleep() {
    if (this.sleeping) return;
    process.kill(this.pid, 'SIGSTOP');
    this.sleeping = true;
  }
  
  /**
   * wakeup (仅Unix平台)
   */
  wakeup() {
    if (!this.sleeping) return;
    process.kill(this.pid, 'SIGCONT');
    this.sleeping = false;
  }
}
 
module.exports = ForkProcess;