Switch to do a game preliminary analytical (2) Kbengine serverapp structure

Foreword

    As used herein, machine as an example. Why is it that the Machine? This had to start from keb startup script. For example start_server.bat beginning to start_server.bat barabara lot. Then start the first app
start %KBE_BIN_PATH%/machine.exe --cid=1000 --gus=1
Start the machine. So ..

text

Of course we also start from the main function

main function

...
int KBENGINE_MAIN(int argc, char* argv[])
{
#if KBE_PLATFORM != PLATFORM_WIN32
    rlimit rlimitData = { RLIM_INFINITY, RLIM_INFINITY };
    setrlimit(RLIMIT_CORE, &rlimitData);
#endif
    
    ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getKBMachine();
    int ret = kbeMainT<Machine>(argc, argv, MACHINE_TYPE, info.externalPorts_min, 
        info.externalPorts_max, "", 0, info.internalInterface);
    return ret; 
}
...

KBENGINE_MAIN definition

#if KBE_PLATFORM == PLATFORM_WIN32
#define KBENGINE_MAIN                       \
kbeMain(int argc, char* argv[]);            \
int main(int argc, char* argv[])            \
{                                           \
    loadConfig();                           \
    g_componentID = genUUID64();            \
    parseMainCommandArgs(argc, argv);       \
    char dumpname[MAX_BUF] = {0};           \
    kbe_snprintf(dumpname, MAX_BUF, "%"PRAppID, g_componentID);\
    KBEngine::exception::installCrashHandler(1, dumpname);     \
    int retcode = -1;                       \
    THREAD_TRY_EXECUTION;                   \
    retcode = kbeMain(argc, argv);          \
    THREAD_HANDLE_CRASH;                    \
    return retcode;                         \
}                                           \
int kbeMain
#else
#define KBENGINE_MAIN                       \
kbeMain(int argc, char* argv[]);            \
int main(int argc, char* argv[])            \
{                                           \
    loadConfig();                           \
    g_componentID = genUUID64();            \
    parseMainCommandArgs(argc, argv);       \
    return kbeMain(argc, argv);             \
}                                           \
int kbeMain
#endif

KBENGINE_MAIN did some Han

KBENGINE_MAIN let the app do all three things,
loadConfig();//载入配置信息,必须要说的事,这只是载入基本配置,如果是app特有的配置后续还会有
g_componentID = genUUID64();//生成app进程的唯一标示
parseMainCommandArgs(argc, argv);//解析Command参数,其实只有3种。 --cid=,--gus=还有--hide=

KBENGINE_MAIN definition of doubts

Here you should have two doubts:

Resmgr repeat initialization

In the Machine on the existence of a global variable leads Resmgr :: getSingleton () initialize () ;. Executes once before the main.
The strange thing is initialize () to determine whether there had originally been initialized, but are commented out.

Command --gus = parameter meaningless

In genUUID64 () will generate uuid g_genuuid_sections whether a valid value is used in two different ways according to.
but, surprisingly yes g_genuuid_sections is Command in --gus =. The Command's resolve actually in genUUID64 () after.

QTMD, no matter, we went on the Main function of the surface.

Kbeman

This uses a template kbeMainT

kbeMainT constructor

I have removed the print log of the code, this would look so simple a Diudiu. .


template <class SERVER_APP>
int kbeMainT(int argc, char * argv[], COMPONENT_TYPE componentType, 
             int32 extlisteningPort_min = -1, int32 extlisteningPort_max = -1, const char * extlisteningInterface = "",
             int32 intlisteningPort = 0, const char * intlisteningInterface = "")
{
    setEvns();
    startLeakDetection(componentType, g_componentID);
    g_componentType = componentType;
    DebugHelper::initialize(componentType);
    KBEKey kbekey(Resmgr::getSingleton().matchPath("key/") + "kbengine_public.key", 
        Resmgr::getSingleton().matchPath("key/") + "kbengine_private.key");
    Network::EventDispatcher dispatcher;
    DebugHelper::getSingleton().pDispatcher(&dispatcher);
    const ChannelCommon& channelCommon = g_kbeSrvConfig.channelCommon();
    Network::g_SOMAXCONN = g_kbeSrvConfig.tcp_SOMAXCONN(g_componentType);
    Network::NetworkInterface networkInterface(&dispatcher, 
        extlisteningPort_min, extlisteningPort_max, extlisteningInterface, 
        channelCommon.extReadBufferSize, channelCommon.extWriteBufferSize,
        (intlisteningPort != -1) ? htons(intlisteningPort) : -1, intlisteningInterface,
        channelCommon.intReadBufferSize, channelCommon.intWriteBufferSize);
    DebugHelper::getSingleton().pNetworkInterface(&networkInterface);
    g_kbeSrvConfig.updateInfos(true, componentType, g_componentID, 
            networkInterface.intaddr(), networkInterface.extaddr());
    Components::getSingleton().initialize(&networkInterface, componentType, g_componentID);
    SERVER_APP app(dispatcher, networkInterface, componentType, g_componentID);
    Components::getSingleton().findLogger();
    START_MSG(COMPONENT_NAME_EX(componentType), g_componentID);
    if(!app.initialize())
    {
        Components::getSingleton().finalise();
        app.finalise();
        // 如果还有日志未同步完成, 这里会继续同步完成才结束
        DebugHelper::getSingleton().finalise();
#if KBE_PLATFORM == PLATFORM_WIN32
        // 等待几秒,让用户能够在窗口上看到信息
        Beep(587, 500);
        KBEngine::sleep(5000);
#endif
        return -1;
    }
    int ret = app.run();
    Components::getSingleton().finalise();
    app.finalise();
    // 如果还有日志未同步完成, 这里会继续同步完成才结束
    DebugHelper::getSingleton().finalise();
    return ret;
}

We interpret code with the breadth-first approach.
setEvns();//设置了一些环境变量
startLeakDetection(componentType, g_componentID);//在machine中啥也没干。其他app中还不知道,这个暂不细究。
DebugHelper::initialize(componentType);//跟了一下,好深~~不过,就是初始化一下日志什么的,先不深究,啦啦啦啦~~好多不深究。恩,我们是为了把精力放到更重要的地方,毕竟学海无涯而吾生有涯~~~
KBEKey kbekey(Resmgr::getSingleton().matchPath("key/") + "kbengine_public.key", Resmgr::getSingleton().matchPath("key/") + "kbengine_private.key");//载入了一下公私key,还做了下对比,标示了下kbekey'是否有效
Network::EventDispatcher dispatcher;//一个事件处理器,这个玩意会对event的增加,减少,执行进行处理,当然,它本身没有实现执行,只是调用
DebugHelper::getSingleton().pDispatcher(&dispatcher);//设置了下处理器,并且启动的DebugHelper的timer
//巴拉巴拉 各种初始化,包裹network的参数,srcConfig的各种参数
const ChannelCommon& channelCommon = g_kbeSrvConfig.channelCommon();Network::g_SOMAXCONN = g_kbeSrvConfig.tcp_SOMAXCONN(g_componentType);Network::NetworkInterface networkInterface(&dispatcher, extlisteningPort_min, extlisteningPort_max, extlisteningInterface, channelCommon.extReadBufferSize, channelCommon.extWriteBufferSize,(intlisteningPort != -1) ? htons(intlisteningPort) : -1, intlisteningInterface,channelCommon.intReadBufferSize, channelCommon.intWriteBufferSize);DebugHelper::getSingleton().pNetworkInterface(&networkInterface);g_kbeSrvConfig.updateInfos(true, componentType, g_componentID, networkInterface.intaddr(), networkInterface.extaddr());
Components::getSingleton().initialize(&networkInterface, componentType, g_componentID);//初始化了一下app需要查找的app。当然了,Machine不需要任何app

Here is the focus


SERVER_APP app(dispatcher, networkInterface, componentType, g_componentID);
Components::getSingleton().findLogger();//查找logger,当然了 Machine 又不需要
if(!app.initialize())//初始化app各种东西,绝对的重要。。欲知详情,请听下回分解,还在本章哦~~~~
{
...//初始化失败了当然就是滚蛋了,有什么好说的
}
int ret = app.run();// app的主循环了,出来就已经gg了,
//后面的暂时不管了,反正已经gg了,不重要了哈哈哈

ServerApp::initialize()

bool ServerApp::initialize()
{
    if(!initThreadPool())return false;//初始化线程池
    if(!installSignals())return false;//注册信号
    if(!loadConfig())return false;//载入特有的配置,通用配置已经在开始前就载入了
    if(!initializeBegin())return false;//初始化前的准备
    if(!inInitialize())return false;//初始化
    bool ret = initializeEnd();//初始化后续处理
#ifdef ENABLE_WATCHERS
    return ret && initializeWatcher();
#else
    return ret;
#endif
}
In the Machine and no additional configuration to be loaded.

1.initializeBegin()

Machine initialized NetWork,
respectively epBroadcast_, ep_, epLocal_ three listeners do initialization. Listening ports are 20086,20087,20088 port, the actual use is still uncertain. Follow-up look.
epBroadcast_.socket (SOCK_DGRAM);
ep_.socket (SOCK_DGRAM);
epLocal_.socket (SOCK_DGRAM); 

2.inInitialize ()

What specific initialization action did not do in the Machine

3.initializeEnd()

Because it does not need to rely on other app so it did not do anything in the Machine

bool Machine::run()

Then there is the run () the
bool Machine::run()
{
    bool ret = true;
    while(!this->dispatcher().hasBreakProcessing())//这句话比较简单,就是检测下app是否该结束了
    {
        threadPool_.onMainThreadTick();//这个对finiTaskList_列表做了处理,把准备好,可以开始处理的放到worker中,处理玩的删除,还未准备好的放回原队
        this->dispatcher().processOnce(false);//处理了一下主线程中的事务
        networkInterface().processChannels(&MachineInterface::messageHandlers);//获取Network中的任务
        KBEngine::sleep(100);
    };
    return ret;
}

Up to now, Machine logic basically clear.
After various initialization, divided into the main thread and a worker thread in two parts processing services.
The main thread is a transaction processing network, apparently is not blocked, it may block some tasks will be to the worker thread.
After processed or sent back to network.

ServerApp define how the Message

Message Machine will deal with

This can be view in the machine_interface.h
// 其他组件向app广播自己的接口地址
MACHINE_MESSAGE_DECLARE_ARGS25(onBroadcastInterface,            NETWORK_VARIABLE_MESSAGE,
                                int32,                          uid, 
                                std::string,                    username,
                                COMPONENT_TYPE,                 componentType, 
                                COMPONENT_ID,                   componentID, 
                                COMPONENT_ID,                   componentIDEx, 
                                COMPONENT_ORDER,                globalorderid, 
                                COMPONENT_ORDER,                grouporderid, 
                                COMPONENT_GUS,                  gus,
                                uint32,                         intaddr, 
                                uint16,                         intport,
                                uint32,                         extaddr, 
                                uint16,                         extport,
                                std::string,                    extaddrEx,
                                uint32,                         pid,
                                float,                          cpu, 
                                float,                          mem, 
                                uint32,                         usedmem,
                                int8,                           state,
                                uint32,                         machineID, 
                                uint64,                         extradata,
                                uint64,                         extradata1,
                                uint64,                         extradata2,
                                uint64,                         extradata3,
                                uint32,                         backRecvAddr,
                                uint16,                         backRecvPort)
// 其他组件向app请求获取某个组件类别的地址    
MACHINE_MESSAGE_DECLARE_ARGS7(onFindInterfaceAddr, NETWORK_VARIABLE_MESSAGE,
                                int32, uid,
                                std::string, username,
                                COMPONENT_TYPE, componentType,
                                COMPONENT_ID, componentID,
                                COMPONENT_TYPE, findComponentType,
                                uint32, addr,
                                uint16, finderRecvPort)
// 查询所有接口信息
MACHINE_MESSAGE_DECLARE_ARGS3(onQueryAllInterfaceInfos,         NETWORK_VARIABLE_MESSAGE,
                                int32,                          uid, 
                                std::string,                    username,
                                uint16,                         finderRecvPort)
// 查询所有machine进程
MACHINE_MESSAGE_DECLARE_ARGS3(onQueryMachines,                  NETWORK_VARIABLE_MESSAGE,
                                int32,                          uid, 
                                std::string,                    username,
                                uint16,                         finderRecvPort)
// 某app主动请求look。
MACHINE_MESSAGE_DECLARE_ARGS0(lookApp,                          NETWORK_FIXED_MESSAGE)
// 某个app请求查看该app负载状态。
MACHINE_MESSAGE_DECLARE_ARGS0(queryLoad,                        NETWORK_FIXED_MESSAGE)
// 启动服务器
MACHINE_MESSAGE_DECLARE_STREAM(startserver,                     NETWORK_VARIABLE_MESSAGE)
// 关闭服务器
MACHINE_MESSAGE_DECLARE_STREAM(stopserver,                      NETWORK_VARIABLE_MESSAGE)
// 关闭服务器
MACHINE_MESSAGE_DECLARE_STREAM(killserver,                      NETWORK_VARIABLE_MESSAGE)
// 请求强制杀死当前app
MACHINE_MESSAGE_DECLARE_STREAM(reqKillServer,                   NETWORK_VARIABLE_MESSAGE)

Message Expand the definition of

Our
MACHINE_MESSAGE_DECLARE_ARGS7(onFindInterfaceAddr, NETWORK_VARIABLE_MESSAGE,
    int32, uid,
    std::string, username,
    COMPONENT_TYPE, componentType,
    COMPONENT_ID, componentID,
    COMPONENT_TYPE, findComponentType,
    uint32, addr,
    uint16, finderRecvPort)


Extended example, after the code is open
class onFindInterfaceAddrMachineMessagehandler7 : public Network::MessageHandler
{
public:
    void handle(Network::Channel* pChannel,
        KBEngine::MemoryStream& s)
     {
        int32 uid;                                                
        s >> uid;                                                        
        std::string username;                                                
        s >> username;                                                        
        COMPONENT_TYPE componentType;                                                
        s >> componentType;                                                        
        COMPONENT_ID componentID;                                               
        s >> componentID;                                                        
        COMPONENT_TYPE findComponentType;                                                
        s >> findComponentType;                                                        
        uint32 addr;                                               
        s >> addr;                                                        
        uint16 finderRecvPort;                                               
        s >> finderRecvPort;                                                        
        KBEngine::Machine::getSingleton().NAME(pChannel,                    
                                    uid, username, componentType,         
                                    componentID, findComponentType, addr,        
                                    finderRecvPort);                                
     }
};
extern const onFindInterfaceAddrMachineMessagehandler7& onFindInterfaceAddr;
class onFindInterfaceAddrArgs7 : public Network::MessageArgs                    
{                                                                
public:                                                            
    int32 uid;
    std::string username;
    COMPONENT_TYPE componentType;
    COMPONENT_ID componentID;
    COMPONENT_TYPE findComponentType;
    uint32 addr;
    uint16 finderRecvPort;
public:                                                            
    onFindInterfaceAddrArgs7():Network::MessageArgs()                        
    {                                                            
        strArgsTypes.push_back("int32");
        strArgsTypes.push_back("std::string");                        
        strArgsTypes.push_back("COMPONENT_TYPE");
        strArgsTypes.push_back("COMPONENT_ID");                        
        strArgsTypes.push_back("COMPONENT_TYPE");                        
        strArgsTypes.push_back("uint32");                        
        strArgsTypes.push_back("uint16");                        
    }                                                            
    onFindInterfaceAddrArgs7(
    int32 init_uid,
    std::string init_username,                                    
    COMPONENT_TYPE init_componentType,                                    
    COMPONENT_ID init_componentID,                                    
    COMPONENT_TYPE init_findComponentType,                                    
    uint32 init_addr,                                    
    uint16 init_finderRecvPort):                                
    Network::MessageArgs(),
        uid(init_uid),                                
        username(init_username),                                
        componentType(init_componentType),                                
        componentID(init_componentID),
        findComponentType(init_findComponentType),
        addr(init_addr),
        finderRecvPort(init_finderRecvPort)
    {                                                            
        strArgsTypes.push_back("int32");
        strArgsTypes.push_back("std::string");
        strArgsTypes.push_back("COMPONENT_TYPE");
        strArgsTypes.push_back("COMPONENT_ID");
        strArgsTypes.push_back("COMPONENT_TYPE");
        strArgsTypes.push_back("uint32");
        strArgsTypes.push_back("uint16");
    }                                                            
    ~onFindInterfaceAddrArgs7(){}                                            
                                                                
    static void staticAddToBundle(Network::Bundle& s,            
        int32 init_uid,
        std::string init_username,
        COMPONENT_TYPE init_componentType,
        COMPONENT_ID init_componentID,
        COMPONENT_TYPE init_findComponentType,
        uint32 init_addr,
        uint16 init_finderRecvPort)
    {                                                            
        s << init_uid;
        s << init_username;
        s << init_componentType;
        s << init_componentID;
        s << init_findComponentType;
        s << init_addr;
        s << init_finderRecvPort;
    }                                                            
    static void staticAddToStream(MemoryStream& s,                
        int32 init_uid,
        std::string init_username,
        COMPONENT_TYPE init_componentType,
        COMPONENT_ID init_componentID,
        COMPONENT_TYPE init_findComponentType,
        uint32 init_addr,
        uint16 init_finderRecvPort)
    {                                                            
        s << init_uid;
        s << init_username;
        s << init_componentType;
        s << init_componentID;
        s << init_findComponentType;
        s << init_addr;
        s << init_finderRecvPort;
    }                                                            
    virtual int32 dataSize(void)                                
    {                                                            
        return    sizeof(int32) +
                sizeof(std::string) +
                sizeof(COMPONENT_TYPE) +
                sizeof(COMPONENT_ID) +
                sizeof(COMPONENT_TYPE) +
                sizeof(uint32) +
                sizeof(uint16);
    }                                                            
    virtual void addToStream(MemoryStream& s)                    
    {                                                            
        s << uid;
        s << username;
        s << componentType;
        s << componentID;
        s << findComponentType;
        s << addr;
        s << finderRecvPort;
    }                                                            
    virtual void createFromStream(MemoryStream& s)                
    {                                                            
        s >> uid;
        s >> username;
        s >> componentType;
        s >> componentID;
        s >> findComponentType;
        s >> addr;
        s >> finderRecvPort;
    }                                                            
};


This is my hand-launched, so it is wrong to have what cp. . Look just fine. I do not know what tools can macro expansion ~ ~ ~ ~ (that may not pain free eggs one day, I would write a small tool, reported the possibility of a million millionth to look forward to it, ha ha ha)
still looked very regular. Machine is basically defines the next generation of Message or something. Machine then call the corresponding interface handle method.
It is worth mentioning that I use vs2015 follow-up time. To get into the handle is a virtual function is not achieved. . . Toss for a long time, and finally inquired at
MACHINE_MESSAGE_HANDLER_STREAM
all defined, and then found the results I want, then do a little test.
MACHINE_MESSAGE_HANDLER_STREAM really is the definition used in this deployment.
Looked at the whole structure should be the only app itself will produce a callback when the definition of belonging to their Message. Other times just plain news.
/ * Here mistake, this macro will be expanded twice, the first time defines the class of virtual functions, and the second defines the realization, if it is part of their own will be a callback, otherwise no processing * /

Published 54 original articles · won praise 1 · views 20000 +

Guess you like

Origin blog.csdn.net/u011255131/article/details/53470221