2 * Copyright (C) 2005-2008 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
23 #include <ace/OS_NS_signal.h>
25 #include "WorldSocketMgr.h"
28 #include "WorldSocket.h"
29 #include "WorldRunnable.h"
33 #include "Policies/SingletonImp.h"
34 #include "SystemConfig.h"
35 #include "Config/ConfigEnv.h"
36 #include "Database/DatabaseEnv.h"
37 #include "CliRunnable.h"
39 #include "ScriptCalls.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"
50 #include "ServiceWin32.h"
51 extern int m_ServiceStatus
;
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
64 FreezeDetectorRunnable() { _delaytime
= 0; }
65 uint32 m_loops
, m_lastchange
;
66 uint32 w_loops
, w_lastchange
;
68 void SetDelayTime(uint32 t
) { _delaytime
= t
; }
73 sLog
.outString("Starting up anti-freeze thread (%u seconds max stuck time)...",_delaytime
/1000);
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
87 // if(m_loops != Master::m_masterLoopCounter)
89 // m_lastchange = curtime;
90 // m_loops = Master::m_masterLoopCounter;
93 // else if(getMSTimeDiff(m_lastchange,curtime) > _delaytime)
95 // sLog.outError("Main/Sockets Thread hangs, kicking out server!");
96 // *((uint32 volatile*)NULL) = 0; // bang crash
100 if(w_loops
!= World::m_worldLoopCounter
)
102 w_lastchange
= curtime
;
103 w_loops
= World::m_worldLoopCounter
;
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
119 uint32 numLoops
, loopCounter
;
123 uint32 socketSelecttime
= sWorld
.getConfig (CONFIG_SOCKET_SELECTTIME
);
124 numLoops
= (sConfig
.GetIntDefault ("MaxPingTime", 30) * (MINUTE
* 1000000 / socketSelecttime
));
132 if ((++loopCounter
) == numLoops
)
135 sLog
.outDetail ("Ping MySQL to keep connection alive");
136 delete WorldDatabase
.Query ("SELECT 1 FROM command LIMIT 1");
137 delete loginDatabase
.Query ("SELECT 1 FROM realmlist LIMIT 1");
138 delete CharacterDatabase
.Query ("SELECT 1 FROM bugreport LIMIT 1");
147 // Launch the RA listener socket
148 ListenSocket
<RASocket
> RAListenSocket (h
);
149 bool usera
= sConfig
.GetBoolDefault ("Ra.Enable", false);
153 port_t raport
= sConfig
.GetIntDefault ("Ra.Port", 3443);
154 std::string stringip
= sConfig
.GetStringDefault ("Ra.IP", "0.0.0.0");
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 ());
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
173 while (!World::IsStopped())
175 h
.Select (0, socketSelecttime
);
179 while (!World::IsStopped())
181 ZThread::Thread::sleep (static_cast<unsigned long> (socketSelecttime
/ 1000));
198 /// worldd PID file creation
199 std::string pidfile
= sConfig
.GetStringDefault("PidFile", "");
202 uint32 pid
= CreatePIDFile(pidfile
);
205 sLog
.outError( "Cannot create PID file %s.\n", pidfile
.c_str() );
209 sLog
.outString( "Daemon PID: %u\n", pid
);
212 ///- Start the databases
216 ///- Initialize the World
217 sWorld
.SetInitialWorldSettings();
219 ///- Catch termination signals
222 ///- Launch WorldRunnable thread
223 ZThread::Thread
t(new WorldRunnable
);
224 t
.setPriority ((ZThread::Priority
)2);
227 loginDatabase
.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID
);
230 if (sConfig
.GetBoolDefault("Console.Enable", true) && (m_ServiceStatus
== -1)/* need disable console in service mode*/)
232 if (sConfig
.GetBoolDefault("Console.Enable", true))
235 ///- Launch CliRunnable thread
236 ZThread::Thread
td1(new CliRunnable
);
239 ZThread::Thread
td2(new RARunnable
);
241 ///- Handle affinity for multiple processors and process priority on Windows
244 HANDLE hProcess
= GetCurrentProcess();
246 uint32 Aff
= sConfig
.GetIntDefault("UseProcessors", 0);
252 if(GetProcessAffinityMask(hProcess
,&appAff
,&sysAff
))
254 ULONG_PTR curAff
= Aff
& appAff
; // remove non accessible processors
258 sLog
.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for mangosd. Accessible processors bitmask (hex): %x",Aff
,appAff
);
262 if(SetProcessAffinityMask(hProcess
,curAff
))
263 sLog
.outString("Using processors (bitmask, hex): %x", curAff
);
265 sLog
.outError("Can't set used processors (hex): %x",curAff
);
271 bool Prio
= sConfig
.GetBoolDefault("ProcessPriority", false);
273 // if(Prio && (m_ServiceStatus == -1)/* need set to default process priority class in service mode*/)
276 if(SetPriorityClass(hProcess
,HIGH_PRIORITY_CLASS
))
277 sLog
.outString("mangosd process priority class set to HIGH");
279 sLog
.outError("ERROR: Can't set mangosd process priority class.");
285 uint32 realCurrTime
, realPrevTime
;
286 realCurrTime
= realPrevTime
= getMSTime();
288 uint32 socketSelecttime
= sWorld
.getConfig(CONFIG_SOCKET_SELECTTIME
);
290 // maximum counter for next ping
291 uint32 numLoops
= (sConfig
.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE
* 1000000 / socketSelecttime
));
292 uint32 loopCounter
= 0;
294 ///- Start up freeze catcher thread
295 uint32 freeze_delay
= sConfig
.GetIntDefault("MaxCoreStuckTime", 0);
298 FreezeDetectorRunnable
*fdr
= new FreezeDetectorRunnable();
299 fdr
->SetDelayTime(freeze_delay
*1000);
300 ZThread::Thread
t(fdr
);
301 t
.setPriority(ZThread::High
);
304 ///- Launch the world listener socket
305 port_t wsport
= sWorld
.getConfig (CONFIG_PORT_WORLD
);
306 std::string bind_ip
= sConfig
.GetStringDefault ("BindIP", "0.0.0.0");
308 if (sWorldSocketMgr
->StartNetwork (wsport
, bind_ip
.c_str ()) == -1)
310 sLog
.outError ("Failed to start network");
311 World::StopNow(ERROR_EXIT_CODE
);
312 // go down and shutdown the server
315 sWorldSocketMgr
->Wait ();
317 // set server offline
318 loginDatabase
.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID
);
320 ///- Remove signal handling before leaving
323 // when the main thread closes the singletons get unloaded
324 // since worldrunnable uses them, it will crash if unloaded after master
328 ///- Clean database before leaving
329 clearOnlineAccounts();
331 ///- Wait for delay threads to end
332 CharacterDatabase
.HaltDelayThread();
333 WorldDatabase
.HaltDelayThread();
334 loginDatabase
.HaltDelayThread();
336 sLog
.outString( "Halting process..." );
339 if (sConfig
.GetBoolDefault("Console.Enable", true))
341 // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API)
343 // send keyboard input to safely unblock the CLI thread
345 HANDLE hStdIn
= GetStdHandle(STD_INPUT_HANDLE
);
346 b
[0].EventType
= KEY_EVENT
;
347 b
[0].Event
.KeyEvent
.bKeyDown
= TRUE
;
348 b
[0].Event
.KeyEvent
.uChar
.AsciiChar
= 'X';
349 b
[0].Event
.KeyEvent
.wVirtualKeyCode
= 'X';
350 b
[0].Event
.KeyEvent
.wRepeatCount
= 1;
352 b
[1].EventType
= KEY_EVENT
;
353 b
[1].Event
.KeyEvent
.bKeyDown
= FALSE
;
354 b
[1].Event
.KeyEvent
.uChar
.AsciiChar
= 'X';
355 b
[1].Event
.KeyEvent
.wVirtualKeyCode
= 'X';
356 b
[1].Event
.KeyEvent
.wRepeatCount
= 1;
358 b
[2].EventType
= KEY_EVENT
;
359 b
[2].Event
.KeyEvent
.bKeyDown
= TRUE
;
360 b
[2].Event
.KeyEvent
.dwControlKeyState
= 0;
361 b
[2].Event
.KeyEvent
.uChar
.AsciiChar
= '\r';
362 b
[2].Event
.KeyEvent
.wVirtualKeyCode
= VK_RETURN
;
363 b
[2].Event
.KeyEvent
.wRepeatCount
= 1;
364 b
[2].Event
.KeyEvent
.wVirtualScanCode
= 0x1c;
366 b
[3].EventType
= KEY_EVENT
;
367 b
[3].Event
.KeyEvent
.bKeyDown
= FALSE
;
368 b
[3].Event
.KeyEvent
.dwControlKeyState
= 0;
369 b
[3].Event
.KeyEvent
.uChar
.AsciiChar
= '\r';
370 b
[3].Event
.KeyEvent
.wVirtualKeyCode
= VK_RETURN
;
371 b
[3].Event
.KeyEvent
.wVirtualScanCode
= 0x1c;
372 b
[3].Event
.KeyEvent
.wRepeatCount
= 1;
374 BOOL ret
= WriteConsoleInput(hStdIn
, b
, 4, &numb
);
378 // for some unknown reason, unloading scripts here and not in worldrunnable
379 // fixes a memory leak related to detaching threads from the module
380 UnloadScriptingModule();
382 // Exit the process with specified return value
383 return World::GetExitCode();
386 /// Initialize connection to the databases
387 bool Master::_StartDB()
389 ///- Get world database info from configuration file
390 std::string dbstring
;
391 if(!sConfig
.GetString("WorldDatabaseInfo", &dbstring
))
393 sLog
.outError("Database not specified in configuration file");
396 sLog
.outString("World Database: %s", dbstring
.c_str());
398 ///- Initialise the world database
399 if(!WorldDatabase
.Initialize(dbstring
.c_str()))
401 sLog
.outError("Cannot connect to world database %s",dbstring
.c_str());
405 if(!sConfig
.GetString("CharacterDatabaseInfo", &dbstring
))
407 sLog
.outError("Character Database not specified in configuration file");
410 sLog
.outString("Character Database: %s", dbstring
.c_str());
412 ///- Initialise the Character database
413 if(!CharacterDatabase
.Initialize(dbstring
.c_str()))
415 sLog
.outError("Cannot connect to Character database %s",dbstring
.c_str());
419 ///- Get login database info from configuration file
420 if(!sConfig
.GetString("LoginDatabaseInfo", &dbstring
))
422 sLog
.outError("Login database not specified in configuration file");
426 ///- Initialise the login database
427 sLog
.outString("Login Database: %s", dbstring
.c_str() );
428 if(!loginDatabase
.Initialize(dbstring
.c_str()))
430 sLog
.outError("Cannot connect to login database %s",dbstring
.c_str());
434 ///- Get the realm Id from the configuration file
435 realmID
= sConfig
.GetIntDefault("RealmID", 0);
438 sLog
.outError("Realm ID not defined in configuration file");
441 sLog
.outString("Realm running as realm ID %d", realmID
);
443 ///- Clean the database before starting
444 clearOnlineAccounts();
446 sWorld
.LoadDBVersion();
448 sLog
.outString("Using %s", sWorld
.GetDBVersion());
452 /// Clear 'online' status for all accounts with characters in this realm
453 void Master::clearOnlineAccounts()
455 // Cleanup online status for characters hosted at current realm
456 /// \todo Only accounts with characters logged on *this* realm should have online status reset. Move the online column from 'account' to 'realmcharacters'?
457 loginDatabase
.PExecute(
458 "UPDATE account SET online = 0 WHERE online > 0 "
459 "AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = '%d')",realmID
);
462 CharacterDatabase
.Execute("UPDATE characters SET online = 0");
465 /// Handle termination signals
466 void Master::_OnSignal(int s
)
471 World::StopNow(RESTART_EXIT_CODE
);
477 World::StopNow(SHUTDOWN_EXIT_CODE
);
481 signal(s
, _OnSignal
);
484 /// Define hook '_OnSignal' for all termination signals
485 void Master::_HookSignals()
487 signal(SIGINT
, _OnSignal
);
488 signal(SIGTERM
, _OnSignal
);
490 signal(SIGBREAK
, _OnSignal
);
494 /// Unhook the signals before leaving
495 void Master::_UnhookSignals()