This commit is contained in:
aozhiwei 2019-03-26 10:59:19 +08:00
parent 43093bb6f4
commit 1d0192420a
13 changed files with 870 additions and 0 deletions

20
.gitignore vendored Normal file
View File

@ -0,0 +1,20 @@
webapp/php-common
*.*\~
*.*~
*.*\#
*.*#
\#*
\.\#*
~*.*
\#*.*
*.pb.*
CMakeCache.txt
cmake_install.cmake
CMakeFiles
Makefile
server/bin
__pycache__
*pb2.py
*.pyc
*.out
compile_commands.json

View File

@ -0,0 +1,75 @@
project(payserver)
cmake_minimum_required(VERSION 2.8)
if (${GAME_ID})
message(GAME_ID: ${GAME_ID})
else()
set(GAME_ID 1008)
message(GAME_ID: ${GAME_ID})
endif()
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_RELEASE "-std=gnu++11 -fsanitize=address -fno-omit-frame-pointer")
set(CMAKE_CXX_FLAGS_DEBUG "-Wall -g -std=gnu++11")
set(CMAKE_CXX_FLAGS_DEBUG "-Wall -g -std=gnu++11 -DGAME_ID=${GAME_ID}")
include_directories(
AFTER
../../third_party/a8engine
/usr/include/mysql
/usr/include/jsoncpp
/usr/include/hiredis
../../third_party
.
)
link_directories(
/usr/lib64/mysql
/usr/local/lib
)
aux_source_directory(../../third_party/a8engine/a8
SRC_LIST
)
aux_source_directory(../../third_party/framework/cpp
SRC_LIST
)
aux_source_directory(.
SRC_LIST
)
set(EXECUTABLE_OUTPUT_PATH
${PROJECT_BINARY_DIR}/../bin
)
set_directory_properties(PROPERTIES COMPILE_DEFINITIONS_DEBUG "_DEBUG")
add_executable(
payserver ${SRC_LIST}
)
# add_custom_target(script_pb_protocol ALL)
# add_custom_command(TARGET script_pb_protocol
# PRE_BUILD
# # COMMAND python ../../tools/script/construct/build_script.py
# COMMAND python ../tools/scripts/construct/build_pb.py
# # COMMAND python ../../tools/script/construct/build_protocol.py
# # COMMAND python ../../tools/script/construct/build_version_file.py
# )
# add_dependencies(payserver script_pb_protocol)
target_link_libraries(
payserver
pthread
mysqlclient
protobuf
rt
crypto
ssl
jsoncpp
curl
hiredis
tinyxml2
)

452
server/payserver/app.cc Normal file
View File

@ -0,0 +1,452 @@
#include "precompile.h"
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <mutex>
#include <condition_variable>
#include <a8/redis.h>
#include <a8/timer.h>
#include <a8/uuid.h>
#include "framework/cpp/netmsghandler.h"
#include "app.h"
#include "GCListener.h"
#include "jsondatamgr.h"
#include "handlermgr.h"
#include "target_conn.h"
#include "target_conn_mgr.h"
#include "gameclient.h"
#include "gameclientmgr.h"
#include "ss_msgid.pb.h"
#include "ss_proto.pb.h"
struct MsgNode
{
SocketFrom_e sockfrom;
int sockhandle;
unsigned short msgid;
unsigned int seqid;
long ip_saddr;
char* buf;
int buflen;
MsgNode* next;
};
struct IMMsgNode
{
unsigned short msgid;
a8::XParams params;
IMMsgNode* next = nullptr;
};
const char* const PROJ_LOG_ROOT_FMT = "/data/logs/%s/logs";
const char* const PROJ_LOG_FILENAME_FMT = "log_$pid_%Y%m%d.log";
static void SavePerfLog()
{
a8::UdpLog::Instance()->Info(" max_run_delay_time:%d max_timer_idle:%d "
"in_data_size:%d out_data_size:%d msgnode_size:%d read_count:%d",
{
App::Instance()->perf.max_run_delay_time,
App::Instance()->perf.max_timer_idle,
App::Instance()->perf.in_data_size,
App::Instance()->perf.out_data_size,
App::Instance()->msgnode_size_,
App::Instance()->perf.read_count,
});
#if 1
App::Instance()->perf.max_run_delay_time = 0;
App::Instance()->perf.max_timer_idle = 0;
#else
App::Instance()->perf = PerfMonitor();
#endif
}
void App::Init(int argc, char* argv[])
{
signal(SIGPIPE, SIG_IGN);
this->argc = argc;
this->argv = argv;
if (!ParseOpt()) {
terminated = true;
a8::XPrintf("masterserver启动失败,缺少-i参数\n", {});
return;
}
a8::XPrintf("masterserver starting instance_id:%d pid:%d\n", {instance_id, getpid()});
loop_mutex_ = new std::mutex();
loop_cond_ = new std::condition_variable();
msg_mutex_ = new std::mutex();
im_msg_mutex_ = new std::mutex();
srand(time(nullptr));
InitLog();
HandlerMgr::Instance()->Init();
a8::Timer::Instance()->Init();
JsonDataMgr::Instance()->Init();
GCListener::Instance()->Init();
uuid.SetMachineId(instance_id);
GameClientMgr::Instance()->Init();
TargetConnMgr::Instance()->Init();
a8::UdpLog::Instance()->Info("masterserver starting instance_id:%d pid:%d", {instance_id, getpid()});
{
int perf_log_time = 1000 * 60 * 5;
if (getenv("is_dev_env")) {
perf_log_time = 1000 * 10;
}
a8::Timer::Instance()->AddRepeatTimer(perf_log_time,
a8::XParams(),
[] (const a8::XParams& param)
{
SavePerfLog();
});
}
}
void App::UnInit()
{
if (terminated) {
return;
}
TargetConnMgr::Instance()->UnInit();
GameClientMgr::Instance()->UnInit();
GCListener::Instance()->UnInit();
JsonDataMgr::Instance()->UnInit();
a8::Timer::Instance()->UnInit();
HandlerMgr::Instance()->UnInit();
UnInitLog();
delete im_msg_mutex_;
im_msg_mutex_ = nullptr;
delete msg_mutex_;
msg_mutex_ = nullptr;
delete loop_cond_;
loop_cond_ = nullptr;
delete loop_mutex_;
loop_mutex_ = nullptr;
}
int App::Run()
{
if (terminated) {
return 0;
}
int ret = 0;
a8::UdpLog::Instance()->Info("masterserver running", {});
while (!terminated) {
a8::tick_t begin_tick = a8::XGetTickCount();
QuickExecute();
SlowerExecute();
a8::tick_t end_tick = a8::XGetTickCount();
if (end_tick - begin_tick > perf.max_run_delay_time) {
perf.max_run_delay_time = end_tick - begin_tick;
}
Schedule();
}
return ret;
}
void App::AddSocketMsg(SocketFrom_e sockfrom,
int sockhandle,
long ip_saddr,
unsigned short msgid,
unsigned int seqid,
const char *msgbody,
int bodylen)
{
MsgNode *p = (MsgNode*) malloc(sizeof(MsgNode));
memset(p, 0, sizeof(MsgNode));
p->sockfrom = sockfrom;
p->ip_saddr = ip_saddr;
p->sockhandle = sockhandle;
p->msgid = msgid;
p->seqid = seqid;
p->buf = nullptr;
p->buflen = bodylen;
if (bodylen > 0) {
p->buf = (char*)malloc(bodylen);
memmove(p->buf, msgbody, bodylen);
}
msg_mutex_->lock();
if (bot_node_) {
bot_node_->next = p;
bot_node_ = p;
} else {
top_node_ = p;
bot_node_ = p;
}
++msgnode_size_;
msg_mutex_->unlock();
NotifyLoopCond();
}
void App::AddIMMsg(unsigned short imcmd, a8::XParams params)
{
IMMsgNode *p = new IMMsgNode;
p->msgid = imcmd;
p->params = params;
p->next = nullptr;
im_msg_mutex_->lock();
if (im_bot_node_) {
im_bot_node_->next = p;
im_bot_node_ = p;
} else {
im_top_node_ = p;
im_bot_node_ = p;
}
im_msg_mutex_->unlock();
NotifyLoopCond();
}
void App::QuickExecute()
{
ProcessIMMsg();
DispatchMsg();
a8::Timer::Instance()->Update();
}
void App::SlowerExecute()
{
}
void App::NotifyLoopCond()
{
std::unique_lock<std::mutex> lk(*loop_mutex_);
loop_cond_->notify_all();
}
void App::Schedule()
{
std::unique_lock<std::mutex> lk(*loop_mutex_);
if (!HasTask()) {
int sleep_time = a8::Timer::Instance()->GetIdleableMillSeconds();
loop_cond_->wait_for(lk, std::chrono::milliseconds(sleep_time));
if (sleep_time > perf.max_timer_idle) {
perf.max_timer_idle = sleep_time;
}
}
}
bool App::HasTask()
{
{
if (!im_work_node_) {
im_msg_mutex_->lock();
if (!im_work_node_ && im_top_node_) {
im_work_node_ = im_top_node_;
im_top_node_ = nullptr;
im_bot_node_ = nullptr;
}
im_msg_mutex_->unlock();
}
if (im_work_node_) {
return true;
}
}
{
if (!work_node_) {
msg_mutex_->lock();
if (!work_node_ && top_node_) {
work_node_ = top_node_;
top_node_ = nullptr;
bot_node_ = nullptr;
}
msg_mutex_->unlock();
}
if (work_node_) {
return true;
}
}
return false;
}
void App::DispatchMsg()
{
long long starttick = a8::XGetTickCount();
if (!work_node_ && top_node_) {
msg_mutex_->lock();
work_node_ = top_node_;
top_node_ = nullptr;
bot_node_ = nullptr;
working_msgnode_size_ = msgnode_size_;
msg_mutex_->unlock();
}
f8::MsgHdr hdr;
while (work_node_) {
MsgNode *pdelnode = work_node_;
work_node_ = pdelnode->next;
hdr.msgid = pdelnode->msgid;
hdr.seqid = pdelnode->seqid;
hdr.socket_handle = pdelnode->sockhandle;
hdr.buf = pdelnode->buf;
hdr.buflen = pdelnode->buflen;
hdr.offset = 0;
hdr.ip_saddr = pdelnode->ip_saddr;
switch (pdelnode->sockfrom) {
case SF_Client:
{
ProcessClientMsg(hdr);
}
break;
case SF_TargetServer:
{
ProcessTargetServerMsg(hdr);
}
break;
}
if (pdelnode->buf) {
free(pdelnode->buf);
}
free(pdelnode);
working_msgnode_size_--;
if (a8::XGetTickCount() - starttick > 200) {
break;
}
}//end while
if (!work_node_) {
working_msgnode_size_ = 0;
}
}
void App::ProcessClientMsg(f8::MsgHdr& hdr)
{
if (hdr.msgid < 100) {
return;
}
TargetConn* conn = nullptr;
if (hdr.msgid == ss::_SS_CMLogin || hdr.msgid == ss::_SS_CMReConnect) {
ss::SS_CMLogin_CMReConnect_CommonHead msg;
bool ok = msg.ParseFromArray(hdr.buf + hdr.offset, hdr.buflen - hdr.offset);
if (ok) {
conn = TargetConnMgr::Instance()->GetConnByInstanceId(msg.server_id());
if (!conn) {
ss::SS_SMRpcError respmsg;
respmsg.set_error_code(10);
GCListener::Instance()->SendMsg(hdr.socket_handle, respmsg);
}
} else {
return;
}
} else {
GameClient* client = GameClientMgr::Instance()->GetGameClientBySocket(hdr.socket_handle);
if (client) {
conn = client->conn;
}
}
if (conn) {
conn->ForwardClientMsg(hdr);
}
}
void App::ProcessTargetServerMsg(f8::MsgHdr& hdr)
{
if (hdr.msgid < 100) {
return;
}
if (hdr.msgid == ss::_SS_CMLogin || hdr.msgid == ss::_SS_CMReConnect) {
GameClientMgr::Instance()->BindTargetConn(hdr.socket_handle, hdr.ip_saddr);
GCListener::Instance()->MarkClient(hdr.socket_handle, true);
}
GCListener::Instance()->ForwardTargetConnMsg(hdr);
}
void App::ProcessIMMsg()
{
if (!im_work_node_ && im_top_node_) {
im_msg_mutex_->lock();
im_work_node_ = im_top_node_;
im_top_node_ = nullptr;
im_bot_node_ = nullptr;
im_msg_mutex_->unlock();
}
while (im_work_node_) {
IMMsgNode *pdelnode = im_work_node_;
switch (im_work_node_->msgid) {
case IM_ClientSocketDisconnect:
{
GameClientMgr::Instance()->OnClientDisconnect(pdelnode->params);
}
break;
case IM_TargetConnDisconnect:
{
GameClientMgr::Instance()->OnTargetServerDisconnect(pdelnode->params);
}
break;
case IM_ExecGM:
{
HandlerMgr::Instance()->ProcGMMsg(pdelnode->params.param3,
pdelnode->params.sender,
pdelnode->params.param1.GetString(),
pdelnode->params.param2.GetString()
);
}
break;
}
im_work_node_ = im_work_node_->next;
delete pdelnode;
}
}
void App::InitLog()
{
std::string filename_fmt = PROJ_LOG_FILENAME_FMT;
a8::ReplaceString(filename_fmt, "$pid", a8::XValue(getpid()));
std::string proj_root_dir = a8::Format(PROJ_ROOT_FMT, {a8::Format(PROJ_NAME_FMT,{GAME_ID})});
std::string proj_log_root_dir = a8::Format(PROJ_LOG_ROOT_FMT, {a8::Format(PROJ_NAME_FMT, {GAME_ID})});
std::string log_file_name = a8::Format(PROJ_LOG_ROOT_FMT,
{a8::Format(PROJ_NAME_FMT, {GAME_ID})}) + "/" + filename_fmt;
a8::MkDir(proj_root_dir);
a8::MkDir(proj_log_root_dir);
a8::UdpLog::Instance()->SetLogFileName(log_file_name);
a8::UdpLog::Instance()->Init();
a8::UdpLog::Instance()->Info("proj_root_dir:%s", {proj_root_dir});
a8::UdpLog::Instance()->Info("proj_log_root_dir:%s", {proj_log_root_dir});
a8::UdpLog::Instance()->Info("log_file_name:%s", {log_file_name});
}
void App::UnInitLog()
{
a8::UdpLog::Instance()->UnInit();
}
bool App::ParseOpt()
{
int ch = 0;
while ((ch = getopt(argc, argv, "i:")) != -1) {
switch (ch) {
case 'i':
{
instance_id = a8::XValue(optarg);
}
break;
}
}
return instance_id > 0;
}
a8::XParams* App::AddContext(long long context_id)
{
context_hash_[context_id] = a8::XParams();
return GetContext(context_id);
}
void App::DelContext(long long context_id)
{
context_hash_.erase(context_id);
}
a8::XParams* App::GetContext(long long context_id)
{
auto itr = context_hash_.find(context_id);
return itr != context_hash_.end() ? &(itr->second) : nullptr;
}

82
server/payserver/app.h Normal file
View File

@ -0,0 +1,82 @@
#pragma once
#include <a8/uuid.h>
struct MsgNode;
struct IMMsgNode;
class App : public a8::Singleton<App>
{
private:
App() {};
friend class a8::Singleton<App>;
public:
void Init(int argc, char* argv[]);
void UnInit();
int Run();
void AddSocketMsg(SocketFrom_e sockfrom,
int sockhandle,
long ip_saddr,
unsigned short msgid,
unsigned int seqid,
const char *msgbody,
int bodylen);
void AddIMMsg(unsigned short imcmd, a8::XParams params);
void NotifyLoopCond();
a8::XParams* AddContext(long long context_id);
void DelContext(long long context_id);
a8::XParams* GetContext(long long context_id);
private:
void QuickExecute();
void SlowerExecute();
void Schedule();
bool HasTask();
void DispatchMsg();
void ProcessIMMsg();
void ProcessClientMsg(f8::MsgHdr& hdr);
void ProcessTargetServerMsg(f8::MsgHdr& hdr);
void InitLog();
void UnInitLog();
bool ParseOpt();
public:
int argc = 0;
char** argv = nullptr;
volatile bool terminated = false;
PerfMonitor perf;
a8::uuid::SnowFlake uuid;
public:
int instance_id = 0;
private:
std::mutex *loop_mutex_ = nullptr;
std::condition_variable *loop_cond_ = nullptr;
std::mutex *msg_mutex_ = nullptr;
MsgNode* top_node_ = nullptr;
MsgNode* bot_node_ = nullptr;
MsgNode* work_node_ = nullptr;
std::mutex* im_msg_mutex_ = nullptr;
IMMsgNode* im_top_node_ = nullptr;
IMMsgNode* im_bot_node_ = nullptr;
IMMsgNode* im_work_node_ = nullptr;
std::map<long long, a8::XParams> context_hash_;
public:
int msgnode_size_ = 0 ;
int working_msgnode_size_ = 0;
};

View File

@ -0,0 +1,37 @@
#pragma once
enum SocketFrom_e
{
SF_Client,
SF_TargetServer,
};
enum InnerMesssage_e
{
IM_ClientSocketDisconnect = 100,
IM_PlayerOffline,
IM_ExecGM,
IM_TargetConnDisconnect
};
//网络处理对象
enum NetHandler_e
{
HID_Player,
HID_PlayerMgr,
HID_RoomSvrMgr,
HID_GCListener,
};
enum PlayerState_e
{
PS_None,
PS_InRoom,
PS_Matching,
PS_WaitingMatch
};
const char* const PROJ_NAME_FMT = "game%d_wsproxy";
const char* const PROJ_ROOT_FMT = "/data/logs/%s";
const int POSTFIX_LEN = 7;

View File

@ -0,0 +1,68 @@
#include "precompile.h"
#include <a8/mutable_xobject.h>
#include "handlermgr.h"
#include "GCListener.h"
static void _GMOpsSelfChecking(f8::JsonHttpRequest* request)
{
request->resp_xobj->SetVal("errcode", 0);
request->resp_xobj->SetVal("errmsg", "");
request->resp_xobj->SetVal("healthy", 1);
request->resp_xobj->SetVal("max_rundelay", 10);
}
void HandlerMgr::Init()
{
RegisterNetMsgHandlers();
RegisterGMMsgHandler("Ops$selfChecking", _GMOpsSelfChecking);
}
void HandlerMgr::UnInit()
{
}
void HandlerMgr::RegisterNetMsgHandlers()
{
}
void HandlerMgr::ProcGMMsg(unsigned long saddr, int sockhandle,
const std::string& url, const std::string& querystr)
{
if (url != "/webapp/index.php") {
GCListener::Instance()->SendText(sockhandle, a8::HttpResponse(404, ""));
return;
}
a8::HTTPRequest request;
a8::ParserUrlQueryString(querystr.c_str(), request);
std::string msgname = a8::Get(request, "c").GetString() + "$" + a8::Get(request, "a").GetString();
auto itr = gmhandlers_.find(msgname);
if (itr != gmhandlers_.end()) {
f8::JsonHttpRequest* request = new f8::JsonHttpRequest;
request->saddr = saddr;
request->socket_handle = sockhandle;
request->query_str = querystr;
request->request.ReadFromUrlQueryString(querystr);
itr->second(request);
if (!request->pending){
std::string response;
request->resp_xobj->ToJsonStr(response);
GCListener::Instance()->SendText(sockhandle, a8::HttpResponse(response));
delete request;
}
} else {
GCListener::Instance()->SendText(sockhandle, a8::HttpResponse("{}"));
}
}
void HandlerMgr::RegisterGMMsgHandler(const std::string& msgname,
void (*handler)(f8::JsonHttpRequest*))
{
gmhandlers_[msgname] = handler;
}

View File

@ -0,0 +1,37 @@
#pragma once
#include <a8/basehttpsession.h>
#include "framework/cpp/netmsghandler.h"
namespace a8
{
class MutableXObject;
}
class HandlerMgr : public a8::Singleton<HandlerMgr>
{
private:
HandlerMgr() {};
friend class a8::Singleton<HandlerMgr>;
public:
void Init();
void UnInit();
f8::NetMsgHandlerObject gcmsghandler;
f8::NetMsgHandlerObject rsmsghandler;
f8::NetMsgHandlerObject gsmsghandler;
void ProcGMMsg(unsigned long saddr, int sockhandle,
const std::string& url, const std::string& querystr);
private:
void RegisterNetMsgHandlers();
void RegisterGMMsgHandler(const std::string& msgname,
void (*)(f8::JsonHttpRequest*));
std::map<std::string, void (*)(f8::JsonHttpRequest*)> gmhandlers_;
};

View File

@ -0,0 +1,38 @@
#include "precompile.h"
#include "jsondatamgr.h"
#include "app.h"
void JsonDataMgr::Init()
{
std::string wsproxyserver_cluster_json_file;
std::string targetserver_cluster_json_file;
if (f8::IsOnlineEnv()) {
wsproxyserver_cluster_json_file = a8::Format("../config/game%d.wsproxy.cluster.json", {GAME_ID});
targetserver_cluster_json_file = a8::Format("../config/game%d.gameserver.cluster.json", {GAME_ID});
} else {
wsproxyserver_cluster_json_file = a8::Format("/var/data/conf_test/game%d/wsproxy/game%d.wsproxy.cluster.json",
{GAME_ID, GAME_ID});
targetserver_cluster_json_file = a8::Format("/var/data/conf_test/game%d/wsproxy/game%d.gameserver.cluster.json",
{GAME_ID, GAME_ID});
}
wsproxyserver_cluster_json_.ReadFromFile(wsproxyserver_cluster_json_file);
targetserver_cluster_json_.ReadFromFile(targetserver_cluster_json_file);
}
void JsonDataMgr::UnInit()
{
}
std::shared_ptr<a8::XObject> JsonDataMgr::GetConf()
{
if (App::Instance()->instance_id < 1 || App::Instance()->instance_id > wsproxyserver_cluster_json_.Size()) {
abort();
}
return wsproxyserver_cluster_json_[App::Instance()->instance_id - 1];
}
std::shared_ptr<a8::XObject> JsonDataMgr::GetTargetServerClusterConf()
{
return std::make_shared<a8::XObject>(targetserver_cluster_json_);
}

View File

@ -0,0 +1,20 @@
#pragma once
class JsonDataMgr : public a8::Singleton<JsonDataMgr>
{
private:
JsonDataMgr() {};
friend class a8::Singleton<JsonDataMgr>;
public:
void Init();
void UnInit();
std::shared_ptr<a8::XObject> GetConf();
std::shared_ptr<a8::XObject> GetTargetServerClusterConf();
private:
a8::XObject wsproxyserver_cluster_json_;
a8::XObject targetserver_cluster_json_;
};

11
server/payserver/main.cc Normal file
View File

@ -0,0 +1,11 @@
#include "precompile.h"
#include "app.h"
int main(int argc, char* argv[])
{
int exitcode = 0;
App::Instance()->Init(argc, argv);
exitcode = App::Instance()->Run();
App::Instance()->UnInit();
return exitcode;
}

View File

@ -0,0 +1,20 @@
#pragma once
#include <a8/a8.h>
#include <a8/udplog.h>
#include "constant.h"
#include "types.h"
namespace google
{
namespace protobuf
{
class Message;
}
}
#include "framework/cpp/types.h"
#include "framework/cpp/utils.h"
#include "framework/cpp/protoutils.h"

View File

10
server/payserver/types.h Normal file
View File

@ -0,0 +1,10 @@
#pragma once
struct PerfMonitor
{
int max_run_delay_time = 0;
int max_timer_idle = 0;
long long out_data_size = 0;
long long in_data_size = 0;
long long read_count = 0;
};