UNPKG

2.81 kBJavaScriptView Raw
1/**
2 * Copyright 2013-2021 the PM2 project authors. All rights reserved.
3 * Use of this source code is governed by a license that
4 * can be found in the LICENSE file.
5 */
6'use strict';
7
8/**
9 * @file Cluster execution functions related
10 * @author Alexandre Strzelewicz <as@unitech.io>
11 * @project PM2
12 */
13var cluster = require('cluster');
14var Utility = require('../Utility.js');
15var pkg = require('../../package.json');
16
17/**
18 * Description
19 * @method exports
20 * @param {} God
21 * @return
22 */
23module.exports = function ClusterMode(God) {
24
25 /**
26 * For Node apps - Cluster mode
27 * It will wrap the code and enable load-balancing mode
28 * @method nodeApp
29 * @param {} env_copy
30 * @param {} cb
31 * @return Literal
32 */
33 God.nodeApp = function nodeApp(env_copy, cb){
34 var clu = null;
35
36 console.log(`App [${env_copy.name}:${env_copy.pm_id}] starting in -cluster mode-`)
37 if (env_copy.node_args && Array.isArray(env_copy.node_args)) {
38 cluster.settings.execArgv = env_copy.node_args;
39 }
40
41 env_copy._pm2_version = pkg.version;
42
43 try {
44 // node.js cluster clients can not receive deep-level objects or arrays in the forked process, e.g.:
45 // { "args": ["foo", "bar"], "env": { "foo1": "bar1" }} will be parsed to
46 // { "args": "foo, bar", "env": "[object Object]"}
47 // So we passing a stringified JSON here.
48 clu = cluster.fork({pm2_env: JSON.stringify(env_copy), windowsHide: true});
49 } catch(e) {
50 God.logAndGenerateError(e);
51 return cb(e);
52 }
53
54 clu.pm2_env = env_copy;
55
56 /**
57 * Broadcast message to God
58 */
59 clu.on('message', function cluMessage(msg) {
60 /*********************************
61 * If you edit this function
62 * Do the same in ForkMode.js !
63 *********************************/
64 if (msg.data && msg.type) {
65 return God.bus.emit(msg.type ? msg.type : 'process:msg', {
66 at : Utility.getDate(),
67 data : msg.data,
68 process : {
69 pm_id : clu.pm2_env.pm_id,
70 name : clu.pm2_env.name,
71 rev : (clu.pm2_env.versioning && clu.pm2_env.versioning.revision) ? clu.pm2_env.versioning.revision : null,
72 namespace : clu.pm2_env.namespace
73 }
74 });
75 }
76 else {
77
78 if (typeof msg == 'object' && 'node_version' in msg) {
79 clu.pm2_env.node_version = msg.node_version;
80 return false;
81 }
82
83 return God.bus.emit('process:msg', {
84 at : Utility.getDate(),
85 raw : msg,
86 process : {
87 pm_id : clu.pm2_env.pm_id,
88 name : clu.pm2_env.name,
89 namespace : clu.pm2_env.namespace
90 }
91 });
92 }
93 });
94
95 return cb(null, clu);
96 };
97};