AzerothCore 3.3.5a
OpenSource WoW Emulator
Loading...
Searching...
No Matches
Acore Daemon

Files

file  CliRunnable.cpp
 
file  CliRunnable.h
 
file  Main.cpp
 

Classes

class  FreezeDetector
 

Macros

#define _ACORE_CORE_CONFIG   "worldserver.conf"
 

Functions

static void PrintCliPrefix ()
 
void utf8print (void *, std::string_view str)
 
void commandFinished (void *, bool)
 
void CliThread ()
 Thread start
 
 FreezeDetector::FreezeDetector (Acore::Asio::IoContext &ioContext, uint32 maxCoreStuckTime)
 
static void FreezeDetector::Start (std::shared_ptr< FreezeDetector > const &freezeDetector)
 
static void FreezeDetector::Handler (std::weak_ptr< FreezeDetector > freezeDetectorRef, boost::system::error_code const &error)
 
void SignalHandler (boost::system::error_code const &error, int signalNumber)
 
void ClearOnlineAccounts ()
 Clear 'online' status for all accounts with characters in this realm.
 
bool StartDB ()
 Initialize connection to the databases.
 
void StopDB ()
 
bool LoadRealmInfo (Acore::Asio::IoContext &ioContext)
 
AsyncAcceptorStartRaSocketAcceptor (Acore::Asio::IoContext &ioContext)
 
void ShutdownCLIThread (std::thread *cliThread)
 
void WorldUpdateLoop ()
 
variables_map GetConsoleArguments (int argc, char **argv, fs::path &configFile, std::string &cfg_service)
 
int main (int argc, char **argv)
 Launch the Azeroth server.
 

Variables

static constexpr char CLI_PREFIX [] = "AC> "
 
char serviceName [] = "worldserver"
 
char serviceLongName [] = "AzerothCore world service"
 
char serviceDescription [] = "AzerothCore World of Warcraft emulator world service"
 
int m_ServiceStatus = -1
 
boost::asio::steady_timer FreezeDetector::_timer
 
uint32 FreezeDetector::_worldLoopCounter
 
uint32 FreezeDetector::_lastChangeMsTime
 
uint32 FreezeDetector::_maxCoreStuckTimeInMs
 

Detailed Description

Macro Definition Documentation

◆ _ACORE_CORE_CONFIG

#define _ACORE_CORE_CONFIG   "worldserver.conf"

Function Documentation

◆ ClearOnlineAccounts()

void ClearOnlineAccounts ( )

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

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

487{
488 // Reset online status for all accounts with characters on the current realm
489 // pussywizard: tc query would set online=0 even if logged in on another realm >_>
490 LoginDatabase.DirectExecute("UPDATE account SET online = 0 WHERE online = {}", realm.Id.Realm);
491
492 // Reset online status for all characters
493 CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0");
494}
DatabaseWorkerPool< LoginDatabaseConnection > LoginDatabase
Accessor to the realm/login database.
Definition DatabaseEnv.cpp:22
DatabaseWorkerPool< CharacterDatabaseConnection > CharacterDatabase
Accessor to the character database.
Definition DatabaseEnv.cpp:21
Realm realm
Definition World.cpp:111
uint32 Realm
Definition Realm.h:43
RealmHandle Id
Definition Realm.h:69

References CharacterDatabase, Realm::Id, LoginDatabase, realm, and RealmHandle::Realm.

Referenced by main(), and StartDB().

◆ CliThread()

void CliThread ( )

#include <azerothcore-wotlk/src/server/apps/worldserver/CommandLine/CliRunnable.cpp>

Thread start

Command Line Interface handling thread.

  • As long as the World is running (no World::m_stopEvent), get the command line and handle it
109{
110#if AC_PLATFORM == AC_PLATFORM_WINDOWS
111 // print this here the first time
112 // later it will be printed after command queue updates
114#else
115 ::rl_attempted_completion_function = &Acore::Impl::Readline::cli_completion;
116 {
117 static char BLANK = '\0';
118 ::rl_completer_word_break_characters = &BLANK;
119 }
120 ::rl_event_hook = &Acore::Impl::Readline::cli_hook_func;
121#endif
122
123 if (sConfigMgr->GetOption<bool>("BeepAtStart", true))
124 printf("\a"); // \a = Alert
125
126#if AC_PLATFORM == AC_PLATFORM_WINDOWS
127 if (sConfigMgr->GetOption<bool>("FlashAtStart", true))
128 {
129 FLASHWINFO fInfo;
130 fInfo.cbSize = sizeof(FLASHWINFO);
131 fInfo.dwFlags = FLASHW_TRAY | FLASHW_TIMERNOFG;
132 fInfo.hwnd = GetConsoleWindow();
133 fInfo.uCount = 0;
134 fInfo.dwTimeout = 0;
135 FlashWindowEx(&fInfo);
136 }
137#endif
138
140 while (!World::IsStopped())
141 {
142 fflush(stdout);
143
144 std::string command;
145
146#if AC_PLATFORM == AC_PLATFORM_WINDOWS
147 wchar_t commandbuf[256];
148 if (fgetws(commandbuf, sizeof(commandbuf), stdin))
149 {
150 if (!WStrToUtf8(commandbuf, wcslen(commandbuf), command))
151 {
153 continue;
154 }
155 }
156#else
157 char* command_str = readline(CLI_PREFIX);
158 ::rl_bind_key('\t', ::rl_complete);
159 if (command_str != nullptr)
160 {
161 command = command_str;
162 free(command_str);
163 }
164#endif
165
166 if (!command.empty())
167 {
168 std::size_t nextLineIndex = command.find_first_of("\r\n");
169 if (nextLineIndex != std::string::npos)
170 {
171 if (nextLineIndex == 0)
172 {
173#if AC_PLATFORM == AC_PLATFORM_WINDOWS
175#endif
176 continue;
177 }
178
179 command.erase(nextLineIndex);
180 }
181
182 fflush(stdout);
183 sWorld->QueueCliCommand(new CliCommandHolder(nullptr, command.c_str(), &utf8print, &commandFinished));
184#if AC_PLATFORM != AC_PLATFORM_WINDOWS
185 add_history(command.c_str());
186#endif
187 }
188 else if (feof(stdin))
189 {
191 }
192 }
193}
bool WStrToUtf8(wchar_t const *wstr, std::size_t size, std::string &utf8str)
Definition Util.cpp:333
static void StopNow(uint8 exitcode)
Definition World.h:188
static bool IsStopped()
Definition World.h:189
#define sConfigMgr
Definition Config.h:93
static void PrintCliPrefix()
Definition CliRunnable.cpp:38
static constexpr char CLI_PREFIX[]
Definition CliRunnable.cpp:36
void utf8print(void *, std::string_view str)
Definition CliRunnable.cpp:74
void commandFinished(void *, bool)
Definition CliRunnable.cpp:86
#define sWorld
Definition World.h:316
@ SHUTDOWN_EXIT_CODE
Definition World.h:53
Storage class for commands issued for delayed execution.
Definition IWorld.h:35

References CLI_PREFIX, commandFinished(), World::IsStopped(), PrintCliPrefix(), sConfigMgr, SHUTDOWN_EXIT_CODE, World::StopNow(), sWorld, utf8print(), and WStrToUtf8().

Referenced by main().

◆ commandFinished()

void commandFinished ( void *  ,
bool   
)

#include <azerothcore-wotlk/src/server/apps/worldserver/CommandLine/CliRunnable.cpp>

87{
89 fflush(stdout);
90}

References PrintCliPrefix().

Referenced by CliThread().

◆ FreezeDetector()

FreezeDetector::FreezeDetector ( Acore::Asio::IoContext ioContext,
uint32  maxCoreStuckTime 
)
inline

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

92 : _timer(ioContext), _worldLoopCounter(0), _lastChangeMsTime(getMSTime()), _maxCoreStuckTimeInMs(maxCoreStuckTime) { }
uint32 getMSTime()
Definition Timer.h:103
uint32 _lastChangeMsTime
Definition Main.cpp:105
uint32 _worldLoopCounter
Definition Main.cpp:104
boost::asio::steady_timer _timer
Definition Main.cpp:103
uint32 _maxCoreStuckTimeInMs
Definition Main.cpp:106

◆ GetConsoleArguments()

variables_map GetConsoleArguments ( int  argc,
char **  argv,
fs::path &  configFile,
std::string &  cfg_service 
)

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

709{
710 options_description all("Allowed options");
711 all.add_options()
712 ("help,h", "print usage message")
713 ("version,v", "print version build info")
714 ("dry-run,d", "Dry run")
715 ("config,c", value<fs::path>(&configFile)->default_value(fs::path(sConfigMgr->GetConfigPath() + std::string(_ACORE_CORE_CONFIG))), "use <arg> as configuration file")
716 ("config-policy", value<std::string>()->value_name("policy"), "override config severity policy (e.g. default=skip,critical_option=fatal)");
717
718#if AC_PLATFORM == AC_PLATFORM_WINDOWS
719 options_description win("Windows platform specific options");
720 win.add_options()
721 ("service,s", value<std::string>(&configService)->default_value(""), "Windows service options: [install | uninstall]");
722
723 all.add(win);
724#endif
725
726 variables_map vm;
727
728 try
729 {
730 store(command_line_parser(argc, argv).options(all).allow_unregistered().run(), vm);
731 notify(vm);
732 }
733 catch (std::exception const& e)
734 {
735 std::cerr << e.what() << "\n";
736 }
737
738 if (vm.count("help"))
739 std::cout << all << "\n";
740 else if (vm.count("version"))
741 std::cout << GitRevision::GetFullVersion() << "\n";
742 else if (vm.count("dry-run"))
743 sConfigMgr->setDryRun(true);
744
745 return vm;
746}
#define _ACORE_CORE_CONFIG
Definition Main.cpp:82
AC_COMMON_API char const * GetFullVersion()
Definition GitRevision.cpp:82

References _ACORE_CORE_CONFIG, GitRevision::GetFullVersion(), and sConfigMgr.

Referenced by main().

◆ Handler()

void FreezeDetector::Handler ( std::weak_ptr< FreezeDetector freezeDetectorRef,
boost::system::error_code const &  error 
)
static

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

613{
614 if (!error)
615 {
616 if (std::shared_ptr<FreezeDetector> freezeDetector = freezeDetectorRef.lock())
617 {
618 uint32 curtime = getMSTime();
619
620 uint32 worldLoopCounter = World::m_worldLoopCounter;
621 if (freezeDetector->_worldLoopCounter != worldLoopCounter)
622 {
623 freezeDetector->_lastChangeMsTime = curtime;
624 freezeDetector->_worldLoopCounter = worldLoopCounter;
625 }
626 // possible freeze
627 else
628 {
629 uint32 msTimeDiff = getMSTimeDiff(freezeDetector->_lastChangeMsTime, curtime);
630 if (msTimeDiff > freezeDetector->_maxCoreStuckTimeInMs)
631 {
632 LOG_ERROR("server.worldserver", "World Thread hangs for {} ms, forcing a crash!", msTimeDiff);
633 ABORT("World Thread hangs for {} ms, forcing a crash!", msTimeDiff);
634 }
635 }
636
637 freezeDetector->_timer.expires_at(Acore::Asio::SteadyTimer::GetExpirationTime(1));
638 freezeDetector->_timer.async_wait(std::bind(&FreezeDetector::Handler, freezeDetectorRef, std::placeholders::_1));
639 }
640 }
641}
std::uint32_t uint32
Definition Define.h:107
#define ABORT
Definition Errors.h:76
#define LOG_ERROR(filterType__,...)
Definition Log.h:158
uint32 getMSTimeDiff(uint32 oldMSTime, uint32 newMSTime)
Definition Timer.h:110
static uint32 m_worldLoopCounter
Definition World.h:142
static void Handler(std::weak_ptr< FreezeDetector > freezeDetectorRef, boost::system::error_code const &error)
Definition Main.cpp:612
auto GetExpirationTime(int32 seconds)
Definition SteadyTimer.h:25

References ABORT, Acore::Asio::SteadyTimer::GetExpirationTime(), getMSTime(), getMSTimeDiff(), FreezeDetector::Handler(), LOG_ERROR, and World::m_worldLoopCounter.

Referenced by FreezeDetector::Handler(), and FreezeDetector::Start().

◆ LoadRealmInfo()

bool LoadRealmInfo ( Acore::Asio::IoContext ioContext)

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

661{
662 QueryResult result = LoginDatabase.Query("SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE id = {}", realm.Id.Realm);
663 if (!result)
664 return false;
665
666 Acore::Asio::Resolver resolver(ioContext);
667
668 Field* fields = result->Fetch();
669 realm.Name = fields[1].Get<std::string>();
670
671 Optional<boost::asio::ip::tcp::endpoint> externalAddress = resolver.Resolve(boost::asio::ip::tcp::v4(), fields[2].Get<std::string>(), "");
672 if (!externalAddress)
673 {
674 LOG_ERROR("server.worldserver", "Could not resolve address {}", fields[2].Get<std::string>());
675 return false;
676 }
677
678 realm.ExternalAddress = std::make_unique<boost::asio::ip::address>(externalAddress->address());
679
680 Optional<boost::asio::ip::tcp::endpoint> localAddress = resolver.Resolve(boost::asio::ip::tcp::v4(), fields[3].Get<std::string>(), "");
681 if (!localAddress)
682 {
683 LOG_ERROR("server.worldserver", "Could not resolve address {}", fields[3].Get<std::string>());
684 return false;
685 }
686
687 realm.LocalAddress = std::make_unique<boost::asio::ip::address>(localAddress->address());
688
689 Optional<boost::asio::ip::tcp::endpoint> localSubmask = resolver.Resolve(boost::asio::ip::tcp::v4(), fields[4].Get<std::string>(), "");
690 if (!localSubmask)
691 {
692 LOG_ERROR("server.worldserver", "Could not resolve address {}", fields[4].Get<std::string>());
693 return false;
694 }
695
696 realm.LocalSubnetMask = std::make_unique<boost::asio::ip::address>(localSubmask->address());
697
698 realm.Port = fields[5].Get<uint16>();
699 realm.Type = fields[6].Get<uint8>();
700 realm.Flags = RealmFlags(fields[7].Get<uint8>());
701 realm.Timezone = fields[8].Get<uint8>();
702 realm.AllowedSecurityLevel = AccountTypes(fields[9].Get<uint8>());
703 realm.PopulationLevel = fields[10].Get<float>();
704 realm.Build = fields[11].Get<uint32>();
705 return true;
706}
AccountTypes
Definition Common.h:56
std::shared_ptr< ResultSet > QueryResult
Definition DatabaseEnvFwd.h:27
std::uint8_t uint8
Definition Define.h:109
std::uint16_t uint16
Definition Define.h:108
std::optional< T > Optional
Optional helper class to wrap optional values within.
Definition Optional.h:24
RealmFlags
Definition Realm.h:26
Definition Resolver.h:31
Class used to access individual fields of database query result.
Definition Field.h:98
std::enable_if_t< std::is_arithmetic_v< T >, T > Get() const
Definition Field.h:112
uint16 Port
Definition Realm.h:74
RealmFlags Flags
Definition Realm.h:77
AccountTypes AllowedSecurityLevel
Definition Realm.h:79
uint8 Timezone
Definition Realm.h:78
std::unique_ptr< boost::asio::ip::address > LocalSubnetMask
Definition Realm.h:73
std::unique_ptr< boost::asio::ip::address > LocalAddress
Definition Realm.h:72
float PopulationLevel
Definition Realm.h:80
uint32 Build
Definition Realm.h:70
std::unique_ptr< boost::asio::ip::address > ExternalAddress
Definition Realm.h:71
std::string Name
Definition Realm.h:75
uint8 Type
Definition Realm.h:76

References Realm::AllowedSecurityLevel, Realm::Build, Realm::ExternalAddress, Realm::Flags, Field::Get(), Realm::Id, Realm::LocalAddress, Realm::LocalSubnetMask, LOG_ERROR, LoginDatabase, Realm::Name, Realm::PopulationLevel, Realm::Port, realm, RealmHandle::Realm, Acore::Asio::Resolver::Resolve(), Realm::Timezone, and Realm::Type.

Referenced by main().

◆ main()

int main ( int  argc,
char **  argv 
)

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

Launch the Azeroth server.

worldserver PID file creation

  • Clean database before leaving
121{
123 signal(SIGABRT, &Acore::AbortHandler);
124
125 // Command line parsing
126 auto configFile = fs::path(sConfigMgr->GetConfigPath() + std::string(_ACORE_CORE_CONFIG));
127 std::string configService;
128 auto vm = GetConsoleArguments(argc, argv, configFile, configService);
129
130 // exit if help or version is enabled
131 if (vm.count("help") || vm.count("version"))
132 return 0;
133
134#if AC_PLATFORM == AC_PLATFORM_WINDOWS
135 if (configService.compare("install") == 0)
136 return WinServiceInstall() == true ? 0 : 1;
137 else if (configService.compare("uninstall") == 0)
138 return WinServiceUninstall() == true ? 0 : 1;
139 else if (configService.compare("run") == 0)
140 WinServiceRun();
141
142 Optional<UINT> newTimerResolution;
143 boost::system::error_code dllError;
144 std::shared_ptr<boost::dll::shared_library> winmm(new boost::dll::shared_library("winmm.dll", dllError, boost::dll::load_mode::search_system_folders), [&](boost::dll::shared_library* lib)
145 {
146 try
147 {
148 if (newTimerResolution)
149 lib->get<decltype(timeEndPeriod)>("timeEndPeriod")(*newTimerResolution);
150 }
151 catch (std::exception const&)
152 {
153 // ignore
154 }
155
156 delete lib;
157 });
158
159 if (winmm->is_loaded())
160 {
161 try
162 {
163 auto timeGetDevCapsPtr = winmm->get<decltype(timeGetDevCaps)>("timeGetDevCaps");
164 // setup timer resolution
165 TIMECAPS timeResolutionLimits;
166 if (timeGetDevCapsPtr(&timeResolutionLimits, sizeof(TIMECAPS)) == TIMERR_NOERROR)
167 {
168 auto timeBeginPeriodPtr = winmm->get<decltype(timeBeginPeriod)>("timeBeginPeriod");
169 newTimerResolution = std::min(std::max(timeResolutionLimits.wPeriodMin, 1u), timeResolutionLimits.wPeriodMax);
170 timeBeginPeriodPtr(*newTimerResolution);
171 }
172 }
173 catch (std::exception const& e)
174 {
175 printf("Failed to initialize timer resolution: %s\n", e.what());
176 }
177 }
178
179#endif
180
181 // Add file and args in config
182 sConfigMgr->Configure(configFile.generic_string(), {argv, argv + argc}, CONFIG_FILE_LIST);
183
184 if (!sConfigMgr->LoadAppConfigs())
185 return 1;
186
187 std::shared_ptr<Acore::Asio::IoContext> ioContext = std::make_shared<Acore::Asio::IoContext>();
188
189 // Init all logs
190 sLog->RegisterAppender<AppenderDB>();
191 // If logs are supposed to be handled async then we need to pass the IoContext into the Log singleton
192 sLog->Initialize(sConfigMgr->GetOption<bool>("Log.Async.Enable", false) ? ioContext.get() : nullptr);
193
194 Acore::Banner::Show("worldserver-daemon",
195 [](std::string_view text)
196 {
197 LOG_INFO("server.worldserver", text);
198 },
199 []()
200 {
201 LOG_INFO("server.worldserver", "> Using configuration file {}", sConfigMgr->GetFilename());
202 LOG_INFO("server.worldserver", "> Using SSL version: {} (library: {})", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION));
203 LOG_INFO("server.worldserver", "> Using Boost version: {}.{}.{}", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100);
204 });
205
207
208 std::shared_ptr<void> opensslHandle(nullptr, [](void*) { OpenSSLCrypto::threadsCleanup(); });
209
210 // Seed the OpenSSL's PRNG here.
211 // That way it won't auto-seed when calling BigNumber::SetRand and slow down the first world login
212 BigNumber seed;
213 seed.SetRand(16 * 8);
214
216 std::string pidFile = sConfigMgr->GetOption<std::string>("PidFile", "");
217 if (!pidFile.empty())
218 {
219 if (uint32 pid = CreatePIDFile(pidFile))
220 LOG_ERROR("server", "Daemon PID: {}\n", pid); // outError for red color in console
221 else
222 {
223 LOG_ERROR("server", "Cannot create PID file {} (possible error: permission)\n", pidFile);
224 return 1;
225 }
226 }
227
228 // Set signal handlers (this must be done before starting IoContext threads, because otherwise they would unblock and exit)
229 boost::asio::signal_set signals(*ioContext, SIGINT, SIGTERM);
230#if AC_PLATFORM == AC_PLATFORM_WINDOWS
231 signals.add(SIGBREAK);
232#endif
233 signals.async_wait(SignalHandler);
234
235 // Start the Boost based thread pool
236 int numThreads = sConfigMgr->GetOption<int32>("ThreadPool", 2);
237 std::shared_ptr<std::vector<std::thread>> threadPool(new std::vector<std::thread>(), [ioContext](std::vector<std::thread>* del)
238 {
239 ioContext->stop();
240 for (std::thread& thr : *del)
241 thr.join();
242
243 delete del;
244 });
245
246 if (numThreads < 1)
247 {
248 numThreads = 1;
249 }
250
251 for (int i = 0; i < numThreads; ++i)
252 {
253 threadPool->push_back(std::thread([ioContext]()
254 {
255 ioContext->run();
256 }));
257 }
258
259 // Set process priority according to configuration settings
260 SetProcessPriority("server.worldserver", sConfigMgr->GetOption<int32>(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetOption<bool>(CONFIG_HIGH_PRIORITY, true));
261
262 // Loading modules configs before scripts
263 sConfigMgr->LoadModulesConfigs();
264
265 sScriptMgr->SetScriptLoader(AddScripts);
266 sScriptMgr->SetModulesLoader(AddModulesScripts);
267
268 std::shared_ptr<void> sScriptMgrHandle(nullptr, [](void*)
269 {
270 sScriptMgr->Unload();
271 //sScriptReloadMgr->Unload();
272 });
273
274 LOG_INFO("server.loading", "Initializing Scripts...");
275 sScriptMgr->Initialize();
276
277 // Start the databases
278 if (!StartDB())
279 return 1;
280
281 std::shared_ptr<void> dbHandle(nullptr, [](void*) { StopDB(); });
282
283 // set server offline (not connectable)
284 LoginDatabase.DirectExecute("UPDATE realmlist SET flag = (flag & ~{}) | {} WHERE id = '{}'", REALM_FLAG_OFFLINE, REALM_FLAG_VERSION_MISMATCH, realm.Id.Realm);
285
286 LoadRealmInfo(*ioContext);
287
288 sMetric->Initialize(realm.Name, *ioContext, []()
289 {
290 METRIC_VALUE("online_players", sWorldSessionMgr->GetPlayerCount());
291 METRIC_VALUE("db_queue_login", uint64(LoginDatabase.QueueSize()));
292 METRIC_VALUE("db_queue_character", uint64(CharacterDatabase.QueueSize()));
293 METRIC_VALUE("db_queue_world", uint64(WorldDatabase.QueueSize()));
294 });
295
296 METRIC_EVENT("events", "Worldserver started", "");
297
298 std::shared_ptr<void> sMetricHandle(nullptr, [](void*)
299 {
300 METRIC_EVENT("events", "Worldserver shutdown", "");
301 sMetric->Unload();
302 });
303
305
307 sSecretMgr->Initialize();
308 sWorld->SetInitialWorldSettings();
309
310 std::shared_ptr<void> mapManagementHandle(nullptr, [](void*)
311 {
312 // unload battleground templates before different singletons destroyed
313 sBattlegroundMgr->DeleteAllBattlegrounds();
314
315 sOutdoorPvPMgr->Die(); // unload it before MapMgr
316 sMapMgr->UnloadAll(); // unload all grids (including locked in memory)
317
318 sScriptMgr->OnAfterUnloadAllMaps();
319 });
320
321 // Start the Remote Access port (acceptor) if enabled
322 std::unique_ptr<AsyncAcceptor> raAcceptor;
323 if (sConfigMgr->GetOption<bool>("Ra.Enable", false))
324 {
325 raAcceptor.reset(StartRaSocketAcceptor(*ioContext));
326 }
327
328 // Start soap serving thread if enabled
329 std::shared_ptr<std::thread> soapThread;
330 if (sConfigMgr->GetOption<bool>("SOAP.Enabled", false))
331 {
332 soapThread.reset(new std::thread(ACSoapThread, sConfigMgr->GetOption<std::string>("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetOption<int32>("SOAP.Port", 7878))),
333 [](std::thread* thr)
334 {
335 thr->join();
336 delete thr;
337 });
338 }
339
340 // Launch the worldserver listener socket
341 uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD));
342 std::string worldListener = sConfigMgr->GetOption<std::string>("BindIP", "0.0.0.0");
343
344 int networkThreads = sConfigMgr->GetOption<int32>("Network.Threads", 1);
345
346 if (networkThreads <= 0)
347 {
348 LOG_ERROR("server.worldserver", "Network.Threads must be greater than 0");
350 return 1;
351 }
352
353 if (!sWorldSocketMgr.StartWorldNetwork(*ioContext, worldListener, worldPort, networkThreads))
354 {
355 LOG_ERROR("server.worldserver", "Failed to initialize network");
357 return 1;
358 }
359
360 std::shared_ptr<void> sWorldSocketMgrHandle(nullptr, [](void*)
361 {
362 sWorldSessionMgr->KickAll(); // save and kick all players
363 sWorldSessionMgr->UpdateSessions(1); // real players unload required UpdateSessions call
364
365 sWorldSocketMgr.StopNetwork();
366
369 });
370
371 // Set server online (allow connecting now)
372 LoginDatabase.DirectExecute("UPDATE realmlist SET flag = flag & ~{}, population = 0 WHERE id = '{}'", REALM_FLAG_VERSION_MISMATCH, realm.Id.Realm);
373 realm.PopulationLevel = 0.0f;
375
376 // Start the freeze check callback cycle in 5 seconds (cycle itself is 1 sec)
377 std::shared_ptr<FreezeDetector> freezeDetector;
378 if (int32 coreStuckTime = sConfigMgr->GetOption<int32>("MaxCoreStuckTime", 60))
379 {
380 freezeDetector = std::make_shared<FreezeDetector>(*ioContext, coreStuckTime * 1000);
381 FreezeDetector::Start(freezeDetector);
382 LOG_INFO("server.worldserver", "Starting up anti-freeze thread ({} seconds max stuck time)...", coreStuckTime);
383 }
384
385 LOG_INFO("server.worldserver", "{} (worldserver-daemon) ready...", GitRevision::GetFullVersion());
386
387 sScriptMgr->OnStartup();
388
389 // Launch CliRunnable thread
390 std::shared_ptr<std::thread> cliThread;
391#if AC_PLATFORM == AC_PLATFORM_WINDOWS
392 if (sConfigMgr->GetOption<bool>("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
393#else
394 if (sConfigMgr->GetOption<bool>("Console.Enable", true))
395#endif
396 {
397 cliThread.reset(new std::thread(CliThread), &ShutdownCLIThread);
398 }
399
401
402 // Shutdown starts here
403 threadPool.reset();
404
405 sLog->SetSynchronous();
406
407 sScriptMgr->OnShutdown();
408
409 // set server offline
410 if (!sConfigMgr->GetOption<bool>("Network.UseSocketActivation", false))
411 LoginDatabase.DirectExecute("UPDATE realmlist SET flag = flag | {} WHERE id = '{}'", REALM_FLAG_OFFLINE, realm.Id.Realm);
412
413 LOG_INFO("server.worldserver", "Halting process...");
414
415 // 0 - normal shutdown
416 // 1 - shutdown at error
417 // 2 - restart command used, this code can be used by restarter for restart AzerothCore
418
419 return World::GetExitCode();
420}
void ACSoapThread(const std::string &host, uint16 port)
Definition ACSoap.cpp:24
#define sBattlegroundMgr
Definition BattlegroundMgr.h:187
std::int32_t int32
Definition Define.h:103
#define LOG_INFO(filterType__,...)
Definition Log.h:166
#define sLog
Definition Log.h:127
#define sMapMgr
Definition MapMgr.h:220
#define sMetric
Definition Metric.h:134
#define METRIC_EVENT(category, title, description)
Definition Metric.h:189
#define sOutdoorPvPMgr
Definition OutdoorPvPMgr.h:102
void SetProcessPriority(std::string const &logChannel, uint32 affinity, bool highPriority)
Definition ProcessPriority.cpp:29
#define CONFIG_HIGH_PRIORITY
Definition ProcessPriority.h:25
#define CONFIG_PROCESSOR_AFFINITY
Definition ProcessPriority.h:24
@ REALM_FLAG_OFFLINE
Definition Realm.h:29
@ REALM_FLAG_VERSION_MISMATCH
Definition Realm.h:28
void AddScripts()
Definition WorldMock.h:29
#define sScriptMgr
Definition ScriptMgr.h:719
#define sSecretMgr
Definition SecretMgr.h:72
@ SERVER_PROCESS_WORLDSERVER
Definition SharedDefines.h:4005
uint32 CreatePIDFile(std::string const &filename)
create PID file
Definition Util.cpp:218
@ CONFIG_PORT_WORLD
Definition WorldConfig.h:169
#define sWorldSessionMgr
Definition WorldSessionMgr.h:108
Definition AppenderDB.h:25
Definition BigNumber.h:29
void SetRand(int32 numbits)
Definition BigNumber.cpp:71
static uint8 GetExitCode()
Definition World.h:187
AsyncAcceptor * StartRaSocketAcceptor(Acore::Asio::IoContext &ioContext)
Definition Main.cpp:643
bool StartDB()
Initialize connection to the databases.
Definition Main.cpp:423
void ClearOnlineAccounts()
Clear 'online' status for all accounts with characters in this realm.
Definition Main.cpp:486
void CliThread()
Thread start
Definition CliRunnable.cpp:108
void WorldUpdateLoop()
Definition Main.cpp:557
static void Start(std::shared_ptr< FreezeDetector > const &freezeDetector)
Definition Main.cpp:94
bool LoadRealmInfo(Acore::Asio::IoContext &ioContext)
Definition Main.cpp:660
void StopDB()
Definition Main.cpp:476
void ShutdownCLIThread(std::thread *cliThread)
Definition Main.cpp:496
variables_map GetConsoleArguments(int argc, char **argv, fs::path &configFile, std::string &cfg_service)
Definition Main.cpp:708
int m_ServiceStatus
Definition Main.cpp:75
void SignalHandler(boost::system::error_code const &error, int signalNumber)
Definition Main.cpp:606
#define sWorldSocketMgr
Definition WorldSocketMgr.h:64
@ ERROR_EXIT_CODE
Definition World.h:54
AC_COMMON_API void Show(std::string_view applicationName, void(*log)(std::string_view text), void(*logExtraInfo)())
Definition Banner.cpp:22
AC_COMMON_API void SetEnableModulesList(std::string_view modulesList)
Definition ModuleMgr.cpp:26
AC_COMMON_API void AbortHandler(int sigval)
Definition Errors.cpp:148
AC_COMMON_API void threadsSetup()
Needs to be called before threads using openssl are spawned.
Definition OpenSSLCrypto.cpp:41
AC_COMMON_API void threadsCleanup()
Needs to be called after threads using openssl are despawned.
Definition OpenSSLCrypto.cpp:50
static ServerProcessTypes _type
Definition SharedDefines.h:4029

References _ACORE_CORE_CONFIG, Acore::Impl::CurrentServerProcessHolder::_type, Acore::AbortHandler(), ACSoapThread(), AddScripts(), ClearOnlineAccounts(), CliThread(), CONFIG_HIGH_PRIORITY, CONFIG_PORT_WORLD, CONFIG_PROCESSOR_AFFINITY, CreatePIDFile(), ERROR_EXIT_CODE, Realm::Flags, GetConsoleArguments(), World::GetExitCode(), GitRevision::GetFullVersion(), Realm::Id, LoadRealmInfo(), LOG_ERROR, LOG_INFO, LoginDatabase, m_ServiceStatus, METRIC_EVENT, Realm::Name, Realm::PopulationLevel, realm, RealmHandle::Realm, REALM_FLAG_OFFLINE, REALM_FLAG_VERSION_MISMATCH, sBattlegroundMgr, sConfigMgr, SERVER_PROCESS_WORLDSERVER, Acore::Module::SetEnableModulesList(), SetProcessPriority(), BigNumber::SetRand(), Acore::Banner::Show(), ShutdownCLIThread(), SignalHandler(), sLog, sMapMgr, sMetric, sOutdoorPvPMgr, sScriptMgr, sSecretMgr, FreezeDetector::Start(), StartDB(), StartRaSocketAcceptor(), StopDB(), World::StopNow(), sWorld, sWorldSessionMgr, sWorldSocketMgr, OpenSSLCrypto::threadsCleanup(), OpenSSLCrypto::threadsSetup(), and WorldUpdateLoop().

◆ PrintCliPrefix()

static void PrintCliPrefix ( )
inlinestatic

◆ ShutdownCLIThread()

void ShutdownCLIThread ( std::thread *  cliThread)

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

497{
498 if (cliThread)
499 {
500#ifdef _WIN32
501 // First try to cancel any I/O in the CLI thread
502 if (!CancelSynchronousIo(cliThread->native_handle()))
503 {
504 // if CancelSynchronousIo() fails, print the error and try with old way
505 DWORD errorCode = GetLastError();
506 LPCSTR errorBuffer;
507
508 DWORD formatReturnCode = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
509 nullptr, errorCode, 0, (LPTSTR)&errorBuffer, 0, nullptr);
510 if (!formatReturnCode)
511 errorBuffer = "Unknown error";
512
513 LOG_DEBUG("server.worldserver", "Error cancelling I/O of CliThread, error code {}, detail: {}", uint32(errorCode), errorBuffer);
514
515 if (!formatReturnCode)
516 LocalFree((LPSTR)errorBuffer);
517
518 // send keyboard input to safely unblock the CLI thread
519 INPUT_RECORD b[4];
520 HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
521 b[0].EventType = KEY_EVENT;
522 b[0].Event.KeyEvent.bKeyDown = TRUE;
523 b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
524 b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
525 b[0].Event.KeyEvent.wRepeatCount = 1;
526
527 b[1].EventType = KEY_EVENT;
528 b[1].Event.KeyEvent.bKeyDown = FALSE;
529 b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
530 b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
531 b[1].Event.KeyEvent.wRepeatCount = 1;
532
533 b[2].EventType = KEY_EVENT;
534 b[2].Event.KeyEvent.bKeyDown = TRUE;
535 b[2].Event.KeyEvent.dwControlKeyState = 0;
536 b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
537 b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
538 b[2].Event.KeyEvent.wRepeatCount = 1;
539 b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;
540
541 b[3].EventType = KEY_EVENT;
542 b[3].Event.KeyEvent.bKeyDown = FALSE;
543 b[3].Event.KeyEvent.dwControlKeyState = 0;
544 b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
545 b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
546 b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
547 b[3].Event.KeyEvent.wRepeatCount = 1;
548 DWORD numb;
549 WriteConsoleInput(hStdIn, b, 4, &numb);
550 }
551#endif
552 cliThread->join();
553 delete cliThread;
554 }
555}
#define LOG_DEBUG(filterType__,...)
Definition Log.h:170

References LOG_DEBUG.

Referenced by main().

◆ SignalHandler()

void SignalHandler ( boost::system::error_code const &  error,
int  signalNumber 
)

◆ Start()

static void FreezeDetector::Start ( std::shared_ptr< FreezeDetector > const &  freezeDetector)
inlinestatic

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

95 {
96 freezeDetector->_timer.expires_at(Acore::Asio::SteadyTimer::GetExpirationTime(5));
97 freezeDetector->_timer.async_wait(std::bind(&FreezeDetector::Handler, std::weak_ptr<FreezeDetector>(freezeDetector), std::placeholders::_1));
98 }

References Acore::Asio::SteadyTimer::GetExpirationTime(), and FreezeDetector::Handler().

Referenced by main().

◆ StartDB()

bool StartDB ( )

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

Initialize connection to the databases.

  • Get the realm Id from the configuration file
  • Clean the database before starting
  • Insert version info into DB
424{
426
427 // Load databases
428 DatabaseLoader loader("server.worldserver", DatabaseLoader::DATABASE_MASK_ALL, AC_MODULES_LIST);
429 loader
430 .AddDatabase(LoginDatabase, "Login")
431 .AddDatabase(CharacterDatabase, "Character")
432 .AddDatabase(WorldDatabase, "World");
433
434 if (!loader.Load())
435 return false;
436
438 realm.Id.Realm = sConfigMgr->GetOption<uint32>("RealmID", 1);
439 if (!realm.Id.Realm)
440 {
441 LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file");
442 return false;
443 }
444 else if (realm.Id.Realm > 255)
445 {
446 /*
447 * Due to the client only being able to read a realm.Id.Realm
448 * with a size of uint8 we can "only" store up to 255 realms
449 * anything further the client will behave anormaly
450 */
451 LOG_ERROR("server.worldserver", "Realm ID must range from 1 to 255");
452 return false;
453 }
454
455 LOG_INFO("server.loading", "Loading World Information...");
456 LOG_INFO("server.loading", "> RealmID: {}", realm.Id.Realm);
457
460
464 stmt->SetData(1, GitRevision::GetHash());
465 WorldDatabase.Execute(stmt);
466
467 sWorld->LoadDBVersion();
468
469 LOG_INFO("server.loading", "> Version DB world: {}", sWorld->GetDBVersion());
470
471 sScriptMgr->OnAfterDatabasesLoaded(loader.GetUpdateFlags());
472
473 return true;
474}
DatabaseWorkerPool< WorldDatabaseConnection > WorldDatabase
Accessor to the world database.
Definition DatabaseEnv.cpp:20
@ WORLD_UPD_VERSION
Definition WorldDatabase.h:119
Definition DatabaseLoader.h:33
@ DATABASE_MASK_ALL
Definition DatabaseLoader.h:52
Acore::Types::is_default< T > SetData(const uint8 index, T value)
Definition PreparedStatement.h:77
Definition PreparedStatement.h:157
AC_COMMON_API char const * GetHash()
Definition GitRevision.cpp:21
AC_DATABASE_API void Library_Init()
Definition MySQLThreading.cpp:21

References DatabaseLoader::AddDatabase(), CharacterDatabase, ClearOnlineAccounts(), DatabaseLoader::DATABASE_MASK_ALL, GitRevision::GetFullVersion(), GitRevision::GetHash(), DatabaseLoader::GetUpdateFlags(), Realm::Id, MySQL::Library_Init(), DatabaseLoader::Load(), LOG_ERROR, LOG_INFO, LoginDatabase, realm, RealmHandle::Realm, sConfigMgr, PreparedStatementBase::SetData(), sScriptMgr, sWorld, WORLD_UPD_VERSION, and WorldDatabase.

Referenced by main().

◆ StartRaSocketAcceptor()

AsyncAcceptor * StartRaSocketAcceptor ( Acore::Asio::IoContext ioContext)

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

644{
645 uint16 raPort = uint16(sConfigMgr->GetOption<int32>("Ra.Port", 3443));
646 std::string raListener = sConfigMgr->GetOption<std::string>("Ra.IP", "0.0.0.0");
647
648 AsyncAcceptor* acceptor = new AsyncAcceptor(ioContext, raListener, raPort);
649 if (!acceptor->Bind())
650 {
651 LOG_ERROR("server.worldserver", "Failed to bind RA socket acceptor");
652 delete acceptor;
653 return nullptr;
654 }
655
656 acceptor->AsyncAccept<RASession>();
657 return acceptor;
658}
Definition AsyncAcceptor.h:33
Definition RASession.h:30

References LOG_ERROR, and sConfigMgr.

Referenced by main().

◆ StopDB()

void StopDB ( )

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

477{
478 CharacterDatabase.Close();
479 WorldDatabase.Close();
480 LoginDatabase.Close();
481
483}
AC_DATABASE_API void Library_End()
Definition MySQLThreading.cpp:26

References CharacterDatabase, MySQL::Library_End(), LoginDatabase, and WorldDatabase.

Referenced by main().

◆ utf8print()

void utf8print ( void *  ,
std::string_view  str 
)

#include <azerothcore-wotlk/src/server/apps/worldserver/CommandLine/CliRunnable.cpp>

75{
76#if AC_PLATFORM == AC_PLATFORM_WINDOWS
77 fmt::print(str);
78#else
79{
80 fmt::print(str);
81 fflush(stdout);
82}
83#endif
84}

Referenced by CliThread().

◆ WorldUpdateLoop()

void WorldUpdateLoop ( )

#include <azerothcore-wotlk/src/server/apps/worldserver/Main.cpp>

  • While we have not World::m_stopEvent, update the world
558{
559 uint32 minUpdateDiff = uint32(sConfigMgr->GetOption<int32>("MinWorldUpdateTime", 1));
560 uint32 realCurrTime = 0;
561 uint32 realPrevTime = getMSTime();
562
563 uint32 maxCoreStuckTime = uint32(sConfigMgr->GetOption<int32>("MaxCoreStuckTime", 60)) * 1000;
564 uint32 halfMaxCoreStuckTime = maxCoreStuckTime / 2;
565 if (!halfMaxCoreStuckTime)
566 halfMaxCoreStuckTime = std::numeric_limits<uint32>::max();
567
568 LoginDatabase.WarnAboutSyncQueries(true);
569 CharacterDatabase.WarnAboutSyncQueries(true);
570 WorldDatabase.WarnAboutSyncQueries(true);
571
573 while (!World::IsStopped())
574 {
576 realCurrTime = getMSTime();
577
578 uint32 diff = getMSTimeDiff(realPrevTime, realCurrTime);
579 if (diff < minUpdateDiff)
580 {
581 uint32 sleepTime = minUpdateDiff - diff;
582 if (sleepTime >= halfMaxCoreStuckTime)
583 LOG_ERROR("server.worldserver", "WorldUpdateLoop() waiting for {} ms with MaxCoreStuckTime set to {} ms", sleepTime, maxCoreStuckTime);
584 // sleep until enough time passes that we can update all timers
585 std::this_thread::sleep_for(Milliseconds(sleepTime));
586 continue;
587 }
588
589 sWorld->Update(diff);
590 realPrevTime = realCurrTime;
591
592#ifdef _WIN32
593 if (m_ServiceStatus == 0)
595
596 while (m_ServiceStatus == 2)
597 Sleep(1000);
598#endif
599 }
600
601 LoginDatabase.WarnAboutSyncQueries(false);
602 CharacterDatabase.WarnAboutSyncQueries(false);
603 WorldDatabase.WarnAboutSyncQueries(false);
604}
std::chrono::milliseconds Milliseconds
Milliseconds shorthand typedef.
Definition Duration.h:27

References CharacterDatabase, getMSTime(), getMSTimeDiff(), World::IsStopped(), LOG_ERROR, LoginDatabase, m_ServiceStatus, World::m_worldLoopCounter, sConfigMgr, SHUTDOWN_EXIT_CODE, World::StopNow(), sWorld, and WorldDatabase.

Referenced by main().

Variable Documentation

◆ _lastChangeMsTime

uint32 FreezeDetector::_lastChangeMsTime
private

◆ _maxCoreStuckTimeInMs

uint32 FreezeDetector::_maxCoreStuckTimeInMs
private

◆ _timer

boost::asio::steady_timer FreezeDetector::_timer
private

◆ _worldLoopCounter

uint32 FreezeDetector::_worldLoopCounter
private

◆ CLI_PREFIX

constexpr char CLI_PREFIX[] = "AC> "
staticconstexpr

◆ m_ServiceStatus

int m_ServiceStatus = -1

◆ serviceDescription

char serviceDescription[] = "AzerothCore World of Warcraft emulator world service"

◆ serviceLongName

char serviceLongName[] = "AzerothCore world service"

◆ serviceName

char serviceName[] = "worldserver"