UNPKG

3.43 kBJavaScriptView Raw
1var cluster = require('cluster');
2var os = require('os');
3var numCPUs = os.cpus().length;
4var express = require('./express');
5var zxy = require('zxy-comm');
6var _ = require('underscore');
7
8var runNode = function (conf, all, middleware) {
9 var singleCoreProcess;
10 if (process.argv) {
11 if (process.argv.length) {
12 singleCoreProcess = process.argv[process.argv.length - 1].indexOf('-d') == 0 ? true : false
13 }
14 else {
15 singleCoreProcess = process.argv[0].indexOf('-d') == 0 ? true : false
16 }
17 }
18 if (cluster.isMaster && !singleCoreProcess) {
19 var isfirstCore = true;
20 var firstCorePid = 0;
21 require('os').cpus().forEach(function () {
22 var worker = cluster.fork();
23 if (isfirstCore) {
24 firstCorePid = worker.process.pid;
25 isfirstCore = false;
26 runjob();
27 }
28 });
29 cluster.on('exit', function (worker, code, signal) {
30 var pid = worker.process.pid;
31 console.warn('process[' + pid + '] with #' + worker.id + ' exit');
32 worker = cluster.fork();
33 if (firstCorePid == pid) {
34 firstCorePid = worker.process.pid;
35 // runjob();
36 }
37 })
38 .on("death", function (worker) {
39 var pid = worker.process.pid;
40 console.warn('process[' + pid + '] with #' + worker.id + ' death');
41 worker = cluster.fork();
42 if (firstCorePid == pid) {
43 firstCorePid = worker.process.pid;
44 // runjob();
45 }
46 })
47 .on('listening', function (worker, address) {
48 var serverip = zxy.app.m_obtain.getServerIP();
49 console.info("process[" + worker.process.pid + "] with #" + worker.id + " express server listening on " + serverip + ":" + address.port);
50 });
51 Object.keys(cluster.workers).forEach(function (id) {
52 cluster.workers[id].on('message', function (msg) {
53 console.info("process[" + cluster.workers[id].process.pid + "] with #" + id, msg);
54 });
55 });
56 } else {
57 express.runExpress(conf.express, middleware);
58 if (all) {
59 zxy.runMysql(conf.mysql);
60 process.send && process.send("being connected to the MySQL server " + conf.mysql.host + ":" + (conf.mysql.port ? conf.mysql.port : 3306));
61 // process.send && process.send("mysql connected to " + conf.mysql.host + ":" + (conf.mysql.port ? conf.mysql.port : 3306));
62 zxy.runRedis(conf.redis);
63 process.send && process.send("being connected to the Redis server " + conf.redis.host + ":" + (conf.redis.port ? conf.redis.port : 6379));
64 // process.send && process.send("redis connected to " + conf.redis.host + ":" + (conf.redis.port ? conf.redis.port : 6379));
65 }
66 }
67}
68exports.runNode = runNode;
69
70function runjob() {
71 if (zxy.app.f_job) {
72 if (zxy.app.m_verify.isArray(zxy.app.f_job)) {
73 _.each(zxy.app.f_job, function (job) {
74 if (zxy.app.m_verify.isJson(job)) {
75 var job = new require('./comm/job').jobObj(job.conf, job.func, job.params, job.name);
76 }
77 });
78 }
79 }
80}
\No newline at end of file