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