Repository navigation
Expand file tree
/
Copy pathserverapp.cpp
More file actions
584 lines (487 loc) · 18.5 KB
/
Copy pathserverapp.cpp
File metadata and controls
584 lines (487 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2016 KBEngine.
KBEngine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KBEngine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "serverapp.h"
#include "server/component_active_report_handler.h"
#include "server/shutdowner.h"
#include "server/serverconfig.h"
#include "server/components.h"
#include "network/channel.h"
#include "network/bundle.h"
#include "network/common.h"
#include "common/memorystream.h"
#include "helper/console_helper.h"
#include "helper/sys_info.h"
#include "helper/watch_pools.h"
#include "resmgr/resmgr.h"
#include "../../server/baseappmgr/baseappmgr_interface.h"
#include "../../server/cellappmgr/cellappmgr_interface.h"
#include "../../server/baseapp/baseapp_interface.h"
#include "../../server/cellapp/cellapp_interface.h"
#include "../../server/dbmgr/dbmgr_interface.h"
#include "../../server/loginapp/loginapp_interface.h"
#include "../../server/tools/logger/logger_interface.h"
#include "../../server/tools/interfaces/interfaces_interface.h"
namespace KBEngine{
COMPONENT_TYPE g_componentType = UNKNOWN_COMPONENT_TYPE;
COMPONENT_ID g_componentID = 0;
COMPONENT_ORDER g_componentGlobalOrder = -1;
COMPONENT_ORDER g_componentGroupOrder = -1;
int32 g_genuuid_sections = -1;
GAME_TIME g_kbetime = 0;
//-------------------------------------------------------------------------------------
ServerApp::ServerApp(Network::EventDispatcher& dispatcher,
Network::NetworkInterface& ninterface,
COMPONENT_TYPE componentType,
COMPONENT_ID componentID):
SignalHandler(),
TimerHandler(),
ShutdownHandler(),
Network::ChannelTimeOutHandler(),
Components::ComponentsNotificationHandler(),
componentType_(componentType),
componentID_(componentID),
dispatcher_(dispatcher),
networkInterface_(ninterface),
timers_(),
startGlobalOrder_(-1),
startGroupOrder_(-1),
pShutdowner_(NULL),
pActiveTimerHandle_(NULL),
threadPool_()
{
networkInterface_.pExtensionData(this);
networkInterface_.pChannelTimeOutHandler(this);
networkInterface_.pChannelDeregisterHandler(this);
// 广播自己的地址给网上上的所有kbemachine
// 并且从kbemachine获取basappmgr和cellappmgr以及dbmgr地址
Components::getSingleton().pHandler(this);
this->dispatcher().addTask(&Components::getSingleton());
pActiveTimerHandle_ = new ComponentActiveReportHandler(this);
pActiveTimerHandle_->startActiveTick(KBE_MAX(1.f, Network::g_channelInternalTimeout / 2.0f));
// 默认所有app都设置为这个值, 如果需要调整则各自在派生类重新赋值
ProfileVal::setWarningPeriod(stampsPerSecond() / g_kbeSrvConfig.gameUpdateHertz());
}
//-------------------------------------------------------------------------------------
ServerApp::~ServerApp()
{
SAFE_RELEASE(pActiveTimerHandle_);
SAFE_RELEASE(pShutdowner_);
}
//-------------------------------------------------------------------------------------
void ServerApp::shutDown(float shutdowntime)
{
if(pShutdowner_ == NULL)
pShutdowner_ = new Shutdowner(this);
pShutdowner_->shutdown(shutdowntime < 0.f ? g_kbeSrvConfig.shutdowntime() : shutdowntime,
g_kbeSrvConfig.shutdownWaitTickTime(), dispatcher_);
}
//-------------------------------------------------------------------------------------
void ServerApp::onShutdownBegin()
{
#if KBE_PLATFORM == PLATFORM_WIN32
printf("[INFO]: shutdown begin.\n");
#endif
dispatcher_.setWaitBreakProcessing();
}
//-------------------------------------------------------------------------------------
void ServerApp::onShutdown(bool first)
{
}
//-------------------------------------------------------------------------------------
void ServerApp::onShutdownEnd()
{
dispatcher_.breakProcessing();
}
//-------------------------------------------------------------------------------------
bool ServerApp::loadConfig()
{
return true;
}
//-------------------------------------------------------------------------------------
bool ServerApp::installSignals()
{
g_kbeSignalHandlers.attachApp(this);
g_kbeSignalHandlers.addSignal(SIGINT, this);
g_kbeSignalHandlers.addSignal(SIGPIPE, this);
g_kbeSignalHandlers.addSignal(SIGHUP, this);
return true;
}
//-------------------------------------------------------------------------------------
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
}
//-------------------------------------------------------------------------------------
bool ServerApp::initializeWatcher()
{
WATCH_OBJECT("stats/stampsPerSecond", &KBEngine::stampsPerSecond);
WATCH_OBJECT("uid", &KBEngine::getUserUID);
WATCH_OBJECT("username", &KBEngine::getUsername);
WATCH_OBJECT("componentType", componentType_);
WATCH_OBJECT("componentID", componentID_);
WATCH_OBJECT("globalOrder", this, &ServerApp::globalOrder);
WATCH_OBJECT("groupOrder", this, &ServerApp::groupOrder);
WATCH_OBJECT("gametime", this, &ServerApp::time);
return Network::initializeWatcher() && Resmgr::getSingleton().initializeWatcher() &&
threadPool_.initializeWatcher() && WatchPool::initWatchPools();
}
//-------------------------------------------------------------------------------------
void ServerApp::queryWatcher(Network::Channel* pChannel, MemoryStream& s)
{
AUTO_SCOPED_PROFILE("watchers");
std::string path;
s >> path;
MemoryStream::SmartPoolObjectPtr readStreamPtr = MemoryStream::createSmartPoolObj();
WatcherPaths::root().readWatchers(path, readStreamPtr.get()->get());
MemoryStream::SmartPoolObjectPtr readStreamPtr1 = MemoryStream::createSmartPoolObj();
WatcherPaths::root().readChildPaths(path, path, readStreamPtr1.get()->get());
Network::Bundle* pBundle = Network::Bundle::createPoolObject();
ConsoleInterface::ConsoleWatcherCBMessageHandler msgHandler;
(*pBundle).newMessage(msgHandler);
uint8 type = 0;
(*pBundle) << type;
(*pBundle).append(readStreamPtr.get()->get());
pChannel->send(pBundle);
Network::Bundle* pBundle1 = Network::Bundle::createPoolObject();
(*pBundle1).newMessage(msgHandler);
type = 1;
(*pBundle1) << type;
(*pBundle1).append(readStreamPtr1.get()->get());
pChannel->send(pBundle1);
}
//-------------------------------------------------------------------------------------
bool ServerApp::initThreadPool()
{
if(!threadPool_.isInitialize())
{
thread::ThreadPool::timeout = int(g_kbeSrvConfig.thread_timeout_);
threadPool_.createThreadPool(g_kbeSrvConfig.thread_init_create_,
g_kbeSrvConfig.thread_pre_create_, g_kbeSrvConfig.thread_max_create_);
return true;
}
return false;
}
//-------------------------------------------------------------------------------------
void ServerApp::finalise(void)
{
ProfileGroup::finalise();
threadPool_.finalise();
Network::finalise();
}
//-------------------------------------------------------------------------------------
double ServerApp::gameTimeInSeconds() const
{
return double(g_kbetime) / g_kbeSrvConfig.gameUpdateHertz();
}
//-------------------------------------------------------------------------------------
void ServerApp::handleTimeout(TimerHandle, void * arg)
{
}
//-------------------------------------------------------------------------------------
void ServerApp::handleTimers()
{
AUTO_SCOPED_PROFILE("callTimers");
timers().process(g_kbetime);
}
//-------------------------------------------------------------------------------------
bool ServerApp::run(void)
{
dispatcher_.processUntilBreak();
return true;
}
//-------------------------------------------------------------------------------------
void ServerApp::onSignalled(int sigNum)
{
switch (sigNum)
{
case SIGINT:
case SIGHUP:
this->shutDown(1.f);
default:
break;
}
}
//-------------------------------------------------------------------------------------
void ServerApp::onChannelDeregister(Network::Channel * pChannel)
{
if(pChannel->isInternal())
{
Components::getSingleton().onChannelDeregister(pChannel, this->isShuttingdown());
}
}
//-------------------------------------------------------------------------------------
void ServerApp::onChannelTimeOut(Network::Channel * pChannel)
{
INFO_MSG(fmt::format("ServerApp::onChannelTimeOut: "
"Channel {0} timed out.\n", pChannel->c_str()));
networkInterface_.deregisterChannel(pChannel);
pChannel->destroy();
Network::Channel::reclaimPoolObject(pChannel);
}
//-------------------------------------------------------------------------------------
void ServerApp::onAddComponent(const Components::ComponentInfos* pInfos)
{
if(pInfos->componentType == LOGGER_TYPE)
{
DebugHelper::getSingleton().registerLogger(LoggerInterface::writeLog.msgID, pInfos->pIntAddr.get());
}
}
//-------------------------------------------------------------------------------------
void ServerApp::onIdentityillegal(COMPONENT_TYPE componentType, COMPONENT_ID componentID, uint32 pid, const char* pAddr)
{
ERROR_MSG(fmt::format("ServerApp::onIdentityillegal: The current process and {}(componentID={} ->conflicted???, pid={}, addr={}) conflict, the process will exit!\n"
"Can modify the components-CID and UID to avoid conflict.\n",
COMPONENT_NAME_EX((COMPONENT_TYPE)componentType), componentID, pid, pAddr));
this->shutDown(1.f);
}
//-------------------------------------------------------------------------------------
void ServerApp::onRemoveComponent(const Components::ComponentInfos* pInfos)
{
if(pInfos->componentType == LOGGER_TYPE)
{
DebugHelper::getSingleton().unregisterLogger(LoggerInterface::writeLog.msgID, pInfos->pIntAddr.get());
}
else if(pInfos->componentType == DBMGR_TYPE)
{
if(g_componentType != MACHINE_TYPE &&
g_componentType != LOGGER_TYPE &&
g_componentType != INTERFACES_TYPE &&
g_componentType != BOTS_TYPE &&
g_componentType != WATCHER_TYPE)
this->shutDown(0.f);
}
else if (pInfos->componentType == CELLAPPMGR_TYPE)
{
if (g_componentType == CELLAPP_TYPE)
this->shutDown(0.f);
}
else if (pInfos->componentType == BASEAPPMGR_TYPE)
{
if (g_componentType == BASEAPP_TYPE)
this->shutDown(0.f);
}
}
//-------------------------------------------------------------------------------------
void ServerApp::onRegisterNewApp(Network::Channel* pChannel, int32 uid, std::string& username,
COMPONENT_TYPE componentType, COMPONENT_ID componentID, COMPONENT_ORDER globalorderID, COMPONENT_ORDER grouporderID,
uint32 intaddr, uint16 intport, uint32 extaddr, uint16 extport, std::string& extaddrEx)
{
if(pChannel->isExternal())
return;
INFO_MSG(fmt::format("ServerApp::onRegisterNewApp: uid:{0}, username:{1}, componentType:{2}, "
"componentID:{3}, globalorderID={9}, grouporderID={10}, intaddr:{4}, intport:{5}, extaddr:{6}, extport:{7}, from {8}.\n",
uid,
username.c_str(),
COMPONENT_NAME_EX((COMPONENT_TYPE)componentType),
componentID,
inet_ntoa((struct in_addr&)intaddr),
ntohs(intport),
(extaddr != 0 ? inet_ntoa((struct in_addr&)extaddr) : "nonsupport"),
ntohs(extport),
pChannel->c_str(),
((int32)globalorderID),
((int32)grouporderID)));
Components::ComponentInfos* cinfos = Components::getSingleton().findComponent((
KBEngine::COMPONENT_TYPE)componentType, uid, componentID);
pChannel->componentID(componentID);
if(cinfos == NULL)
{
Components::getSingleton().addComponent(uid, username.c_str(),
(KBEngine::COMPONENT_TYPE)componentType, componentID, globalorderID, grouporderID, intaddr, intport, extaddr, extport, extaddrEx, 0,
0.f, 0.f, 0, 0, 0, 0, 0, pChannel);
}
else
{
KBE_ASSERT(cinfos->pIntAddr->ip == intaddr && cinfos->pIntAddr->port == intport);
cinfos->pChannel = pChannel;
}
}
//-------------------------------------------------------------------------------------
void ServerApp::reqKillServer(Network::Channel* pChannel, MemoryStream& s)
{
if(pChannel->isExternal())
return;
COMPONENT_ID componentID;
COMPONENT_TYPE componentType;
std::string username;
int32 uid;
std::string reason;
s >> componentID >> componentType >> username >> uid >> reason;
INFO_MSG(fmt::format("ServerApp::reqKillServer: requester(uid:{}, username:{}, componentType:{}, "
"componentID:{}, reason:{}, from {})\n",
uid,
username,
COMPONENT_NAME_EX((COMPONENT_TYPE)componentType),
componentID,
reason,
pChannel->c_str()));
CRITICAL_MSG("The application was killed!\n");
}
//-------------------------------------------------------------------------------------
void ServerApp::onAppActiveTick(Network::Channel* pChannel, COMPONENT_TYPE componentType, COMPONENT_ID componentID)
{
if(componentType != CLIENT_TYPE)
if(pChannel->isExternal())
return;
Network::Channel* pTargetChannel = NULL;
if(componentType != CONSOLE_TYPE && componentType != CLIENT_TYPE)
{
Components::ComponentInfos* cinfos =
Components::getSingleton().findComponent(componentType, KBEngine::getUserUID(), componentID);
if(cinfos == NULL || cinfos->pChannel == NULL)
{
ERROR_MSG(fmt::format("ServerApp::onAppActiveTick[{:p}]: {}:{} not found.\n",
(void*)pChannel, COMPONENT_NAME_EX(componentType), componentID));
return;
}
pTargetChannel = cinfos->pChannel;
pTargetChannel->updateLastReceivedTime();
}
else
{
pChannel->updateLastReceivedTime();
pTargetChannel = pChannel;
}
//DEBUG_MSG("ServerApp::onAppActiveTick[%x]: %s:%"PRAppID" lastReceivedTime:%"PRIu64" at %s.\n",
// pChannel, COMPONENT_NAME_EX(componentType), componentID, pChannel->lastReceivedTime(), pTargetChannel->c_str());
}
//-------------------------------------------------------------------------------------
void ServerApp::reqClose(Network::Channel* pChannel)
{
DEBUG_MSG(fmt::format("ServerApp::reqClose: {}\n", pChannel->c_str()));
// this->networkInterface().deregisterChannel(pChannel);
// pChannel->destroy();
}
//-------------------------------------------------------------------------------------
void ServerApp::lookApp(Network::Channel* pChannel)
{
if(pChannel->isExternal())
return;
DEBUG_MSG(fmt::format("ServerApp::lookApp: {}\n", pChannel->c_str()));
Network::Bundle* pBundle = Network::Bundle::createPoolObject();
(*pBundle) << g_componentType;
(*pBundle) << componentID_;
ShutdownHandler::SHUTDOWN_STATE state = shuttingdown();
int8 istate = int8(state);
(*pBundle) << istate;
pChannel->send(pBundle);
}
//-------------------------------------------------------------------------------------
void ServerApp::reqCloseServer(Network::Channel* pChannel, MemoryStream& s)
{
DEBUG_MSG(fmt::format("ServerApp::reqCloseServer: {}\n", pChannel->c_str()));
Network::Bundle* pBundle = Network::Bundle::createPoolObject();
bool success = true;
(*pBundle) << success;
pChannel->send(pBundle);
this->shutDown();
}
//-------------------------------------------------------------------------------------
void ServerApp::queryLoad(Network::Channel* pChannel)
{
}
//-------------------------------------------------------------------------------------
void ServerApp::hello(Network::Channel* pChannel, MemoryStream& s)
{
std::string verInfo, scriptVerInfo, encryptedKey;
s >> verInfo >> scriptVerInfo;
s.readBlob(encryptedKey);
char buf[MAX_BUF];
std::string encryptedKey_str;
if (encryptedKey.size() > 3 && encryptedKey.size() <= 65535)
{
for (int i = 0; i < (int)encryptedKey.size(); ++i)
{
memset(buf, 0, MAX_BUF);
kbe_snprintf(buf, MAX_BUF / 2, "%02hhX ", (unsigned char)encryptedKey.data()[i]);
encryptedKey_str += buf;
}
}
else
{
encryptedKey = "";
encryptedKey_str = "None";
}
INFO_MSG(fmt::format("ServerApp::onHello: verInfo={}, scriptVerInfo={}, encryptedKey={}, addr:{}\n",
verInfo, scriptVerInfo, encryptedKey_str, pChannel->c_str()));
if(verInfo != KBEVersion::versionString())
onVersionNotMatch(pChannel);
else if(scriptVerInfo != KBEVersion::scriptVersionString())
onScriptVersionNotMatch(pChannel);
else
onHello(pChannel, verInfo, scriptVerInfo, encryptedKey);
}
//-------------------------------------------------------------------------------------
void ServerApp::onHello(Network::Channel* pChannel,
const std::string& verInfo,
const std::string& scriptVerInfo,
const std::string& encryptedKey)
{
}
//-------------------------------------------------------------------------------------
void ServerApp::onVersionNotMatch(Network::Channel* pChannel)
{
}
//-------------------------------------------------------------------------------------
void ServerApp::onScriptVersionNotMatch(Network::Channel* pChannel)
{
}
//-------------------------------------------------------------------------------------
void ServerApp::startProfile(Network::Channel* pChannel, KBEngine::MemoryStream& s)
{
std::string profileName;
int8 profileType;
uint32 timelen;
s >> profileName >> profileType >> timelen;
startProfile_(pChannel, profileName, profileType, timelen);
}
//-------------------------------------------------------------------------------------
void ServerApp::startProfile_(Network::Channel* pChannel, std::string profileName, int8 profileType, uint32 timelen)
{
switch(profileType)
{
case 1: // cprofile
new CProfileHandler(this->networkInterface(), timelen, profileName, pChannel->addr());
break;
case 2: // eventprofile
new EventProfileHandler(this->networkInterface(), timelen, profileName, pChannel->addr());
break;
case 3: // networkprofile
new NetworkProfileHandler(this->networkInterface(), timelen, profileName, pChannel->addr());
break;
default:
ERROR_MSG(fmt::format("ServerApp::startProfile_: type({}:{}) not support!\n",
profileType, profileName));
break;
};
}
//-------------------------------------------------------------------------------------
}