pomelo源码分析(1)

pomelo源码分析(1)

一、app init

首先我们来分析一下

// at app.ts
var app = pinus.createApp();

紧接着会调用 app.init(opts) 初始化

	// at pinus.ts
    createApp(opts ?: ApplicationOptions) {
        let app = new Application();
        app.init(opts);
        this._app = app;
        return app;
    }

继续往下看

	// at application.ts
    init(opts ?: ApplicationOptions) {
        opts = opts || {};
        let base = opts.base || process.cwd();
        this.set(Constants.RESERVED.BASE, base);
        this.base = base;

        appUtil.defaultConfiguration(this);

        this.state = STATE_INITED;
        logger.info('application inited: %j', this.getServerId());
    }

我们重点看appUtil.defaultConfiguration(this)

// at appUitl.ts
export function defaultConfiguration(app: Application) {
	// Parse command line arguments
    let args = parseArgs(process.argv);
    // Setup enviroment
    setupEnv(app, args);
    // Load master info from config/master.json.
    loadMaster(app);
    // Load server info from config/servers.json.
    loadServers(app);
    // Process server start command
    processArgs(app, args);
    // Configure custom logger
    configLogger(app);
    // Load lifecycle file.
    loadLifecycle(app);
}

可以看到 最后初始化其实干了这些事 我们来依次分析一下。

1.passeArgs

这个方法官方注释的解释是Parse command line arguments,解析命令行参数。我在本地调试的时候,process.argv的值是一个由2个元素组成的数组[“C:\Program Files\nodejs\node.exe”,“D:\code\project\dist\app.js”],方法最后返回一个字符串"D:\code\project\dist\app.js"。

2.setupEnv(app, args)

设置环境

3.loadMaster(app)

往下看代码

// at appUitl.ts
let loadMaster = function (app: Application) {
	// Constants.RESERVED.MASTER = 'master'
	// Constants.FILEPATH.MASTER = '/config/master.json'
    app.loadConfigBaseApp(Constants.RESERVED.MASTER, Constants.FILEPATH.MASTER);
    app.master = app.get(Constants.RESERVED.MASTER);
};
	// at application.ts
    loadConfigBaseApp(key: string, val: string, reload = false) {
        let self = this;
        let env = this.get(Constants.RESERVED.ENV);
        let originPath = path.join(this.getBase(), val);
        let presentPath = path.join(this.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(val));
        let realPath: string;
        if (fs.existsSync(originPath)) {
            realPath = originPath;
            let file = require(originPath);
            if (file[env]) {
                file = file[env];
            }
            // 把解析结果存放到map里
            this.set(key, file);
        } else if (fs.existsSync(presentPath)) {
            realPath = presentPath;
            let pfile = require(presentPath);
            // 把解析结果存放到map里
            this.set(key, pfile);
        } else {
            logger.error('invalid configuration with file path: %s', key);
        }

        if (!!realPath && !!reload) {
            fs.watch(realPath, function (event, filename) {
                if (event === 'change') {
                    delete require.cache[require.resolve(realPath)];
                    self.loadConfigBaseApp(key, val);
                }
            });
        }
    }

这段代码的作用是解析配置文件,并存到map里,所有,这段代码之前的 app.master 就可以赋值成功了。

   app.master = app.get(Constants.RESERVED.MASTER);

好了,我们现在知道了这句代码就是加载/config/master.json的配置,并放到key为Constants.RESERVED.MASTER的map里

4.loadServers(app);

流程跟**loadMaster(app)**基本一样,加载/config/servers.json的配置,但是最后要把所有serverId放到serverMap里,并把serverMap放到key为Constants.KEYWORDS.SERVER_MAP的map里。

// at appUitl.ts
let loadServers = function (app: Application) {
    app.loadConfigBaseApp(Constants.RESERVED.SERVERS, Constants.FILEPATH.SERVER);
    let servers = app.get(Constants.RESERVED.SERVERS);
    let serverMap: {[serverId: string]: ServerInfo} = {}, slist, i, l, server;
    for (let serverType in servers) {
        slist = servers[serverType];
        for (i = 0, l = slist.length; i < l; i++) {
            server = slist[i];
            server.serverType = serverType;
            if (server[Constants.RESERVED.CLUSTER_COUNT]) {
                utils.loadCluster(app, server, serverMap);
                continue;
            }
            serverMap[server.id] = server;
            if (server.wsPort) {
                logger.warn('wsPort is deprecated, use clientPort in frontend server instead, server: %j', server);
            }
        }
    }
    app.set(Constants.KEYWORDS.SERVER_MAP, serverMap);
};

5.processArgs(app, args)

进程服务器启动命令

6.configLogger(app)

根据文件/config/log4js.json来配置自定义日志

7.loadLifecycle(app)

加载lifecycle文件

二、app start

初始化完成后

// at aplication.ts
start(cb ?: (err ?: Error , result ?: void) => void) {
        this.startTime = Date.now();
        if (this.state > STATE_INITED) {
            utils.invokeCallback(cb, new Error('application has already start.'));
            return;
        }

        let self = this;
        appUtil.startByType(self, function () {
            appUtil.loadDefaultComponents(self);
            let startUp = function () {
                self.state = STATE_BEFORE_START;
                logger.info('%j enter before start...', self.getServerId());

                appUtil.optComponents(self.loaded, Constants.RESERVED.BEFORE_START, function (err) {
                    if (err) {
                        utils.invokeCallback(cb, err);
                    } else {
                        logger.info('%j enter after start...', self.getServerId());

                        appUtil.optComponents(self.loaded, Constants.RESERVED.START, function (err) {
                            self.state = STATE_START;
                            if (err) {
                                utils.invokeCallback(cb, err);
                            } else {
                                logger.info('%j enter after start...', self.getServerId());
                                self.afterStart(cb);
                            }
                        });
                    }
                });

            };

            appUtil.optLifecycles(self.usedPlugins, Constants.LIFECYCLE.BEFORE_STARTUP, self, function (err) {
                if (err) {
                    utils.invokeCallback(cb, err);
                } else {
                    startUp();
                }
            });
        });
    }

通过代码可以看出,我们可以看出调用流程如下:

  1. appUtil.startByType
  2. appUtil.loadDefaultComponents
  3. appUtil.optLifecycles
  4. startUp

我们先来看下appUtil.startByType的流程:

// at appUtils.ts
export function startByType(app: Application, cb: (err?: Error) => void) {
    if (!!app.startId) {
        if (app.startId === Constants.RESERVED.MASTER) {
            utils.invokeCallback(cb);
        } else {
            starter.runServers(app);
        }
    } else {
        if (!!app.type && app.type !== Constants.RESERVED.ALL && app.type !== Constants.RESERVED.MASTER) {
            starter.runServers(app);
        } else {
            utils.invokeCallback(cb);
        }
    }
}

可以看出,这个方法有两个分支,当调用starter.runServers(app),方法就不会回调了,直接启动进程,也就没有流程2,3,4了。如果调用utils.invokeCallback(cb),说明启动服务交给下面的流程进行了。

当调用utils.invokeCallback(cb),进入流程2

// at appUtil.ts
export function loadDefaultComponents(app: Application) {
    // load system default components
    if (app.serverType === Constants.RESERVED.MASTER) {
        app.load(pinus.components.master, app.get('masterConfig'));
    } else {
        app.load(pinus.components.proxy, app.get('proxyConfig'));
        if (app.getCurServer().port) {
            app.load(pinus.components.remote, app.get('remoteConfig'));
        }
        if (app.isFrontend()) {
            app.load(pinus.components.connection, app.get('connectionConfig'));
            app.load(pinus.components.connector, app.get('connectorConfig'));
            app.load(pinus.components.session, app.get('sessionConfig'));
            // compatible for schedulerConfig
            if (app.get('schedulerConfig')) {
                app.load(pinus.components.pushScheduler, app.get('schedulerConfig'));
            } else {
                app.load(pinus.components.pushScheduler, app.get('pushSchedulerConfig'));
            }
        }
        app.load(pinus.components.backendSession, app.get('backendSessionConfig'));
        app.load(pinus.components.channel, app.get('channelConfig'));
        app.load(pinus.components.server, app.get('serverConfig'));
    }
    app.load(pinus.components.monitor, app.get('monitorConfig'));
}

流程2在这时候会进入条件1,执行 app.load(pinus.components.master, app.get(‘masterConfig’)),加载master组件。

流程3没啥东西,我们看下流程4,startUp 方法会执行appUtil.optComponents:

// at appUtil.ts
export function optComponents(comps: IComponent[], method: string, cb: (err?: Error) => void) {
    let i = 0;
    async.forEachSeries(comps, function (comp, done) {
        i++;
        if (typeof (comp as any)[method] === 'function') {
            (comp as any)[method](done);
        } else {
            done();
        }
    }, function (err: Error) {
        if (err) {
            if (typeof err === 'string') {
                logger.error('fail to operate component, method: %s, err: %j', method, err);
            } else {
                logger.error('fail to operate component, method: %s, err: %j', method, err.stack);
            }
        }
        utils.invokeCallback(cb, err);
    });
}

当第一次执行appUtil.optComponents,typeof (comp as any)[method] === 'function’为false,会调用回调,回调方法又会调用一次appUtil.optComponents,这时候typeof (comp as any)[method] === 'function’为true,这是候会直接调用(comp as any)[method],最后会调用starter.runServers来启动服务

// at starter.ts
export function runServers(app: Application) {
    let server, servers;
    let condition = app.startId || app.type;
    switch (condition) {
        case Constants.RESERVED.MASTER:
            break;
        case Constants.RESERVED.ALL:
            servers = app.getServersFromConfig();
            for (let serverId in servers) {
                run(app, servers[serverId]);
            }
            break;
        default:
            server = app.getServerFromConfig(condition);
            if (!!server) {
                run(app, server);
            } else {
                servers = app.get(Constants.RESERVED.SERVERS)[condition];
                for (let i = 0; i < servers.length; i++) {
                    run(app, servers[i]);
                }
            }
    }
}

可以看到,当condition为Constants.RESERVED.ALL时,会依次启动所有服务。

阅读更多
换一批

没有更多推荐了,返回首页