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.

497{
498 // Reset online status for all accounts with characters on the current realm
499 // pussywizard: tc query would set online=0 even if logged in on another realm >_>
500 LoginDatabase.DirectExecute("UPDATE account SET online = 0 WHERE online = {}", realm.Id.Realm);
501
502 // Reset online status for all characters
503 CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0");
504}
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:115
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
112{
113#if AC_PLATFORM == AC_PLATFORM_WINDOWS
114 // Set console code pages to UTF-8
115 SetConsoleCP(CP_UTF8);
116 SetConsoleOutputCP(CP_UTF8);
117
118 // print this here the first time
119 // later it will be printed after command queue updates
121#else
122 ::rl_attempted_completion_function = &Acore::Impl::Readline::cli_completion;
123 {
124 static char BLANK = '\0';
125 ::rl_completer_word_break_characters = &BLANK;
126 }
127 ::rl_event_hook = &Acore::Impl::Readline::cli_hook_func;
128#endif
129
130 if (sConfigMgr->GetOption<bool>("BeepAtStart", true))
131 printf("\a"); // \a = Alert
132
133#if AC_PLATFORM == AC_PLATFORM_WINDOWS
134 if (sConfigMgr->GetOption<bool>("FlashAtStart", true))
135 {
136 FLASHWINFO fInfo;
137 fInfo.cbSize = sizeof(FLASHWINFO);
138 fInfo.dwFlags = FLASHW_TRAY | FLASHW_TIMERNOFG;
139 fInfo.hwnd = GetConsoleWindow();
140 fInfo.uCount = 0;
141 fInfo.dwTimeout = 0;
142 FlashWindowEx(&fInfo);
143 }
144
145 // Get console input handle once for reading commands
146 HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
147 if (hStdIn == INVALID_HANDLE_VALUE)
148 {
149 LOG_ERROR("server.worldserver", "Failed to get console input handle");
150 return;
151 }
152#endif
153
155 while (!World::IsStopped())
156 {
157 fflush(stdout);
158
159 std::string command;
160
161#if AC_PLATFORM == AC_PLATFORM_WINDOWS
162
163 static bool checkedConsole = false;
164 static bool isRealConsole = false;
165
166 if (!checkedConsole)
167 {
168 DWORD mode = 0;
169 isRealConsole = GetConsoleMode(hStdIn, &mode);
170 checkedConsole = true;
171 }
172
173 if (isRealConsole)
174 {
175 // ===== Real Windows Console =====
176 wchar_t commandbuf[256];
177 DWORD charsRead = 0;
178
179 if (ReadConsoleW(hStdIn, commandbuf,
180 sizeof(commandbuf) / sizeof(wchar_t) - 1,
181 &charsRead, nullptr))
182 {
183 if (charsRead > 0)
184 {
185 commandbuf[charsRead] = L'\0';
186 if (!WStrToUtf8(commandbuf, charsRead, command))
187 {
189 continue;
190 }
191 }
192 }
193 }
194 else
195 {
196 // ===== Redirected input (pipe) =====
197 if (!std::getline(std::cin, command))
198 {
200 break;
201 }
202 }
203
204#else
205 char* command_str = readline(CLI_PREFIX);
206 ::rl_bind_key('\t', ::rl_complete);
207 if (command_str != nullptr)
208 {
209 command = command_str;
210 free(command_str);
211 }
212#endif
213
214 if (!command.empty())
215 {
216 std::size_t nextLineIndex = command.find_first_of("\r\n");
217 if (nextLineIndex != std::string::npos)
218 {
219 if (nextLineIndex == 0)
220 {
221#if AC_PLATFORM == AC_PLATFORM_WINDOWS
223#endif
224 continue;
225 }
226
227 command.erase(nextLineIndex);
228 }
229
230 fflush(stdout);
231 sWorld->QueueCliCommand(new CliCommandHolder(nullptr, command.c_str(), &utf8print, &commandFinished));
232#if AC_PLATFORM != AC_PLATFORM_WINDOWS
233 add_history(command.c_str());
234#endif
235 }
236 else if (feof(stdin))
237 {
239 }
240 }
241}
#define LOG_ERROR(filterType__,...)
Definition Log.h:145
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:41
static constexpr char CLI_PREFIX[]
Definition CliRunnable.cpp:39
void utf8print(void *, std::string_view str)
Definition CliRunnable.cpp:77
void commandFinished(void *, bool)
Definition CliRunnable.cpp:89
#define sWorld
Definition World.h:318
@ 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(), LOG_ERROR, 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>

90{
92 fflush(stdout);
93}

References PrintCliPrefix().

Referenced by CliThread().

◆ FreezeDetector()

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

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

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

◆ GetConsoleArguments()

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

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

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

623{
624 if (!error)
625 {
626 if (std::shared_ptr<FreezeDetector> freezeDetector = freezeDetectorRef.lock())
627 {
628 uint32 curtime = getMSTime();
629
630 uint32 worldLoopCounter = World::m_worldLoopCounter;
631 if (freezeDetector->_worldLoopCounter != worldLoopCounter)
632 {
633 freezeDetector->_lastChangeMsTime = curtime;
634 freezeDetector->_worldLoopCounter = worldLoopCounter;
635 }
636 // possible freeze
637 else
638 {
639 uint32 msTimeDiff = getMSTimeDiff(freezeDetector->_lastChangeMsTime, curtime);
640 if (msTimeDiff > freezeDetector->_maxCoreStuckTimeInMs)
641 {
642 LOG_ERROR("server.worldserver", "World Thread hangs for {} ms, forcing a crash!", msTimeDiff);
643 ABORT("World Thread hangs for {} ms, forcing a crash!", msTimeDiff);
644 }
645 }
646
647 freezeDetector->_timer.expires_at(Acore::Asio::SteadyTimer::GetExpirationTime(1));
648 freezeDetector->_timer.async_wait(std::bind(&FreezeDetector::Handler, freezeDetectorRef, std::placeholders::_1));
649 }
650 }
651}
std::uint32_t uint32
Definition Define.h:107
#define ABORT
Definition Errors.h:76
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:622
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>

671{
672 QueryResult result = LoginDatabase.Query("SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE id = {}", realm.Id.Realm);
673 if (!result)
674 return false;
675
676 Acore::Asio::Resolver resolver(ioContext);
677
678 Field* fields = result->Fetch();
679 realm.Name = fields[1].Get<std::string>();
680
681 Optional<boost::asio::ip::tcp::endpoint> externalAddress = resolver.Resolve(boost::asio::ip::tcp::v4(), fields[2].Get<std::string>(), "");
682 if (!externalAddress)
683 {
684 LOG_ERROR("server.worldserver", "Could not resolve address {}", fields[2].Get<std::string>());
685 return false;
686 }
687
688 realm.ExternalAddress = std::make_unique<boost::asio::ip::address>(externalAddress->address());
689
690 Optional<boost::asio::ip::tcp::endpoint> localAddress = resolver.Resolve(boost::asio::ip::tcp::v4(), fields[3].Get<std::string>(), "");
691 if (!localAddress)
692 {
693 LOG_ERROR("server.worldserver", "Could not resolve address {}", fields[3].Get<std::string>());
694 return false;
695 }
696
697 realm.LocalAddress = std::make_unique<boost::asio::ip::address>(localAddress->address());
698
699 Optional<boost::asio::ip::tcp::endpoint> localSubmask = resolver.Resolve(boost::asio::ip::tcp::v4(), fields[4].Get<std::string>(), "");
700 if (!localSubmask)
701 {
702 LOG_ERROR("server.worldserver", "Could not resolve address {}", fields[4].Get<std::string>());
703 return false;
704 }
705
706 realm.LocalSubnetMask = std::make_unique<boost::asio::ip::address>(localSubmask->address());
707
708 realm.Port = fields[5].Get<uint16>();
709 realm.Type = fields[6].Get<uint8>();
710 realm.Flags = RealmFlags(fields[7].Get<uint8>());
711 realm.Timezone = fields[8].Get<uint8>();
712 realm.AllowedSecurityLevel = AccountTypes(fields[9].Get<uint8>());
713 realm.PopulationLevel = fields[10].Get<float>();
714 realm.Build = fields[11].Get<uint32>();
715 return true;
716}
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
123{
125 signal(SIGABRT, &Acore::AbortHandler);
126
127 // Command line parsing
128 auto configFile = fs::path(sConfigMgr->GetConfigPath() + std::string(_ACORE_CORE_CONFIG));
129 std::string configService;
130 auto vm = GetConsoleArguments(argc, argv, configFile, configService);
131
132 // exit if help or version is enabled
133 if (vm.count("help") || vm.count("version"))
134 return 0;
135
136#if AC_PLATFORM == AC_PLATFORM_WINDOWS
137 if (configService.compare("install") == 0)
138 return WinServiceInstall() == true ? 0 : 1;
139 else if (configService.compare("uninstall") == 0)
140 return WinServiceUninstall() == true ? 0 : 1;
141 else if (configService.compare("run") == 0)
142 WinServiceRun();
143
144 Optional<UINT> newTimerResolution;
145 boost::system::error_code dllError;
146 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)
147 {
148 try
149 {
150 if (newTimerResolution)
151 lib->get<decltype(timeEndPeriod)>("timeEndPeriod")(*newTimerResolution);
152 }
153 catch (std::exception const&)
154 {
155 // ignore
156 }
157
158 delete lib;
159 });
160
161 if (winmm->is_loaded())
162 {
163 try
164 {
165 auto timeGetDevCapsPtr = winmm->get<decltype(timeGetDevCaps)>("timeGetDevCaps");
166 // setup timer resolution
167 TIMECAPS timeResolutionLimits;
168 if (timeGetDevCapsPtr(&timeResolutionLimits, sizeof(TIMECAPS)) == TIMERR_NOERROR)
169 {
170 auto timeBeginPeriodPtr = winmm->get<decltype(timeBeginPeriod)>("timeBeginPeriod");
171 newTimerResolution = std::min(std::max(timeResolutionLimits.wPeriodMin, 1u), timeResolutionLimits.wPeriodMax);
172 timeBeginPeriodPtr(*newTimerResolution);
173 }
174 }
175 catch (std::exception const& e)
176 {
177 printf("Failed to initialize timer resolution: %s\n", e.what());
178 }
179 }
180
181#endif
182
183 // Add file and args in config
184 sConfigMgr->Configure(configFile.generic_string(), {argv, argv + argc}, CONFIG_FILE_LIST);
185
186 if (!sConfigMgr->LoadAppConfigs())
187 return 1;
188
189 std::shared_ptr<Acore::Asio::IoContext> ioContext = std::make_shared<Acore::Asio::IoContext>();
190
191 // Init all logs
192 sLog->RegisterAppender<AppenderDB>();
193 // If logs are supposed to be handled async then we need to pass the IoContext into the Log singleton
194 sLog->Initialize(sConfigMgr->GetOption<bool>("Log.Async.Enable", false) ? ioContext.get() : nullptr);
195
196 Acore::Banner::Show("worldserver-daemon",
197 [](std::string_view text)
198 {
199 LOG_INFO("server.worldserver", text);
200 },
201 []()
202 {
203 LOG_INFO("server.worldserver", "> Using configuration file {}", sConfigMgr->GetFilename());
204 LOG_INFO("server.worldserver", "> Using SSL version: {} (library: {})", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION));
205 LOG_INFO("server.worldserver", "> Using Boost version: {}.{}.{}", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100);
206 });
207
209
210 std::shared_ptr<void> opensslHandle(nullptr, [](void*) { OpenSSLCrypto::threadsCleanup(); });
211
212 // Seed the OpenSSL's PRNG here.
213 // That way it won't auto-seed when calling BigNumber::SetRand and slow down the first world login
214 BigNumber seed;
215 seed.SetRand(16 * 8);
216
218 std::string pidFile = sConfigMgr->GetOption<std::string>("PidFile", "");
219 if (!pidFile.empty())
220 {
221 if (uint32 pid = CreatePIDFile(pidFile))
222 LOG_ERROR("server", "Daemon PID: {}\n", pid); // outError for red color in console
223 else
224 {
225 LOG_ERROR("server", "Cannot create PID file {} (possible error: permission)\n", pidFile);
226 return 1;
227 }
228 }
229
230 // Set signal handlers (this must be done before starting IoContext threads, because otherwise they would unblock and exit)
231 boost::asio::signal_set signals(*ioContext, SIGINT, SIGTERM);
232#if AC_PLATFORM == AC_PLATFORM_WINDOWS
233 signals.add(SIGBREAK);
234#endif
235 signals.async_wait(SignalHandler);
236
237 // Start the Boost based thread pool
238 int numThreads = sConfigMgr->GetOption<int32>("ThreadPool", 2);
239 std::shared_ptr<std::vector<std::thread>> threadPool(new std::vector<std::thread>(), [ioContext](std::vector<std::thread>* del)
240 {
241 ioContext->stop();
242 for (std::thread& thr : *del)
243 thr.join();
244
245 delete del;
246 });
247
248 if (numThreads < 1)
249 {
250 numThreads = 1;
251 }
252
253 for (int i = 0; i < numThreads; ++i)
254 {
255 threadPool->push_back(std::thread([ioContext]()
256 {
257 ioContext->run();
258 }));
259 }
260
261 // Set process priority according to configuration settings
262 SetProcessPriority("server.worldserver", sConfigMgr->GetOption<int32>(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetOption<bool>(CONFIG_HIGH_PRIORITY, true));
263
264 // Loading modules configs before scripts
265 sConfigMgr->LoadModulesConfigs();
266
267 sScriptMgr->SetScriptLoader(AddScripts);
268 sScriptMgr->SetModulesLoader(AddModulesScripts);
269
270 std::shared_ptr<void> sScriptMgrHandle(nullptr, [](void*)
271 {
272 sScriptMgr->Unload();
273 //sScriptReloadMgr->Unload();
274 });
275
276 LOG_INFO("server.loading", "Initializing Scripts...");
277 sScriptMgr->Initialize();
278
279 // Start the databases
280 if (!StartDB())
281 return 1;
282
283 std::shared_ptr<void> dbHandle(nullptr, [](void*) { StopDB(); });
284
285 // set server offline (not connectable)
286 LoginDatabase.DirectExecute("UPDATE realmlist SET flag = (flag & ~{}) | {} WHERE id = '{}'", REALM_FLAG_OFFLINE, REALM_FLAG_VERSION_MISMATCH, realm.Id.Realm);
287
288 LoadRealmInfo(*ioContext);
289
290 sMetric->Initialize(realm.Name, *ioContext, []()
291 {
292 METRIC_VALUE("online_players", sWorldSessionMgr->GetPlayerCount());
293 METRIC_VALUE("db_queue_login", uint64(LoginDatabase.QueueSize()));
294 METRIC_VALUE("db_queue_character", uint64(CharacterDatabase.QueueSize()));
295 METRIC_VALUE("db_queue_world", uint64(WorldDatabase.QueueSize()));
296 });
297
298 METRIC_EVENT("events", "Worldserver started", "");
299
300 std::shared_ptr<void> sMetricHandle(nullptr, [](void*)
301 {
302 METRIC_EVENT("events", "Worldserver shutdown", "");
303 sMetric->Unload();
304 });
305
307
309 sSecretMgr->Initialize();
310 sWorld->SetInitialWorldSettings();
311
312 std::shared_ptr<void> mapManagementHandle(nullptr, [](void*)
313 {
314 // unload battleground templates before different singletons destroyed
315 sBattlegroundMgr->DeleteAllBattlegrounds();
316
317 sOutdoorPvPMgr->Die(); // unload it before MapMgr
318 sMapMgr->UnloadAll(); // unload all grids (including locked in memory)
319
320 sScriptMgr->OnAfterUnloadAllMaps();
321 });
322
323 // Start the Remote Access port (acceptor) if enabled
324 std::unique_ptr<AsyncAcceptor> raAcceptor;
325 if (sConfigMgr->GetOption<bool>("Ra.Enable", false))
326 {
327 raAcceptor.reset(StartRaSocketAcceptor(*ioContext));
328 }
329
330 // Start soap serving thread if enabled
331 std::shared_ptr<std::thread> soapThread;
332 if (sConfigMgr->GetOption<bool>("SOAP.Enabled", false))
333 {
334 soapThread.reset(new std::thread(ACSoapThread, sConfigMgr->GetOption<std::string>("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetOption<int32>("SOAP.Port", 7878))),
335 [](std::thread* thr)
336 {
337 thr->join();
338 delete thr;
339 });
340 }
341
342 // Launch the worldserver listener socket
343 uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD));
344 std::string worldListener = sConfigMgr->GetOption<std::string>("BindIP", "0.0.0.0");
345
346 int networkThreads = sConfigMgr->GetOption<int32>("Network.Threads", 1);
347
348 if (networkThreads <= 0)
349 {
350 LOG_ERROR("server.worldserver", "Network.Threads must be greater than 0");
352 return 1;
353 }
354
355 if (!sWorldSocketMgr.StartWorldNetwork(*ioContext, worldListener, worldPort, networkThreads))
356 {
357 LOG_ERROR("server.worldserver", "Failed to initialize network");
359 return 1;
360 }
361
362 std::shared_ptr<void> sWorldSocketMgrHandle(nullptr, [](void*)
363 {
364 sWorldSessionMgr->KickAll(); // save and kick all players
365 sWorldSessionMgr->UpdateSessions(1); // real players unload required UpdateSessions call
366
367 sWorldSocketMgr.StopNetwork();
368
370 if (!sToCloud9Sidecar->ClusterModeEnabled())
372 });
373
374 // Set server online (allow connecting now)
375 LoginDatabase.DirectExecute("UPDATE realmlist SET flag = flag & ~{}, population = 0 WHERE id = '{}'", REALM_FLAG_VERSION_MISMATCH, realm.Id.Realm);
376 realm.PopulationLevel = 0.0f;
378
379 // Start the freeze check callback cycle in 5 seconds (cycle itself is 1 sec)
380 std::shared_ptr<FreezeDetector> freezeDetector;
381 if (int32 coreStuckTime = sConfigMgr->GetOption<int32>("MaxCoreStuckTime", 60))
382 {
383 freezeDetector = std::make_shared<FreezeDetector>(*ioContext, coreStuckTime * 1000);
384 FreezeDetector::Start(freezeDetector);
385 LOG_INFO("server.worldserver", "Starting up anti-freeze thread ({} seconds max stuck time)...", coreStuckTime);
386 }
387
388 LOG_INFO("server.worldserver", "{} (worldserver-daemon) ready...", GitRevision::GetFullVersion());
389
390 sScriptMgr->OnStartup();
391
392 // Launch CliRunnable thread
393 std::shared_ptr<std::thread> cliThread;
394#if AC_PLATFORM == AC_PLATFORM_WINDOWS
395 if (sConfigMgr->GetOption<bool>("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
396#else
397 if (sConfigMgr->GetOption<bool>("Console.Enable", true))
398#endif
399 {
400 cliThread.reset(new std::thread(CliThread), &ShutdownCLIThread);
401 }
402
403 sToCloud9Sidecar->Init(worldPort, realm.Id.Realm);
404
406
407 // Shutdown starts here
408 threadPool.reset();
409
410 sToCloud9Sidecar->Deinit();
411
412 sLog->SetSynchronous();
413
414 sScriptMgr->OnShutdown();
415
416 // set server offline
417 if (!sConfigMgr->GetOption<bool>("Network.UseSocketActivation", false))
418 LoginDatabase.DirectExecute("UPDATE realmlist SET flag = flag | {} WHERE id = '{}'", REALM_FLAG_OFFLINE, realm.Id.Realm);
419
420 LOG_INFO("server.worldserver", "Halting process...");
421
422 // 0 - normal shutdown
423 // 1 - shutdown at error
424 // 2 - restart command used, this code can be used by restarter for restart AzerothCore
425
426 return World::GetExitCode();
427}
void ACSoapThread(std::string const &host, uint16 port)
Definition ACSoap.cpp:26
#define sBattlegroundMgr
Definition BattlegroundMgr.h:190
std::int32_t int32
Definition Define.h:103
#define LOG_INFO(filterType__,...)
Definition Log.h:153
#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:743
#define sSecretMgr
Definition SecretMgr.h:72
@ SERVER_PROCESS_WORLDSERVER
Definition SharedDefines.h:3995
#define sToCloud9Sidecar
Definition TC9Sidecar.h:76
uint32 CreatePIDFile(std::string const &filename)
create PID file
Definition Util.cpp:218
@ CONFIG_PORT_WORLD
Definition WorldConfig.h:174
#define sWorldSessionMgr
Definition WorldSessionMgr.h:118
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:653
bool StartDB()
Initialize connection to the databases.
Definition Main.cpp:430
void ClearOnlineAccounts()
Clear 'online' status for all accounts with characters in this realm.
Definition Main.cpp:496
void CliThread()
Thread start
Definition CliRunnable.cpp:111
void WorldUpdateLoop()
Definition Main.cpp:567
static void Start(std::shared_ptr< FreezeDetector > const &freezeDetector)
Definition Main.cpp:96
bool LoadRealmInfo(Acore::Asio::IoContext &ioContext)
Definition Main.cpp:670
void StopDB()
Definition Main.cpp:486
void ShutdownCLIThread(std::thread *cliThread)
Definition Main.cpp:506
variables_map GetConsoleArguments(int argc, char **argv, fs::path &configFile, std::string &cfg_service)
Definition Main.cpp:718
int m_ServiceStatus
Definition Main.cpp:77
void SignalHandler(boost::system::error_code const &error, int signalNumber)
Definition Main.cpp:616
#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:4019

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(), sToCloud9Sidecar, 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>

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

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>

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

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. Cluster.Enabled is read from config here because sToCloud9Sidecar->Init() has not run yet; ClusterModeEnabled() would still be the default false.
  • Insert version info into DB
431{
433
434 // Load databases
435 DatabaseLoader loader("server.worldserver", DatabaseLoader::DATABASE_MASK_ALL, AC_MODULES_LIST);
436 loader
437 .AddDatabase(LoginDatabase, "Login")
438 .AddDatabase(CharacterDatabase, "Character")
439 .AddDatabase(WorldDatabase, "World");
440
441 if (!loader.Load())
442 return false;
443
445 realm.Id.Realm = sConfigMgr->GetOption<uint32>("RealmID", 1);
446 if (!realm.Id.Realm)
447 {
448 LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file");
449 return false;
450 }
451 else if (realm.Id.Realm > 255)
452 {
453 /*
454 * Due to the client only being able to read a realm.Id.Realm
455 * with a size of uint8 we can "only" store up to 255 realms
456 * anything further the client will behave anormaly
457 */
458 LOG_ERROR("server.worldserver", "Realm ID must range from 1 to 255");
459 return false;
460 }
461
462 LOG_INFO("server.loading", "Loading World Information...");
463 LOG_INFO("server.loading", "> RealmID: {}", realm.Id.Realm);
464
468 if (!sConfigMgr->GetOption<bool>("Cluster.Enabled", false))
470
474 stmt->SetData(1, GitRevision::GetHash());
475 WorldDatabase.Execute(stmt);
476
477 sWorld->LoadDBVersion();
478
479 LOG_INFO("server.loading", "> Version DB world: {}", sWorld->GetDBVersion());
480
481 sScriptMgr->OnAfterDatabasesLoaded(loader.GetUpdateFlags());
482
483 return true;
484}
DatabaseWorkerPool< WorldDatabaseConnection > WorldDatabase
Accessor to the world database.
Definition DatabaseEnv.cpp:20
@ WORLD_UPD_VERSION
Definition WorldDatabase.h:120
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>

654{
655 uint16 raPort = uint16(sConfigMgr->GetOption<int32>("Ra.Port", 3443));
656 std::string raListener = sConfigMgr->GetOption<std::string>("Ra.IP", "0.0.0.0");
657
658 AsyncAcceptor* acceptor = new AsyncAcceptor(ioContext, raListener, raPort);
659 if (!acceptor->Bind())
660 {
661 LOG_ERROR("server.worldserver", "Failed to bind RA socket acceptor");
662 delete acceptor;
663 return nullptr;
664 }
665
666 acceptor->AsyncAccept<RASession>();
667 return acceptor;
668}
Definition AsyncAcceptor.h:34
Definition RASession.h:28

References LOG_ERROR, and sConfigMgr.

Referenced by main().

◆ StopDB()

void StopDB ( )

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

487{
488 CharacterDatabase.Close();
489 WorldDatabase.Close();
490 LoginDatabase.Close();
491
493}
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>

78{
79#if AC_PLATFORM == AC_PLATFORM_WINDOWS
80 fmt::print("{}", str);
81#else
82{
83 fmt::print("{}", str);
84 fflush(stdout);
85}
86#endif
87}

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
568{
569 uint32 minUpdateDiff = uint32(sConfigMgr->GetOption<int32>("MinWorldUpdateTime", 1));
570 uint32 realCurrTime = 0;
571 uint32 realPrevTime = getMSTime();
572
573 uint32 maxCoreStuckTime = uint32(sConfigMgr->GetOption<int32>("MaxCoreStuckTime", 60)) * 1000;
574 uint32 halfMaxCoreStuckTime = maxCoreStuckTime / 2;
575 if (!halfMaxCoreStuckTime)
576 halfMaxCoreStuckTime = std::numeric_limits<uint32>::max();
577
578 LoginDatabase.WarnAboutSyncQueries(true);
579 CharacterDatabase.WarnAboutSyncQueries(true);
580 WorldDatabase.WarnAboutSyncQueries(true);
581
583 while (!World::IsStopped())
584 {
586 realCurrTime = getMSTime();
587
588 uint32 diff = getMSTimeDiff(realPrevTime, realCurrTime);
589 if (diff < minUpdateDiff)
590 {
591 uint32 sleepTime = minUpdateDiff - diff;
592 if (sleepTime >= halfMaxCoreStuckTime)
593 LOG_ERROR("server.worldserver", "WorldUpdateLoop() waiting for {} ms with MaxCoreStuckTime set to {} ms", sleepTime, maxCoreStuckTime);
594 // sleep until enough time passes that we can update all timers
595 std::this_thread::sleep_for(Milliseconds(sleepTime));
596 continue;
597 }
598
599 sWorld->Update(diff);
600 realPrevTime = realCurrTime;
601
602#ifdef _WIN32
603 if (m_ServiceStatus == 0)
605
606 while (m_ServiceStatus == 2)
607 Sleep(1000);
608#endif
609 }
610
611 LoginDatabase.WarnAboutSyncQueries(false);
612 CharacterDatabase.WarnAboutSyncQueries(false);
613 WorldDatabase.WarnAboutSyncQueries(false);
614}
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"