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.

485{
486 // Reset online status for all accounts with characters on the current realm
487 // pussywizard: tc query would set online=0 even if logged in on another realm >_>
488 LoginDatabase.DirectExecute("UPDATE account SET online = 0 WHERE online = {}", realm.Id.Realm);
489
490 // Reset online status for all characters
491 CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0");
492}
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}
#define sConfigMgr
Definition Config.h:74
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:195
static bool IsStopped()
Definition World.h:196
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:363
@ SHUTDOWN_EXIT_CODE
Definition World.h:53
Storage class for commands issued for delayed execution.
Definition IWorld.h:34

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>

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

◆ GetConsoleArguments()

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

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

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

References _ACORE_CORE_CONFIG, 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>

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

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

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>

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

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>

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

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
422{
424
425 // Load databases
426 DatabaseLoader loader("server.worldserver", DatabaseLoader::DATABASE_NONE, AC_MODULES_LIST);
427 loader
428 .AddDatabase(LoginDatabase, "Login")
429 .AddDatabase(CharacterDatabase, "Character")
430 .AddDatabase(WorldDatabase, "World");
431
432 if (!loader.Load())
433 return false;
434
436 realm.Id.Realm = sConfigMgr->GetOption<uint32>("RealmID", 0);
437 if (!realm.Id.Realm)
438 {
439 LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file");
440 return false;
441 }
442 else if (realm.Id.Realm > 255)
443 {
444 /*
445 * Due to the client only being able to read a realm.Id.Realm
446 * with a size of uint8 we can "only" store up to 255 realms
447 * anything further the client will behave anormaly
448 */
449 LOG_ERROR("server.worldserver", "Realm ID must range from 1 to 255");
450 return false;
451 }
452
453 LOG_INFO("server.loading", "Loading World Information...");
454 LOG_INFO("server.loading", "> RealmID: {}", realm.Id.Realm);
455
458
462 stmt->SetData(1, GitRevision::GetHash());
463 WorldDatabase.Execute(stmt);
464
465 sWorld->LoadDBVersion();
466
467 LOG_INFO("server.loading", "> Version DB world: {}", sWorld->GetDBVersion());
468
469 sScriptMgr->OnAfterDatabasesLoaded(loader.GetUpdateFlags());
470
471 return true;
472}
DatabaseWorkerPool< WorldDatabaseConnection > WorldDatabase
Accessor to the world database.
Definition DatabaseEnv.cpp:20
@ WORLD_UPD_VERSION
Definition WorldDatabase.h:119
Definition DatabaseLoader.h:33
@ DATABASE_NONE
Definition DatabaseLoader.h:46
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_NONE, 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>

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

References LOG_ERROR, and sConfigMgr.

Referenced by main().

◆ StopDB()

void StopDB ( )

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

475{
476 CharacterDatabase.Close();
477 WorldDatabase.Close();
478 LoginDatabase.Close();
479
481}
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
556{
557 uint32 minUpdateDiff = uint32(sConfigMgr->GetOption<int32>("MinWorldUpdateTime", 1));
558 uint32 realCurrTime = 0;
559 uint32 realPrevTime = getMSTime();
560
561 uint32 maxCoreStuckTime = uint32(sConfigMgr->GetOption<int32>("MaxCoreStuckTime", 60)) * 1000;
562 uint32 halfMaxCoreStuckTime = maxCoreStuckTime / 2;
563 if (!halfMaxCoreStuckTime)
564 halfMaxCoreStuckTime = std::numeric_limits<uint32>::max();
565
566 LoginDatabase.WarnAboutSyncQueries(true);
567 CharacterDatabase.WarnAboutSyncQueries(true);
568 WorldDatabase.WarnAboutSyncQueries(true);
569
571 while (!World::IsStopped())
572 {
574 realCurrTime = getMSTime();
575
576 uint32 diff = getMSTimeDiff(realPrevTime, realCurrTime);
577 if (diff < minUpdateDiff)
578 {
579 uint32 sleepTime = minUpdateDiff - diff;
580 if (sleepTime >= halfMaxCoreStuckTime)
581 LOG_ERROR("server.worldserver", "WorldUpdateLoop() waiting for {} ms with MaxCoreStuckTime set to {} ms", sleepTime, maxCoreStuckTime);
582 // sleep until enough time passes that we can update all timers
583 std::this_thread::sleep_for(Milliseconds(sleepTime));
584 continue;
585 }
586
587 sWorld->Update(diff);
588 realPrevTime = realCurrTime;
589
590#ifdef _WIN32
591 if (m_ServiceStatus == 0)
593
594 while (m_ServiceStatus == 2)
595 Sleep(1000);
596#endif
597 }
598
599 LoginDatabase.WarnAboutSyncQueries(false);
600 CharacterDatabase.WarnAboutSyncQueries(false);
601 WorldDatabase.WarnAboutSyncQueries(false);
602}
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"