[7732] Fixed compile warnings.
[getmangos.git] / src / mangosd / Master.cpp
bloba4ef6e2ac3f3ecb2de28f7be9840d75274d48475
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup mangosd
23 #include <ace/OS_NS_signal.h>
25 #include "WorldSocketMgr.h"
26 #include "Common.h"
27 #include "Master.h"
28 #include "WorldSocket.h"
29 #include "WorldRunnable.h"
30 #include "World.h"
31 #include "Log.h"
32 #include "Timer.h"
33 #include "Policies/SingletonImp.h"
34 #include "SystemConfig.h"
35 #include "Config/ConfigEnv.h"
36 #include "Database/DatabaseEnv.h"
37 #include "CliRunnable.h"
38 #include "RASocket.h"
39 #include "ScriptCalls.h"
40 #include "Util.h"
42 #include "sockets/TcpSocket.h"
43 #include "sockets/Utility.h"
44 #include "sockets/Parse.h"
45 #include "sockets/Socket.h"
46 #include "sockets/SocketHandler.h"
47 #include "sockets/ListenSocket.h"
49 #ifdef WIN32
50 #include "ServiceWin32.h"
51 extern int m_ServiceStatus;
52 #endif
54 /// \todo Warning disabling not useful under VC++2005. Can somebody say on which compiler it is useful?
55 #pragma warning(disable:4305)
57 INSTANTIATE_SINGLETON_1( Master );
59 volatile uint32 Master::m_masterLoopCounter = 0;
61 class FreezeDetectorRunnable : public ZThread::Runnable
63 public:
64 FreezeDetectorRunnable() { _delaytime = 0; }
65 uint32 m_loops, m_lastchange;
66 uint32 w_loops, w_lastchange;
67 uint32 _delaytime;
68 void SetDelayTime(uint32 t) { _delaytime = t; }
69 void run(void)
71 if(!_delaytime)
72 return;
73 sLog.outString("Starting up anti-freeze thread (%u seconds max stuck time)...",_delaytime/1000);
74 m_loops = 0;
75 w_loops = 0;
76 m_lastchange = 0;
77 w_lastchange = 0;
78 while(!World::IsStopped())
80 ZThread::Thread::sleep(1000);
81 uint32 curtime = getMSTime();
82 //DEBUG_LOG("anti-freeze: time=%u, counters=[%u; %u]",curtime,Master::m_masterLoopCounter,World::m_worldLoopCounter);
84 // There is no Master anymore
85 // TODO: clear the rest of the code
86 // // normal work
87 // if(m_loops != Master::m_masterLoopCounter)
88 // {
89 // m_lastchange = curtime;
90 // m_loops = Master::m_masterLoopCounter;
91 // }
92 // // possible freeze
93 // else if(getMSTimeDiff(m_lastchange,curtime) > _delaytime)
94 // {
95 // sLog.outError("Main/Sockets Thread hangs, kicking out server!");
96 // *((uint32 volatile*)NULL) = 0; // bang crash
97 // }
99 // normal work
100 if(w_loops != World::m_worldLoopCounter)
102 w_lastchange = curtime;
103 w_loops = World::m_worldLoopCounter;
105 // possible freeze
106 else if(getMSTimeDiff(w_lastchange,curtime) > _delaytime)
108 sLog.outError("World Thread hangs, kicking out server!");
109 *((uint32 volatile*)NULL) = 0; // bang crash
112 sLog.outString("Anti-freeze thread exiting without problems.");
116 class RARunnable : public ZThread::Runnable
118 public:
119 uint32 numLoops, loopCounter;
121 RARunnable ()
123 uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
124 numLoops = (sConfig.GetIntDefault ("MaxPingTime", 30) * (MINUTE * 1000000 / socketSelecttime));
125 loopCounter = 0;
128 void checkping ()
130 // ping if need
131 if ((++loopCounter) == numLoops)
133 loopCounter = 0;
134 sLog.outDetail ("Ping MySQL to keep connection alive");
135 delete WorldDatabase.Query ("SELECT 1 FROM command LIMIT 1");
136 delete loginDatabase.Query ("SELECT 1 FROM realmlist LIMIT 1");
137 delete CharacterDatabase.Query ("SELECT 1 FROM bugreport LIMIT 1");
141 void run ()
143 SocketHandler h;
145 // Launch the RA listener socket
146 ListenSocket<RASocket> RAListenSocket (h);
147 bool usera = sConfig.GetBoolDefault ("Ra.Enable", false);
149 if (usera)
151 port_t raport = sConfig.GetIntDefault ("Ra.Port", 3443);
152 std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0");
153 ipaddr_t raip;
154 if (!Utility::u2ip (stringip, raip))
155 sLog.outError ("MaNGOS RA can not bind to ip %s", stringip.c_str ());
156 else if (RAListenSocket.Bind (raip, raport))
157 sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ());
158 else
160 h.Add (&RAListenSocket);
162 sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ());
166 // Socket Selet time is in microseconds , not miliseconds!!
167 uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
169 // if use ra spend time waiting for io, if not use ra ,just sleep
170 if (usera)
172 while (!World::IsStopped())
174 h.Select (0, socketSelecttime);
175 checkping ();
178 else
180 while (!World::IsStopped())
182 ZThread::Thread::sleep (static_cast<unsigned long> (socketSelecttime / 1000));
183 checkping ();
189 Master::Master()
193 Master::~Master()
197 /// Main function
198 int Master::Run()
200 /// worldd PID file creation
201 std::string pidfile = sConfig.GetStringDefault("PidFile", "");
202 if(!pidfile.empty())
204 uint32 pid = CreatePIDFile(pidfile);
205 if( !pid )
207 sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str() );
208 return 1;
211 sLog.outString( "Daemon PID: %u\n", pid );
214 ///- Start the databases
215 if (!_StartDB())
216 return 1;
218 ///- Initialize the World
219 sWorld.SetInitialWorldSettings();
221 ///- Catch termination signals
222 _HookSignals();
224 ///- Launch WorldRunnable thread
225 ZThread::Thread t(new WorldRunnable);
226 t.setPriority ((ZThread::Priority )2);
228 // set server online
229 loginDatabase.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID);
231 #ifdef WIN32
232 if (sConfig.GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
233 #else
234 if (sConfig.GetBoolDefault("Console.Enable", true))
235 #endif
237 ///- Launch CliRunnable thread
238 ZThread::Thread td1(new CliRunnable);
241 ZThread::Thread td2(new RARunnable);
243 ///- Handle affinity for multiple processors and process priority on Windows
244 #ifdef WIN32
246 HANDLE hProcess = GetCurrentProcess();
248 uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
249 if(Aff > 0)
251 ULONG_PTR appAff;
252 ULONG_PTR sysAff;
254 if(GetProcessAffinityMask(hProcess,&appAff,&sysAff))
256 ULONG_PTR curAff = Aff & appAff; // remove non accessible processors
258 if(!curAff )
260 sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for mangosd. Accessible processors bitmask (hex): %x",Aff,appAff);
262 else
264 if(SetProcessAffinityMask(hProcess,curAff))
265 sLog.outString("Using processors (bitmask, hex): %x", curAff);
266 else
267 sLog.outError("Can't set used processors (hex): %x",curAff);
270 sLog.outString();
273 bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
275 // if(Prio && (m_ServiceStatus == -1)/* need set to default process priority class in service mode*/)
276 if(Prio)
278 if(SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
279 sLog.outString("mangosd process priority class set to HIGH");
280 else
281 sLog.outError("ERROR: Can't set mangosd process priority class.");
282 sLog.outString();
285 #endif
287 uint32 realCurrTime, realPrevTime;
288 realCurrTime = realPrevTime = getMSTime();
290 uint32 socketSelecttime = sWorld.getConfig(CONFIG_SOCKET_SELECTTIME);
292 // maximum counter for next ping
293 uint32 numLoops = (sConfig.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE * 1000000 / socketSelecttime));
294 uint32 loopCounter = 0;
296 ///- Start up freeze catcher thread
297 uint32 freeze_delay = sConfig.GetIntDefault("MaxCoreStuckTime", 0);
298 if(freeze_delay)
300 FreezeDetectorRunnable *fdr = new FreezeDetectorRunnable();
301 fdr->SetDelayTime(freeze_delay*1000);
302 ZThread::Thread t(fdr);
303 t.setPriority(ZThread::High);
306 ///- Launch the world listener socket
307 port_t wsport = sWorld.getConfig (CONFIG_PORT_WORLD);
308 std::string bind_ip = sConfig.GetStringDefault ("BindIP", "0.0.0.0");
310 if (sWorldSocketMgr->StartNetwork (wsport, bind_ip.c_str ()) == -1)
312 sLog.outError ("Failed to start network");
313 World::StopNow(ERROR_EXIT_CODE);
314 // go down and shutdown the server
317 sWorldSocketMgr->Wait ();
319 // set server offline
320 loginDatabase.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID);
322 ///- Remove signal handling before leaving
323 _UnhookSignals();
325 // when the main thread closes the singletons get unloaded
326 // since worldrunnable uses them, it will crash if unloaded after master
327 t.wait();
328 td2.wait ();
330 ///- Clean database before leaving
331 clearOnlineAccounts();
333 ///- Wait for delay threads to end
334 CharacterDatabase.HaltDelayThread();
335 WorldDatabase.HaltDelayThread();
336 loginDatabase.HaltDelayThread();
338 sLog.outString( "Halting process..." );
340 #ifdef WIN32
341 if (sConfig.GetBoolDefault("Console.Enable", true))
343 // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API)
344 //_exit(1);
345 // send keyboard input to safely unblock the CLI thread
346 INPUT_RECORD b[5];
347 HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
348 b[0].EventType = KEY_EVENT;
349 b[0].Event.KeyEvent.bKeyDown = TRUE;
350 b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
351 b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
352 b[0].Event.KeyEvent.wRepeatCount = 1;
354 b[1].EventType = KEY_EVENT;
355 b[1].Event.KeyEvent.bKeyDown = FALSE;
356 b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
357 b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
358 b[1].Event.KeyEvent.wRepeatCount = 1;
360 b[2].EventType = KEY_EVENT;
361 b[2].Event.KeyEvent.bKeyDown = TRUE;
362 b[2].Event.KeyEvent.dwControlKeyState = 0;
363 b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
364 b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
365 b[2].Event.KeyEvent.wRepeatCount = 1;
366 b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;
368 b[3].EventType = KEY_EVENT;
369 b[3].Event.KeyEvent.bKeyDown = FALSE;
370 b[3].Event.KeyEvent.dwControlKeyState = 0;
371 b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
372 b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
373 b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
374 b[3].Event.KeyEvent.wRepeatCount = 1;
375 DWORD numb;
376 BOOL ret = WriteConsoleInput(hStdIn, b, 4, &numb);
378 #endif
380 // for some unknown reason, unloading scripts here and not in worldrunnable
381 // fixes a memory leak related to detaching threads from the module
382 UnloadScriptingModule();
384 // Exit the process with specified return value
385 return World::GetExitCode();
388 /// Initialize connection to the databases
389 bool Master::_StartDB()
391 ///- Get world database info from configuration file
392 std::string dbstring;
393 if(!sConfig.GetString("WorldDatabaseInfo", &dbstring))
395 sLog.outError("Database not specified in configuration file");
396 return false;
398 sLog.outString("World Database: %s", dbstring.c_str());
400 ///- Initialise the world database
401 if(!WorldDatabase.Initialize(dbstring.c_str()))
403 sLog.outError("Cannot connect to world database %s",dbstring.c_str());
404 return false;
407 if(!sConfig.GetString("CharacterDatabaseInfo", &dbstring))
409 sLog.outError("Character Database not specified in configuration file");
410 return false;
412 sLog.outString("Character Database: %s", dbstring.c_str());
414 ///- Initialise the Character database
415 if(!CharacterDatabase.Initialize(dbstring.c_str()))
417 sLog.outError("Cannot connect to Character database %s",dbstring.c_str());
418 return false;
421 ///- Get login database info from configuration file
422 if(!sConfig.GetString("LoginDatabaseInfo", &dbstring))
424 sLog.outError("Login database not specified in configuration file");
425 return false;
428 ///- Initialise the login database
429 sLog.outString("Login Database: %s", dbstring.c_str() );
430 if(!loginDatabase.Initialize(dbstring.c_str()))
432 sLog.outError("Cannot connect to login database %s",dbstring.c_str());
433 return false;
436 ///- Get the realm Id from the configuration file
437 realmID = sConfig.GetIntDefault("RealmID", 0);
438 if(!realmID)
440 sLog.outError("Realm ID not defined in configuration file");
441 return false;
443 sLog.outString("Realm running as realm ID %d", realmID);
445 ///- Clean the database before starting
446 clearOnlineAccounts();
448 sWorld.LoadDBVersion();
450 sLog.outString("Using World DB: %s", sWorld.GetDBVersion());
451 sLog.outString("Using creature EventAI: %s", sWorld.GetCreatureEventAIVersion());
452 return true;
455 /// Clear 'online' status for all accounts with characters in this realm
456 void Master::clearOnlineAccounts()
458 // Cleanup online status for characters hosted at current realm
459 /// \todo Only accounts with characters logged on *this* realm should have online status reset. Move the online column from 'account' to 'realmcharacters'?
460 loginDatabase.PExecute(
461 "UPDATE account SET online = 0 WHERE online > 0 "
462 "AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = '%d')",realmID);
464 CharacterDatabase.Execute("UPDATE characters SET online = 0 WHERE online<>0");
466 // Battleground instance ids reset at server restart
467 CharacterDatabase.Execute("UPDATE characters SET bgid = 0 WHERE bgid<>0");
470 /// Handle termination signals
471 void Master::_OnSignal(int s)
473 switch (s)
475 case SIGINT:
476 World::StopNow(RESTART_EXIT_CODE);
477 break;
478 case SIGTERM:
479 #ifdef _WIN32
480 case SIGBREAK:
481 #endif
482 World::StopNow(SHUTDOWN_EXIT_CODE);
483 break;
486 signal(s, _OnSignal);
489 /// Define hook '_OnSignal' for all termination signals
490 void Master::_HookSignals()
492 signal(SIGINT, _OnSignal);
493 signal(SIGTERM, _OnSignal);
494 #ifdef _WIN32
495 signal(SIGBREAK, _OnSignal);
496 #endif
499 /// Unhook the signals before leaving
500 void Master::_UnhookSignals()
502 signal(SIGINT, 0);
503 signal(SIGTERM, 0);
504 #ifdef _WIN32
505 signal(SIGBREAK, 0);
506 #endif