[8441] Implement check DBs versions (required_* fields) at mangosd/realmd loading.
[getmangos.git] / src / mangosd / Master.cpp
blob7cb6c1011d64b6a8e0613d713d08176f1bd7c485
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"
41 #include "revision_sql.h"
43 #include "sockets/TcpSocket.h"
44 #include "sockets/Utility.h"
45 #include "sockets/Parse.h"
46 #include "sockets/Socket.h"
47 #include "sockets/SocketHandler.h"
48 #include "sockets/ListenSocket.h"
50 #ifdef WIN32
51 #include "ServiceWin32.h"
52 extern int m_ServiceStatus;
53 #endif
55 /// \todo Warning disabling not useful under VC++2005. Can somebody say on which compiler it is useful?
56 #pragma warning(disable:4305)
58 INSTANTIATE_SINGLETON_1( Master );
60 volatile uint32 Master::m_masterLoopCounter = 0;
62 class FreezeDetectorRunnable : public ACE_Based::Runnable
64 public:
65 FreezeDetectorRunnable() { _delaytime = 0; }
66 uint32 m_loops, m_lastchange;
67 uint32 w_loops, w_lastchange;
68 uint32 _delaytime;
69 void SetDelayTime(uint32 t) { _delaytime = t; }
70 void run(void)
72 if(!_delaytime)
73 return;
74 sLog.outString("Starting up anti-freeze thread (%u seconds max stuck time)...",_delaytime/1000);
75 m_loops = 0;
76 w_loops = 0;
77 m_lastchange = 0;
78 w_lastchange = 0;
79 while(!World::IsStopped())
81 ACE_Based::Thread::Sleep(1000);
83 uint32 curtime = getMSTime();
84 //DEBUG_LOG("anti-freeze: time=%u, counters=[%u; %u]",curtime,Master::m_masterLoopCounter,World::m_worldLoopCounter);
86 // There is no Master anymore
87 // TODO: clear the rest of the code
88 // // normal work
89 // if(m_loops != Master::m_masterLoopCounter)
90 // {
91 // m_lastchange = curtime;
92 // m_loops = Master::m_masterLoopCounter;
93 // }
94 // // possible freeze
95 // else if(getMSTimeDiff(m_lastchange,curtime) > _delaytime)
96 // {
97 // sLog.outError("Main/Sockets Thread hangs, kicking out server!");
98 // *((uint32 volatile*)NULL) = 0; // bang crash
99 // }
101 // normal work
102 if(w_loops != World::m_worldLoopCounter)
104 w_lastchange = curtime;
105 w_loops = World::m_worldLoopCounter;
107 // possible freeze
108 else if(getMSTimeDiff(w_lastchange,curtime) > _delaytime)
110 sLog.outError("World Thread hangs, kicking out server!");
111 *((uint32 volatile*)NULL) = 0; // bang crash
114 sLog.outString("Anti-freeze thread exiting without problems.");
118 class RARunnable : public ACE_Based::Runnable
120 public:
121 uint32 numLoops, loopCounter;
123 RARunnable ()
125 uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
126 numLoops = (sConfig.GetIntDefault ("MaxPingTime", 30) * (MINUTE * 1000000 / socketSelecttime));
127 loopCounter = 0;
130 void checkping ()
132 // ping if need
133 if ((++loopCounter) == numLoops)
135 loopCounter = 0;
136 sLog.outDetail ("Ping MySQL to keep connection alive");
137 delete WorldDatabase.Query ("SELECT 1 FROM command LIMIT 1");
138 delete loginDatabase.Query ("SELECT 1 FROM realmlist LIMIT 1");
139 delete CharacterDatabase.Query ("SELECT 1 FROM bugreport LIMIT 1");
143 void run ()
145 SocketHandler h;
147 // Launch the RA listener socket
148 ListenSocket<RASocket> RAListenSocket (h);
149 bool usera = sConfig.GetBoolDefault ("Ra.Enable", false);
151 if (usera)
153 port_t raport = sConfig.GetIntDefault ("Ra.Port", 3443);
154 std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0");
155 ipaddr_t raip;
156 if (!Utility::u2ip (stringip, raip))
157 sLog.outError ("MaNGOS RA can not bind to ip %s", stringip.c_str ());
158 else if (RAListenSocket.Bind (raip, raport))
159 sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ());
160 else
162 h.Add (&RAListenSocket);
164 sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ());
168 // Socket Selet time is in microseconds , not miliseconds!!
169 uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
171 // if use ra spend time waiting for io, if not use ra ,just sleep
172 if (usera)
174 while (!World::IsStopped())
176 h.Select (0, socketSelecttime);
177 checkping ();
180 else
182 while (!World::IsStopped())
184 ACE_Based::Thread::Sleep(static_cast<unsigned long> (socketSelecttime / 1000));
185 checkping ();
191 Master::Master()
195 Master::~Master()
199 /// Main function
200 int Master::Run()
202 /// worldd PID file creation
203 std::string pidfile = sConfig.GetStringDefault("PidFile", "");
204 if(!pidfile.empty())
206 uint32 pid = CreatePIDFile(pidfile);
207 if( !pid )
209 sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str() );
210 return 1;
213 sLog.outString( "Daemon PID: %u\n", pid );
216 ///- Start the databases
217 if (!_StartDB())
218 return 1;
220 ///- Initialize the World
221 sWorld.SetInitialWorldSettings();
223 ///- Catch termination signals
224 _HookSignals();
226 ///- Launch WorldRunnable thread
227 ACE_Based::Thread world_thread(new WorldRunnable);
228 world_thread.setPriority(ACE_Based::Highest);
230 // set server online
231 loginDatabase.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID);
233 ACE_Based::Thread* cliThread = NULL;
235 #ifdef WIN32
236 if (sConfig.GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
237 #else
238 if (sConfig.GetBoolDefault("Console.Enable", true))
239 #endif
241 ///- Launch CliRunnable thread
242 cliThread = new ACE_Based::Thread(new CliRunnable);
245 ACE_Based::Thread rar_thread(new RARunnable);
247 ///- Handle affinity for multiple processors and process priority on Windows
248 #ifdef WIN32
250 HANDLE hProcess = GetCurrentProcess();
252 uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
253 if(Aff > 0)
255 ULONG_PTR appAff;
256 ULONG_PTR sysAff;
258 if(GetProcessAffinityMask(hProcess,&appAff,&sysAff))
260 ULONG_PTR curAff = Aff & appAff; // remove non accessible processors
262 if(!curAff )
264 sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for mangosd. Accessible processors bitmask (hex): %x",Aff,appAff);
266 else
268 if(SetProcessAffinityMask(hProcess,curAff))
269 sLog.outString("Using processors (bitmask, hex): %x", curAff);
270 else
271 sLog.outError("Can't set used processors (hex): %x",curAff);
274 sLog.outString();
277 bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
279 // if(Prio && (m_ServiceStatus == -1)/* need set to default process priority class in service mode*/)
280 if(Prio)
282 if(SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
283 sLog.outString("mangosd process priority class set to HIGH");
284 else
285 sLog.outError("ERROR: Can't set mangosd process priority class.");
286 sLog.outString();
289 #endif
291 uint32 realCurrTime, realPrevTime;
292 realCurrTime = realPrevTime = getMSTime();
294 uint32 socketSelecttime = sWorld.getConfig(CONFIG_SOCKET_SELECTTIME);
296 // maximum counter for next ping
297 uint32 numLoops = (sConfig.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE * 1000000 / socketSelecttime));
298 uint32 loopCounter = 0;
300 ///- Start up freeze catcher thread
301 if(uint32 freeze_delay = sConfig.GetIntDefault("MaxCoreStuckTime", 0))
303 FreezeDetectorRunnable *fdr = new FreezeDetectorRunnable();
304 fdr->SetDelayTime(freeze_delay*1000);
305 ACE_Based::Thread freeze_thread(fdr);
306 freeze_thread.setPriority(ACE_Based::Highest);
309 ///- Launch the world listener socket
310 port_t wsport = sWorld.getConfig (CONFIG_PORT_WORLD);
311 std::string bind_ip = sConfig.GetStringDefault ("BindIP", "0.0.0.0");
313 if (sWorldSocketMgr->StartNetwork (wsport, bind_ip.c_str ()) == -1)
315 sLog.outError ("Failed to start network");
316 World::StopNow(ERROR_EXIT_CODE);
317 // go down and shutdown the server
320 sWorldSocketMgr->Wait ();
322 // set server offline
323 loginDatabase.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID);
325 ///- Remove signal handling before leaving
326 _UnhookSignals();
328 // when the main thread closes the singletons get unloaded
329 // since worldrunnable uses them, it will crash if unloaded after master
330 world_thread.wait();
331 rar_thread.wait ();
333 ///- Clean database before leaving
334 clearOnlineAccounts();
336 ///- Wait for delay threads to end
337 CharacterDatabase.HaltDelayThread();
338 WorldDatabase.HaltDelayThread();
339 loginDatabase.HaltDelayThread();
341 sLog.outString( "Halting process..." );
343 if (cliThread)
345 #ifdef WIN32
347 // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API)
348 //_exit(1);
349 // send keyboard input to safely unblock the CLI thread
350 INPUT_RECORD b[5];
351 HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
352 b[0].EventType = KEY_EVENT;
353 b[0].Event.KeyEvent.bKeyDown = TRUE;
354 b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
355 b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
356 b[0].Event.KeyEvent.wRepeatCount = 1;
358 b[1].EventType = KEY_EVENT;
359 b[1].Event.KeyEvent.bKeyDown = FALSE;
360 b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
361 b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
362 b[1].Event.KeyEvent.wRepeatCount = 1;
364 b[2].EventType = KEY_EVENT;
365 b[2].Event.KeyEvent.bKeyDown = TRUE;
366 b[2].Event.KeyEvent.dwControlKeyState = 0;
367 b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
368 b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
369 b[2].Event.KeyEvent.wRepeatCount = 1;
370 b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;
372 b[3].EventType = KEY_EVENT;
373 b[3].Event.KeyEvent.bKeyDown = FALSE;
374 b[3].Event.KeyEvent.dwControlKeyState = 0;
375 b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
376 b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
377 b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
378 b[3].Event.KeyEvent.wRepeatCount = 1;
379 DWORD numb;
380 BOOL ret = WriteConsoleInput(hStdIn, b, 4, &numb);
382 cliThread->wait();
384 #else
386 cliThread->destroy();
388 #endif
390 delete cliThread;
393 // for some unknown reason, unloading scripts here and not in worldrunnable
394 // fixes a memory leak related to detaching threads from the module
395 UnloadScriptingModule();
397 // Exit the process with specified return value
398 return World::GetExitCode();
401 /// Initialize connection to the databases
402 bool Master::_StartDB()
404 ///- Get world database info from configuration file
405 std::string dbstring;
406 if(!sConfig.GetString("WorldDatabaseInfo", &dbstring))
408 sLog.outError("Database not specified in configuration file");
409 return false;
411 sLog.outString("World Database: %s", dbstring.c_str());
413 ///- Initialise the world database
414 if(!WorldDatabase.Initialize(dbstring.c_str()))
416 sLog.outError("Cannot connect to world database %s",dbstring.c_str());
417 return false;
420 if(!WorldDatabase.CheckRequiredField("db_version",REVISION_DB_MANGOS))
421 return false;
423 if(!sConfig.GetString("CharacterDatabaseInfo", &dbstring))
425 sLog.outError("Character Database not specified in configuration file");
426 return false;
428 sLog.outString("Character Database: %s", dbstring.c_str());
430 ///- Initialise the Character database
431 if(!CharacterDatabase.Initialize(dbstring.c_str()))
433 sLog.outError("Cannot connect to Character database %s",dbstring.c_str());
434 return false;
437 if(!CharacterDatabase.CheckRequiredField("character_db_version",REVISION_DB_CHARACTERS))
438 return false;
440 ///- Get login database info from configuration file
441 if(!sConfig.GetString("LoginDatabaseInfo", &dbstring))
443 sLog.outError("Login database not specified in configuration file");
444 return false;
447 ///- Initialise the login database
448 sLog.outString("Login Database: %s", dbstring.c_str() );
449 if(!loginDatabase.Initialize(dbstring.c_str()))
451 sLog.outError("Cannot connect to login database %s",dbstring.c_str());
452 return false;
455 if(!loginDatabase.CheckRequiredField("realmd_db_version",REVISION_DB_REALMD))
456 return false;
458 ///- Get the realm Id from the configuration file
459 realmID = sConfig.GetIntDefault("RealmID", 0);
460 if(!realmID)
462 sLog.outError("Realm ID not defined in configuration file");
463 return false;
465 sLog.outString("Realm running as realm ID %d", realmID);
467 ///- Clean the database before starting
468 clearOnlineAccounts();
470 sWorld.LoadDBVersion();
472 sLog.outString("Using World DB: %s", sWorld.GetDBVersion());
473 sLog.outString("Using creature EventAI: %s", sWorld.GetCreatureEventAIVersion());
474 return true;
477 /// Clear 'online' status for all accounts with characters in this realm
478 void Master::clearOnlineAccounts()
480 // Cleanup online status for characters hosted at current realm
481 /// \todo Only accounts with characters logged on *this* realm should have online status reset. Move the online column from 'account' to 'realmcharacters'?
482 loginDatabase.PExecute(
483 "UPDATE account SET online = 0 WHERE online > 0 "
484 "AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = '%d')",realmID);
486 CharacterDatabase.Execute("UPDATE characters SET online = 0 WHERE online<>0");
488 // Battleground instance ids reset at server restart
489 CharacterDatabase.Execute("UPDATE character_battleground_data SET instance_id = 0");
492 /// Handle termination signals
493 void Master::_OnSignal(int s)
495 switch (s)
497 case SIGINT:
498 World::StopNow(RESTART_EXIT_CODE);
499 break;
500 case SIGTERM:
501 #ifdef _WIN32
502 case SIGBREAK:
503 #endif
504 World::StopNow(SHUTDOWN_EXIT_CODE);
505 break;
508 signal(s, _OnSignal);
511 /// Define hook '_OnSignal' for all termination signals
512 void Master::_HookSignals()
514 signal(SIGINT, _OnSignal);
515 signal(SIGTERM, _OnSignal);
516 #ifdef _WIN32
517 signal(SIGBREAK, _OnSignal);
518 #endif
521 /// Unhook the signals before leaving
522 void Master::_UnhookSignals()
524 signal(SIGINT, 0);
525 signal(SIGTERM, 0);
526 #ifdef _WIN32
527 signal(SIGBREAK, 0);
528 #endif