TrinityCore
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
Trinity Daemon

Macros

#define _TRINITY_CORE_CONFIG   "worldserver.conf"
 
#define WORLD_SLEEP_CONST   50
 

Functions

void utf8print (void *, const char *str)
 
void commandFinished (void *, bool)
 
void CliThread ()
 Thread start More...
 
boost::asio::deadline_timer _freezeCheckTimer (_ioService)
 
uint32 _worldLoopCounter (0)
 
uint32 _lastChangeMsTime (0)
 
uint32 _maxCoreStuckTimeInMs (0)
 
void SignalHandler (const boost::system::error_code &error, int signalNumber)
 
void FreezeDetectorHandler (const boost::system::error_code &error)
 
AsyncAcceptorStartRaSocketAcceptor (boost::asio::io_service &ioService)
 
bool StartDB ()
 Initialize connection to the databases. More...
 
void StopDB ()
 
void WorldUpdateLoop ()
 
void ClearOnlineAccounts ()
 Clear 'online' status for all accounts with characters in this realm. More...
 
void ShutdownCLIThread (std::thread *cliThread)
 
void ShutdownThreadPool (std::vector< std::thread > &threadPool)
 
bool LoadRealmInfo ()
 
variables_map GetConsoleArguments (int argc, char **argv, std::string &cfg_file, std::string &cfg_service)
 
int main (int argc, char **argv)
 Launch the Trinity server. More...
 

Variables

boost::asio::io_service _ioService
 

Detailed Description

Macro Definition Documentation

#define _TRINITY_CORE_CONFIG   "worldserver.conf"
#define WORLD_SLEEP_CONST   50

Function Documentation

boost::asio::deadline_timer _freezeCheckTimer ( _ioService  )

+ Here is the caller graph for this function:

uint32 _lastChangeMsTime ( )

+ Here is the caller graph for this function:

uint32 _maxCoreStuckTimeInMs ( )

+ Here is the caller graph for this function:

uint32 _worldLoopCounter ( )

+ Here is the caller graph for this function:

void ClearOnlineAccounts ( )

Clear 'online' status for all accounts with characters in this realm.

569 {
570  // Reset online status for all accounts with characters on the current realm
571  LoginDatabase.DirectPExecute("UPDATE account SET online = 0 WHERE online > 0 AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = %d)", realm.Id.Realm);
572 
573  // Reset online status for all characters
574  CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0");
575 
576  // Battleground instance ids reset at server restart
577  CharacterDatabase.DirectExecute("UPDATE character_battleground_data SET instanceId = 0");
578 }
uint32 Realm
Definition: Realm.h:53
Realm realm
Definition: World.cpp:3485
LoginDatabaseWorkerPool LoginDatabase
Accessor to the realm/login database.
Definition: DatabaseEnv.cpp:22
void DirectPExecute(Format &&sql, Args &&...args)
Definition: DatabaseWorkerPool.h:134
Battlenet::RealmHandle Id
Definition: Realm.h:86
CharacterDatabaseWorkerPool CharacterDatabase
Accessor to the character database.
Definition: DatabaseEnv.cpp:21
void DirectExecute(const char *sql)
Definition: DatabaseWorkerPool.h:121

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void CliThread ( )

Thread start

  • Display the list of available CLI functions then beep
  • As long as the World is running (no World::m_stopEvent), get the command line and handle it
134 {
136  //TC_LOG_INFO("server.worldserver", "");
137 #if PLATFORM != PLATFORM_WINDOWS
138  rl_attempted_completion_function = cli_completion;
139  rl_event_hook = cli_hook_func;
140 #endif
141 
142  if (sConfigMgr->GetBoolDefault("BeepAtStart", true))
143  printf("\a"); // \a = Alert
144 
145  // print this here the first time
146  // later it will be printed after command queue updates
147  printf("TC>");
148 
150  while (!World::IsStopped())
151  {
152  fflush(stdout);
153 
154  char *command_str ; // = fgets(commandbuf, sizeof(commandbuf), stdin);
155 
156 #if PLATFORM == PLATFORM_WINDOWS
157  char commandbuf[256];
158  command_str = fgets(commandbuf, sizeof(commandbuf), stdin);
159 #else
160  command_str = readline("TC>");
161  rl_bind_key('\t', rl_complete);
162 #endif
163 
164  if (command_str != NULL)
165  {
166  for (int x=0; command_str[x]; ++x)
167  if (command_str[x] == '\r' || command_str[x] == '\n')
168  {
169  command_str[x] = 0;
170  break;
171  }
172 
173  if (!*command_str)
174  {
175 #if PLATFORM == PLATFORM_WINDOWS
176  printf("TC>");
177 #else
178  free(command_str);
179 #endif
180  continue;
181  }
182 
183  std::string command;
184  if (!consoleToUtf8(command_str, command)) // convert from console encoding to utf8
185  {
186 #if PLATFORM == PLATFORM_WINDOWS
187  printf("TC>");
188 #else
189  free(command_str);
190 #endif
191  continue;
192  }
193 
194  fflush(stdout);
195  sWorld->QueueCliCommand(new CliCommandHolder(NULL, command.c_str(), &utf8print, &commandFinished));
196 #if PLATFORM != PLATFORM_WINDOWS
197  add_history(command.c_str());
198  free(command_str);
199 #endif
200  }
201  else if (feof(stdin))
202  {
204  }
205  }
206 }
void utf8print(void *, const char *str)
Definition: CliRunnable.cpp:92
#define sConfigMgr
Definition: Config.h:61
bool consoleToUtf8(const std::string &conStr, std::string &utf8str)
Definition: Util.cpp:438
arena_t NULL
Definition: jemalloc_internal.h:624
static bool IsStopped()
Definition: World.h:663
#define sWorld
Definition: World.h:887
Storage class for commands issued for delayed execution.
Definition: World.h:507
Definition: World.h:73
void commandFinished(void *, bool)
Definition: CliRunnable.cpp:111
G3D::int16 x
Definition: Vector2int16.h:37
static void StopNow(uint8 exitcode)
Definition: World.h:662
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
Definition: format.h:3083

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void commandFinished ( void *  ,
bool   
)
112 {
113  printf("TC> ");
114  fflush(stdout);
115 }
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
Definition: format.h:3083

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void FreezeDetectorHandler ( const boost::system::error_code &  error)
432 {
433  if (!error)
434  {
435  uint32 curtime = getMSTime();
436 
437  uint32 worldLoopCounter = World::m_worldLoopCounter;
438  if (_worldLoopCounter != worldLoopCounter)
439  {
440  _lastChangeMsTime = curtime;
441  _worldLoopCounter = worldLoopCounter;
442  }
443  // possible freeze
445  {
446  TC_LOG_ERROR("server.worldserver", "World Thread hangs, kicking out server!");
447  ABORT();
448  }
449 
450  _freezeCheckTimer.expires_from_now(boost::posix_time::seconds(1));
452  }
453 }
uint32 getMSTimeDiff(uint32 oldMSTime, uint32 newMSTime)
Definition: Timer.h:33
uint32 _maxCoreStuckTimeInMs(0)
boost::asio::deadline_timer _freezeCheckTimer(_ioService)
uint32 getMSTime()
Definition: Timer.h:24
void FreezeDetectorHandler(const boost::system::error_code &error)
Definition: Main.cpp:431
float seconds()
Definition: units.h:97
static std::atomic< uint32 > m_worldLoopCounter
Definition: World.h:549
uint32 _lastChangeMsTime(0)
uint32_t uint32
Definition: Define.h:150
#define ABORT
Definition: Errors.h:56
#define TC_LOG_ERROR(filterType__,...)
Definition: Log.h:207
uint32 _worldLoopCounter(0)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

variables_map GetConsoleArguments ( int  argc,
char **  argv,
std::string &  cfg_file,
std::string &  cfg_service 
)
583 {
584  // Silences warning about configService not be used if the OS is not Windows
585  (void)configService;
586 
587  options_description all("Allowed options");
588  all.add_options()
589  ("help,h", "print usage message")
590  ("version,v", "print version build info")
591  ("config,c", value<std::string>(&configFile)->default_value(_TRINITY_CORE_CONFIG), "use <arg> as configuration file")
592  ;
593 #ifdef _WIN32
594  options_description win("Windows platform specific options");
595  win.add_options()
596  ("service,s", value<std::string>(&configService)->default_value(""), "Windows service options: [install | uninstall]")
597  ;
598 
599  all.add(win);
600 #endif
601  variables_map vm;
602  try
603  {
604  store(command_line_parser(argc, argv).options(all).allow_unregistered().run(), vm);
605  notify(vm);
606  }
607  catch (std::exception& e)
608  {
609  std::cerr << e.what() << "\n";
610  }
611 
612  if (vm.count("help"))
613  {
614  std::cout << all << "\n";
615  }
616  else if (vm.count("version"))
617  {
618  std::cout << GitRevision::GetFullVersion() << "\n";
619  }
620 
621  return vm;
622 }
TC_COMMON_API char const * GetFullVersion()
Definition: GitRevision.cpp:51
bool all(float x)
Definition: g3dmath.h:431
#define _TRINITY_CORE_CONFIG
Definition: Main.cpp:57

+ Here is the call graph for this function:

bool LoadRealmInfo ( )
466 {
467  boost::asio::ip::tcp::resolver resolver(_ioService);
468  boost::asio::ip::tcp::resolver::iterator end;
469 
470  QueryResult result = LoginDatabase.PQuery("SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild, Region, Battlegroup FROM realmlist WHERE id = %u", realm.Id.Realm);
471  if (!result)
472  return false;
473 
474  Field* fields = result->Fetch();
475  realm.Name = fields[1].GetString();
476  boost::asio::ip::tcp::resolver::query externalAddressQuery(ip::tcp::v4(), fields[2].GetString(), "");
477 
478  boost::system::error_code ec;
479  boost::asio::ip::tcp::resolver::iterator endPoint = resolver.resolve(externalAddressQuery, ec);
480  if (endPoint == end || ec)
481  {
482  TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[2].GetString().c_str());
483  return false;
484  }
485 
486  realm.ExternalAddress = (*endPoint).endpoint().address();
487 
488  boost::asio::ip::tcp::resolver::query localAddressQuery(ip::tcp::v4(), fields[3].GetString(), "");
489  endPoint = resolver.resolve(localAddressQuery, ec);
490  if (endPoint == end || ec)
491  {
492  TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[3].GetString().c_str());
493  return false;
494  }
495 
496  realm.LocalAddress = (*endPoint).endpoint().address();
497 
498  boost::asio::ip::tcp::resolver::query localSubmaskQuery(ip::tcp::v4(), fields[4].GetString(), "");
499  endPoint = resolver.resolve(localSubmaskQuery, ec);
500  if (endPoint == end || ec)
501  {
502  TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[4].GetString().c_str());
503  return false;
504  }
505 
506  realm.LocalSubnetMask = (*endPoint).endpoint().address();
507 
508  realm.Port = fields[5].GetUInt16();
509  realm.Type = fields[6].GetUInt8();
510  realm.Flags = RealmFlags(fields[7].GetUInt8());
511  realm.Timezone = fields[8].GetUInt8();
512  realm.AllowedSecurityLevel = AccountTypes(fields[9].GetUInt8());
513  realm.PopulationLevel = fields[10].GetFloat();
514  realm.Id.Region = fields[12].GetUInt8();
515  realm.Id.Site = fields[13].GetUInt8();
516  realm.Build = fields[11].GetUInt32();
517  return true;
518 }
uint32 Realm
Definition: Realm.h:53
uint8 Region
Definition: Realm.h:51
std::string Name
Definition: Realm.h:92
AccountTypes AllowedSecurityLevel
Definition: Realm.h:96
float GetFloat() const
Definition: Field.h:222
QueryResult PQuery(Format &&sql, T *conn, Args &&...args)
Definition: DatabaseWorkerPool.h:165
Realm realm
Definition: World.cpp:3485
Class used to access individual fields of database query result.
Definition: Field.h:56
char * query(struct soap *soap)
Definition: httpget.cpp:244
uint16 Port
Definition: Realm.h:91
ip::address ExternalAddress
Definition: Realm.h:88
LoginDatabaseWorkerPool LoginDatabase
Accessor to the realm/login database.
Definition: DatabaseEnv.cpp:22
uint8 GetUInt8() const
Definition: Field.h:70
ip::address LocalSubnetMask
Definition: Realm.h:90
uint8 Site
Definition: Realm.h:52
Battlenet::RealmHandle Id
Definition: Realm.h:86
ip::address LocalAddress
Definition: Realm.h:89
AccountTypes
Definition: Common.h:106
std::shared_ptr< ResultSet > QueryResult
Definition: QueryResult.h:61
uint16 GetUInt16() const
Definition: Field.h:108
boost::asio::io_service _ioService
Definition: Main.cpp:76
uint32 Build
Definition: Realm.h:87
RealmFlags
Definition: Realm.h:27
uint8 Timezone
Definition: Realm.h:95
uint32 GetUInt32() const
Definition: Field.h:146
#define TC_LOG_ERROR(filterType__,...)
Definition: Log.h:207
uint8 Type
Definition: Realm.h:93
RealmFlags Flags
Definition: Realm.h:94
std::string GetString() const
Definition: Field.h:276
float PopulationLevel
Definition: Realm.h:97

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

int main ( int  argc,
char **  argv 
)

Launch the Trinity server.

worldserver PID file creation

  • Clean database before leaving
96 {
97  signal(SIGABRT, &Trinity::AbortHandler);
98 
99  std::string configFile = _TRINITY_CORE_CONFIG;
100  std::string configService;
101 
102  auto vm = GetConsoleArguments(argc, argv, configFile, configService);
103  // exit if help or version is enabled
104  if (vm.count("help") || vm.count("version"))
105  return 0;
106 
108 
109 #ifdef _WIN32
110  if (configService.compare("install") == 0)
111  return WinServiceInstall() ? 0 : 1;
112  else if (configService.compare("uninstall") == 0)
113  return WinServiceUninstall() ? 0 : 1;
114  else if (configService.compare("run") == 0)
115  return WinServiceRun() ? 0 : 0;
116 #endif
117 
118  std::string configError;
119  if (!sConfigMgr->LoadInitial(configFile, configError))
120  {
121  printf("Error in config file: %s\n", configError.c_str());
122  return 1;
123  }
124 
125  sLog->RegisterAppender<AppenderDB>();
126  // If logs are supposed to be handled async then we need to pass the io_service into the Log singleton
127  sLog->Initialize(sConfigMgr->GetBoolDefault("Log.Async.Enable", false) ? &_ioService : nullptr);
128 
129  TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon)", GitRevision::GetFullVersion());
130  TC_LOG_INFO("server.worldserver", "<Ctrl-C> to stop.\n");
131  TC_LOG_INFO("server.worldserver", " ______ __");
132  TC_LOG_INFO("server.worldserver", "/\\__ _\\ __ __/\\ \\__");
133  TC_LOG_INFO("server.worldserver", "\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __");
134  TC_LOG_INFO("server.worldserver", " \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\");
135  TC_LOG_INFO("server.worldserver", " \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\");
136  TC_LOG_INFO("server.worldserver", " \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\");
137  TC_LOG_INFO("server.worldserver", " \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\");
138  TC_LOG_INFO("server.worldserver", " C O R E /\\___/");
139  TC_LOG_INFO("server.worldserver", "http://TrinityCore.org \\/__/\n");
140  TC_LOG_INFO("server.worldserver", "Using configuration file %s.", configFile.c_str());
141  TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
142  TC_LOG_INFO("server.worldserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100);
143 
145 
146  // Seed the OpenSSL's PRNG here.
147  // That way it won't auto-seed when calling BigNumber::SetRand and slow down the first world login
148  BigNumber seed;
149  seed.SetRand(16 * 8);
150 
152  std::string pidFile = sConfigMgr->GetStringDefault("PidFile", "");
153  if (!pidFile.empty())
154  {
155  if (uint32 pid = CreatePIDFile(pidFile))
156  TC_LOG_INFO("server.worldserver", "Daemon PID: %u\n", pid);
157  else
158  {
159  TC_LOG_ERROR("server.worldserver", "Cannot create PID file %s.\n", pidFile.c_str());
160  return 1;
161  }
162  }
163 
164  // Set signal handlers (this must be done before starting io_service threads, because otherwise they would unblock and exit)
165  boost::asio::signal_set signals(_ioService, SIGINT, SIGTERM);
166 #if PLATFORM == PLATFORM_WINDOWS
167  signals.add(SIGBREAK);
168 #endif
169  signals.async_wait(SignalHandler);
170 
171  // Start the Boost based thread pool
172  int numThreads = sConfigMgr->GetIntDefault("ThreadPool", 1);
173  std::vector<std::thread> threadPool;
174 
175  if (numThreads < 1)
176  numThreads = 1;
177 
178  for (int i = 0; i < numThreads; ++i)
179  threadPool.push_back(std::thread(boost::bind(&boost::asio::io_service::run, &_ioService)));
180 
181  // Set process priority according to configuration settings
182  SetProcessPriority("server.worldserver");
183 
184  // Start the databases
185  if (!StartDB())
186  {
187  ShutdownThreadPool(threadPool);
188  return 1;
189  }
190 
191  // Set server offline (not connectable)
192  LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realm.Id.Realm);
193 
194  sRealmList->Initialize(_ioService, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 10));
195 
196  LoadRealmInfo();
197 
198  // Initialize the World
199  sScriptMgr->SetScriptLoader(AddScripts);
200  sWorld->SetInitialWorldSettings();
201 
202  // Launch CliRunnable thread
203  std::thread* cliThread = nullptr;
204 #ifdef _WIN32
205  if (sConfigMgr->GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
206 #else
207  if (sConfigMgr->GetBoolDefault("Console.Enable", true))
208 #endif
209  {
210  cliThread = new std::thread(CliThread);
211  }
212 
213  // Start the Remote Access port (acceptor) if enabled
214  AsyncAcceptor* raAcceptor = nullptr;
215  if (sConfigMgr->GetBoolDefault("Ra.Enable", false))
216  raAcceptor = StartRaSocketAcceptor(_ioService);
217 
218  // Start soap serving thread if enabled
219  std::thread* soapThread = nullptr;
220  if (sConfigMgr->GetBoolDefault("SOAP.Enabled", false))
221  {
222  soapThread = new std::thread(TCSoapThread, sConfigMgr->GetStringDefault("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetIntDefault("SOAP.Port", 7878)));
223  }
224 
225  // Launch the worldserver listener socket
226  uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD));
227  std::string worldListener = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0");
228 
229  int networkThreads = sConfigMgr->GetIntDefault("Network.Threads", 1);
230 
231  if (networkThreads <= 0)
232  {
233  TC_LOG_ERROR("server.worldserver", "Network.Threads must be greater than 0");
234  return false;
235  }
236 
237  sWorldSocketMgr.StartNetwork(_ioService, worldListener, worldPort, networkThreads);
238 
239  // Set server online (allow connecting now)
240  LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag & ~%u, population = 0 WHERE id = '%u'", REALM_FLAG_OFFLINE, realm.Id.Realm);
241  realm.PopulationLevel = 0.0f;
243 
244  // Start the freeze check callback cycle in 5 seconds (cycle itself is 1 sec)
245  if (int coreStuckTime = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0))
246  {
247  _maxCoreStuckTimeInMs = coreStuckTime * 1000;
248  _freezeCheckTimer.expires_from_now(boost::posix_time::seconds(5));
250  TC_LOG_INFO("server.worldserver", "Starting up anti-freeze thread (%u seconds max stuck time)...", coreStuckTime);
251  }
252 
253  TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon) ready...", GitRevision::GetFullVersion());
254 
255  sScriptMgr->OnStartup();
256 
257  WorldUpdateLoop();
258 
259  // Shutdown starts here
260  ShutdownThreadPool(threadPool);
261 
262  sLog->SetSynchronous();
263 
264  sScriptMgr->OnShutdown();
265 
266  sWorld->KickAll(); // save and kick all players
267  sWorld->UpdateSessions(1); // real players unload required UpdateSessions call
268 
269  // unload battleground templates before different singletons destroyed
270  sBattlegroundMgr->DeleteAllBattlegrounds();
271 
272  sWorldSocketMgr.StopNetwork();
273 
274  sInstanceSaveMgr->Unload();
275  sOutdoorPvPMgr->Die(); // unload it before MapManager
276  sMapMgr->UnloadAll(); // unload all grids (including locked in memory)
277  sScriptMgr->Unload();
278 
279  // set server offline
280  LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realm.Id.Realm);
281  sRealmList->Close();
282 
283  // Clean up threads if any
284  if (soapThread != nullptr)
285  {
286  soapThread->join();
287  delete soapThread;
288  }
289 
290  delete raAcceptor;
291 
294 
295  StopDB();
296 
297  TC_LOG_INFO("server.worldserver", "Halting process...");
298 
299  ShutdownCLIThread(cliThread);
300 
302 
304 
305  // 0 - normal shutdown
306  // 1 - shutdown at error
307  // 2 - restart command used, this code can be used by restarter for restart Trinityd
308 
309  return World::GetExitCode();
310 }
Definition: BigNumber.h:28
uint32 Realm
Definition: Realm.h:53
Definition: AsyncAcceptor.h:28
#define sOutdoorPvPMgr
Definition: OutdoorPvPMgr.h:105
uint32 CreatePIDFile(std::string const &filename)
create PID file
Definition: Util.cpp:222
Realm realm
Definition: World.cpp:3485
void StopDB()
Close the connection to the database.
Definition: Main.cpp:243
variables_map GetConsoleArguments(int argc, char **argv, std::string &configFile, std::string &configService)
Definition: Main.cpp:298
uint32 _maxCoreStuckTimeInMs(0)
void AddScripts()
Definition: ScriptLoader.cpp:37
boost::asio::deadline_timer _freezeCheckTimer(_ioService)
#define sWorldSocketMgr
Definition: WorldSocketMgr.h:62
#define sConfigMgr
Definition: Config.h:61
TC_COMMON_API char const * GetFullVersion()
Definition: GitRevision.cpp:51
void FreezeDetectorHandler(const boost::system::error_code &error)
Definition: Main.cpp:431
#define sLog
Definition: Log.h:154
int m_ServiceStatus
Definition: Main.cpp:56
#define sWorld
Definition: World.h:887
Definition: Realm.h:31
bool LoadRealmInfo()
Definition: Main.cpp:465
float seconds()
Definition: units.h:97
uint16_t uint16
Definition: g3dmath.h:166
AsyncAcceptor * StartRaSocketAcceptor(boost::asio::io_service &ioService)
Definition: Main.cpp:455
#define GOOGLE_PROTOBUF_VERIFY_VERSION
Definition: common.h:149
void SignalHandler(boost::system::error_code const &error, int signalNumber)
Definition: Main.cpp:249
LoginDatabaseWorkerPool LoginDatabase
Accessor to the realm/login database.
Definition: DatabaseEnv.cpp:22
void ShutdownCLIThread(std::thread *cliThread)
Definition: Main.cpp:312
static uint8 GetExitCode()
Definition: World.h:661
void DirectPExecute(Format &&sql, Args &&...args)
Definition: DatabaseWorkerPool.h:134
void ClearOnlineAccounts()
Clear 'online' status for all accounts with characters in this realm.
Definition: Main.cpp:568
Battlenet::RealmHandle Id
Definition: Realm.h:86
LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary()
void AbortHandler(int)
Definition: Errors.cpp:99
uint32_t uint32
Definition: Define.h:150
void CliThread()
Thread start
Definition: CliRunnable.cpp:133
uint16_t uint16
Definition: Define.h:151
void SetRand(int32 numbits)
Definition: BigNumber.cpp:74
boost::asio::io_service _ioService
Definition: Main.cpp:76
Definition: World.h:215
#define sInstanceSaveMgr
Definition: InstanceSaveMgr.h:243
void ShutdownThreadPool(std::vector< std::thread > &threadPool)
Definition: Main.cpp:372
RealmFlags
Definition: Realm.h:27
bool StartDB()
Initialize connection to the database.
Definition: Main.cpp:225
#define sMapMgr
Definition: MapManager.h:194
#define sRealmList
Definition: RealmList.h:101
#define sBattlegroundMgr
Definition: BattlegroundMgr.h:181
#define _TRINITY_CORE_CONFIG
Definition: Main.cpp:57
Definition: AppenderDB.h:23
#define TC_LOG_INFO(filterType__,...)
Definition: Log.h:201
void TCSoapThread(const std::string &host, uint16 port)
Definition: TCSoap.cpp:25
#define sScriptMgr
Definition: ScriptMgr.h:837
#define TC_LOG_ERROR(filterType__,...)
Definition: Log.h:207
RealmFlags Flags
Definition: Realm.h:94
void WorldUpdateLoop()
Definition: Main.cpp:384
void SetProcessPriority(const std::string &logChannel)
Definition: ProcessPriority.h:29
TC_COMMON_API void threadsCleanup()
Needs to be called after threads using openssl are despawned.
Definition: OpenSSLCrypto.cpp:50
TC_COMMON_API void threadsSetup()
Needs to be called before threads using openssl are spawned.
Definition: OpenSSLCrypto.cpp:39
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
Definition: format.h:3083
float PopulationLevel
Definition: Realm.h:97

+ Here is the call graph for this function:

void ShutdownCLIThread ( std::thread *  cliThread)
313 {
314  if (cliThread != nullptr)
315  {
316 #ifdef _WIN32
317  // First try to cancel any I/O in the CLI thread
318  if (!CancelSynchronousIo(cliThread->native_handle()))
319  {
320  // if CancelSynchronousIo() fails, print the error and try with old way
321  DWORD errorCode = GetLastError();
322  LPSTR errorBuffer;
323 
324  DWORD formatReturnCode = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
325  nullptr, errorCode, 0, (LPTSTR)&errorBuffer, 0, nullptr);
326  if (!formatReturnCode)
327  errorBuffer = "Unknown error";
328 
329  TC_LOG_DEBUG("server.worldserver", "Error cancelling I/O of CliThread, error code %u, detail: %s",
330  uint32(errorCode), errorBuffer);
331  LocalFree(errorBuffer);
332 
333  // send keyboard input to safely unblock the CLI thread
334  INPUT_RECORD b[4];
335  HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
336  b[0].EventType = KEY_EVENT;
337  b[0].Event.KeyEvent.bKeyDown = TRUE;
338  b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
339  b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
340  b[0].Event.KeyEvent.wRepeatCount = 1;
341 
342  b[1].EventType = KEY_EVENT;
343  b[1].Event.KeyEvent.bKeyDown = FALSE;
344  b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
345  b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
346  b[1].Event.KeyEvent.wRepeatCount = 1;
347 
348  b[2].EventType = KEY_EVENT;
349  b[2].Event.KeyEvent.bKeyDown = TRUE;
350  b[2].Event.KeyEvent.dwControlKeyState = 0;
351  b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
352  b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
353  b[2].Event.KeyEvent.wRepeatCount = 1;
354  b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;
355 
356  b[3].EventType = KEY_EVENT;
357  b[3].Event.KeyEvent.bKeyDown = FALSE;
358  b[3].Event.KeyEvent.dwControlKeyState = 0;
359  b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
360  b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
361  b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
362  b[3].Event.KeyEvent.wRepeatCount = 1;
363  DWORD numb;
364  WriteConsoleInput(hStdIn, b, 4, &numb);
365  }
366 #endif
367  cliThread->join();
368  delete cliThread;
369  }
370 }
void * HANDLE
Definition: CascPort.h:146
#define TC_LOG_DEBUG(filterType__,...)
Definition: Log.h:198
unsigned int DWORD
Definition: CascPort.h:139
int GetLastError()
Definition: Common.cpp:70
uint32_t uint32
Definition: g3dmath.h:168

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void ShutdownThreadPool ( std::vector< std::thread > &  threadPool)
373 {
374  sScriptMgr->OnNetworkStop();
375 
376  _ioService.stop();
377 
378  for (auto& thread : threadPool)
379  {
380  thread.join();
381  }
382 }
boost::asio::io_service _ioService
Definition: Main.cpp:76
#define sScriptMgr
Definition: ScriptMgr.h:837

+ Here is the caller graph for this function:

void SignalHandler ( const boost::system::error_code &  error,
int  signalNumber 
)
426 {
427  if (!error)
429 }
Definition: World.h:73
static void StopNow(uint8 exitcode)
Definition: World.h:662

+ Here is the call graph for this function:

bool StartDB ( )

Initialize connection to the databases.

  • Get the realm Id from the configuration file
  • Clean the database before starting
  • Insert version info into DB
522 {
524 
525  // Load databases
526  DatabaseLoader loader("server.worldserver", DatabaseLoader::DATABASE_NONE);
527  loader
528  .AddDatabase(LoginDatabase, "Login")
529  .AddDatabase(CharacterDatabase, "Character")
530  .AddDatabase(WorldDatabase, "World")
531  .AddDatabase(HotfixDatabase, "Hotfix");
532 
533  if (!loader.Load())
534  return false;
535 
537  realm.Id.Realm = sConfigMgr->GetIntDefault("RealmID", 0);
538  if (!realm.Id.Realm)
539  {
540  TC_LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file");
541  return false;
542  }
543 
544  TC_LOG_INFO("server.worldserver", "Realm running as realm ID %u", realm.Id.Realm);
545 
548 
550  WorldDatabase.PExecute("UPDATE version SET core_version = '%s', core_revision = '%s'", GitRevision::GetFullVersion(), GitRevision::GetHash()); // One-time query
551 
552  sWorld->LoadDBVersion();
553 
554  TC_LOG_INFO("server.worldserver", "Using World DB: %s", sWorld->GetDBVersion());
555  return true;
556 }
uint32 Realm
Definition: Realm.h:53
Definition: DatabaseLoader.h:44
Realm realm
Definition: World.cpp:3485
#define sConfigMgr
Definition: Config.h:61
TC_COMMON_API char const * GetFullVersion()
Definition: GitRevision.cpp:51
WorldDatabaseWorkerPool WorldDatabase
Accessor to the world database.
Definition: DatabaseEnv.cpp:20
#define sWorld
Definition: World.h:887
LoginDatabaseWorkerPool LoginDatabase
Accessor to the realm/login database.
Definition: DatabaseEnv.cpp:22
void PExecute(Format &&sql, Args &&...args)
Definition: DatabaseWorkerPool.h:99
Definition: DatabaseLoader.h:30
void ClearOnlineAccounts()
Clear 'online' status for all accounts with characters in this realm.
Definition: Main.cpp:568
Battlenet::RealmHandle Id
Definition: Realm.h:86
HotfixDatabaseWorkerPool HotfixDatabase
Accessor to the hotfix database.
Definition: DatabaseEnv.cpp:23
static void Library_Init()
Definition: MySQLThreading.h:26
TC_COMMON_API char const * GetHash()
Definition: GitRevision.cpp:4
CharacterDatabaseWorkerPool CharacterDatabase
Accessor to the character database.
Definition: DatabaseEnv.cpp:21
#define TC_LOG_INFO(filterType__,...)
Definition: Log.h:201
#define TC_LOG_ERROR(filterType__,...)
Definition: Log.h:207

+ Here is the call graph for this function:

AsyncAcceptor * StartRaSocketAcceptor ( boost::asio::io_service &  ioService)
456 {
457  uint16 raPort = uint16(sConfigMgr->GetIntDefault("Ra.Port", 3443));
458  std::string raListener = sConfigMgr->GetStringDefault("Ra.IP", "0.0.0.0");
459 
460  AsyncAcceptor* acceptor = new AsyncAcceptor(ioService, raListener, raPort);
461  acceptor->AsyncAccept<RASession>();
462  return acceptor;
463 }
Definition: AsyncAcceptor.h:28
#define sConfigMgr
Definition: Config.h:61
uint16_t uint16
Definition: g3dmath.h:166
Definition: RASession.h:33
uint16_t uint16
Definition: Define.h:151
void AsyncAccept()
Definition: AsyncAcceptor.h:90

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void StopDB ( )
559 {
563 
565 }
static void Library_End()
Definition: MySQLThreading.h:31
WorldDatabaseWorkerPool WorldDatabase
Accessor to the world database.
Definition: DatabaseEnv.cpp:20
void Close()
Definition: DatabaseWorkerPool.cpp:72
LoginDatabaseWorkerPool LoginDatabase
Accessor to the realm/login database.
Definition: DatabaseEnv.cpp:22
CharacterDatabaseWorkerPool CharacterDatabase
Accessor to the character database.
Definition: DatabaseEnv.cpp:21

+ Here is the call graph for this function:

void utf8print ( void *  ,
const char *  str 
)
93 {
94 #if PLATFORM == PLATFORM_WINDOWS
95  wchar_t wtemp_buf[6000];
96  size_t wtemp_len = 6000-1;
97  if (!Utf8toWStr(str, strlen(str), wtemp_buf, wtemp_len))
98  return;
99 
100  char temp_buf[6000];
101  CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], wtemp_len+1);
102  printf(temp_buf);
103 #else
104 {
105  printf("%s", str);
106  fflush(stdout);
107 }
108 #endif
109 }
bool Utf8toWStr(char const *utf8str, size_t csize, wchar_t *wstr, size_t &wsize)
Definition: Util.cpp:281
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
Definition: format.h:3083

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void WorldUpdateLoop ( )
385 {
386  uint32 realCurrTime = 0;
387  uint32 realPrevTime = getMSTime();
388 
389  uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST
390 
392  while (!World::IsStopped())
393  {
395  realCurrTime = getMSTime();
396 
397  uint32 diff = getMSTimeDiff(realPrevTime, realCurrTime);
398 
399  sWorld->Update(diff);
400  realPrevTime = realCurrTime;
401 
402  // diff (D0) include time of previous sleep (d0) + tick time (t0)
403  // we want that next d1 + t1 == WORLD_SLEEP_CONST
404  // we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement
405  // d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0
406  if (diff <= WORLD_SLEEP_CONST + prevSleepTime)
407  {
408  prevSleepTime = WORLD_SLEEP_CONST + prevSleepTime - diff;
409 
410  std::this_thread::sleep_for(std::chrono::milliseconds(prevSleepTime));
411  }
412  else
413  prevSleepTime = 0;
414 
415 #ifdef _WIN32
416  if (m_ServiceStatus == 0)
418 
419  while (m_ServiceStatus == 2)
420  Sleep(1000);
421 #endif
422  }
423 }
uint32 getMSTimeDiff(uint32 oldMSTime, uint32 newMSTime)
Definition: Timer.h:33
uint32 getMSTime()
Definition: Timer.h:24
static bool IsStopped()
Definition: World.h:663
int m_ServiceStatus
Definition: Main.cpp:56
#define sWorld
Definition: World.h:887
static std::atomic< uint32 > m_worldLoopCounter
Definition: World.h:549
#define WORLD_SLEEP_CONST
Definition: Main.cpp:60
uint32_t uint32
Definition: Define.h:150
Definition: World.h:73
float milliseconds()
Definition: units.h:92
static void StopNow(uint8 exitcode)
Definition: World.h:662

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Variable Documentation

boost::asio::io_service _ioService