root/trunk/src/trinitycore/Master.cpp @ 34

Revision 34, 16.6 kB (checked in by yumileroy, 17 years ago)

[svn] * Removing useless data accidentally committed.
* Applying ImpConfig? patch.
* Note: QUEUE_FOR_GM currently disabled as it's not compatible with the ACE patch. Anyone care to rewrite it?
* Note2: This is untested - I may have done some mistakes here and there. Will try to compile now.

Original author: XTZGZoReX
Date: 2008-10-10 13:37:21-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
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.
8 *
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.
13 *
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
17 */
18
19/** \file
20    \ingroup mangosd
21*/
22
23#include <ace/OS_NS_signal.h>
24
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
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"
48
49#ifdef WIN32
50#include "ServiceWin32.h"
51extern int m_ServiceStatus;
52#endif
53
54/// \todo Warning disabling not useful under VC++2005. Can somebody say on which compiler it is useful?
55#pragma warning(disable:4305)
56
57INSTANTIATE_SINGLETON_1( Master );
58
59volatile uint32 Master::m_masterLoopCounter = 0;
60
61class FreezeDetectorRunnable : public ZThread::Runnable
62{
63public:
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)
70    {
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::m_stopEvent)
79        {
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);
83
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//            }
98
99            // normal work
100            if(w_loops != World::m_worldLoopCounter)
101            {
102                w_lastchange = curtime;
103                w_loops = World::m_worldLoopCounter;
104            }
105            // possible freeze
106            else if(getMSTimeDiff(w_lastchange,curtime) > _delaytime)
107            {
108                sLog.outError("World Thread hangs, kicking out server!");
109                *((uint32 volatile*)NULL) = 0;                       // bang crash
110            }
111        }
112        sLog.outString("Anti-freeze thread exiting without problems.");
113    }
114};
115
116class RARunnable : public ZThread::Runnable
117{
118public:
119  uint32 numLoops, loopCounter;
120
121  RARunnable ()
122  {
123    uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
124    numLoops = (sConfig.GetIntDefault ("MaxPingTime", 30) * (MINUTE * 1000000 / socketSelecttime));
125    loopCounter = 0;
126  }
127
128  void
129  checkping ()
130  {
131    // ping if need
132    if ((++loopCounter) == numLoops)
133      {
134        loopCounter = 0;
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");
139      }
140  }
141
142  void
143  run (void)
144  {
145    SocketHandler h;
146
147    // Launch the RA listener socket
148    ListenSocket<RASocket> RAListenSocket (h);
149    bool usera = sConfig.GetBoolDefault ("Ra.Enable", false);
150
151    if (usera)
152      {
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
161          {
162            h.Add (&RAListenSocket);
163
164            sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ());
165          }
166      }
167
168    // Socket Selet time is in microseconds , not miliseconds!!
169    uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
170
171    // if use ra spend time waiting for io, if not use ra ,just sleep
172    if (usera)
173      while (!World::m_stopEvent)
174        {
175          h.Select (0, socketSelecttime);
176          checkping ();
177        }
178    else
179      while (!World::m_stopEvent)
180        {
181          ZThread::Thread::sleep (static_cast<unsigned long> (socketSelecttime / 1000));
182          checkping ();
183        }
184  }
185};
186
187Master::Master()
188{
189}
190
191Master::~Master()
192{
193}
194
195/// Main function
196int Master::Run()
197{
198    sLog.outString( "%s (core-daemon)", _FULLVERSION );
199    sLog.outString( "<Ctrl-C> to stop.\n" );
200
201    sLog.outTitle( " ______                       __");
202    sLog.outTitle( "/\\__  _\\       __          __/\\ \\__");
203    sLog.outTitle( "\\/_/\\ \\/ _ __ /\\_\\    ___ /\\_\\ \\ ,_\\  __  __");
204    sLog.outTitle( "   \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\");
205    sLog.outTitle( "    \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\");
206    sLog.outTitle( "     \\ \\_\\ \\_\\  \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\");
207    sLog.outTitle( "      \\/_/\\/_/   \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\");
208    sLog.outTitle( "                                 C O R E  /\\___/");
209    sLog.outTitle( "http://TrinityCore.org                    \\/__/\n");
210
211    /// worldd PID file creation
212    std::string pidfile = sConfig.GetStringDefault("PidFile", "");
213    if(!pidfile.empty())
214    {
215        uint32 pid = CreatePIDFile(pidfile);
216        if( !pid )
217        {
218            sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str() );
219            return 1;
220        }
221
222        sLog.outString( "Daemon PID: %u\n", pid );
223    }
224
225    ///- Start the databases
226    if (!_StartDB())
227        return 1;
228
229    ///- Initialize the World
230    sWorld.SetInitialWorldSettings();
231
232    ///- Catch termination signals
233    _HookSignals();
234
235    ///- Launch WorldRunnable thread
236    ZThread::Thread t(new WorldRunnable);
237    t.setPriority ((ZThread::Priority )2);
238
239    // set server online
240    loginDatabase.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID);
241
242        // Create table: has_logged_in_before - used for certain custom options
243        sLog.outBasic("ImpConfig: Creating/Checking table 'has_logged_in_before'...");
244        CharacterDatabase.PExecute("CREATE TABLE IF NOT EXISTS `has_logged_in_before` (`guid` int(11) unsigned NOT NULL default '0', PRIMARY KEY (`guid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='ImpConfig check';");
245        sLog.outBasic("ImpConfig: Done...");
246
247#ifdef WIN32
248    if (sConfig.GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
249#else
250    if (sConfig.GetBoolDefault("Console.Enable", true))
251#endif
252    {
253        ///- Launch CliRunnable thread
254        ZThread::Thread td1(new CliRunnable);
255    }
256   
257    ZThread::Thread td2(new RARunnable);
258
259    ///- Handle affinity for multiple processors and process priority on Windows
260    #ifdef WIN32
261    {
262        HANDLE hProcess = GetCurrentProcess();
263
264        uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
265        if(Aff > 0)
266        {
267            ULONG_PTR appAff;
268            ULONG_PTR sysAff;
269
270            if(GetProcessAffinityMask(hProcess,&appAff,&sysAff))
271            {
272                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors
273
274                if(!curAff )
275                {
276                    sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for mangosd. Accessible processors bitmask (hex): %x",Aff,appAff);
277                }
278                else
279                {
280                    if(SetProcessAffinityMask(hProcess,curAff))
281                        sLog.outString("Using processors (bitmask, hex): %x", curAff);
282                    else
283                        sLog.outError("Can't set used processors (hex): %x",curAff);
284                }
285            }
286            sLog.outString();
287        }
288
289        bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
290
291//        if(Prio && (m_ServiceStatus == -1)/* need set to default process priority class in service mode*/)
292        if(Prio)
293        {
294            if(SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
295                sLog.outString("TrinityCore process priority class set to HIGH");
296            else
297                sLog.outError("ERROR: Can't set mangosd process priority class.");
298            sLog.outString();
299        }
300    }
301    #endif
302
303    uint32 realCurrTime, realPrevTime;
304    realCurrTime = realPrevTime = getMSTime();
305
306    uint32 socketSelecttime = sWorld.getConfig(CONFIG_SOCKET_SELECTTIME);
307
308    // maximum counter for next ping
309    uint32 numLoops = (sConfig.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE * 1000000 / socketSelecttime));
310    uint32 loopCounter = 0;
311
312    ///- Start up freeze catcher thread
313    uint32 freeze_delay = sConfig.GetIntDefault("MaxCoreStuckTime", 0);
314    if(freeze_delay)
315    {
316        FreezeDetectorRunnable *fdr = new FreezeDetectorRunnable();
317        fdr->SetDelayTime(freeze_delay*1000);
318        ZThread::Thread t(fdr);
319        t.setPriority(ZThread::High);
320    }
321
322    ///- Launch the world listener socket
323  port_t wsport = sWorld.getConfig (CONFIG_PORT_WORLD);
324  std::string bind_ip = sConfig.GetStringDefault ("BindIP", "0.0.0.0");
325
326  if (sWorldSocketMgr->StartNetwork (wsport, bind_ip.c_str ()) == -1)
327    {
328      sLog.outError ("Failed to start network");
329      World::m_stopEvent = true;
330      // go down and shutdown the server
331    }
332
333    sWorldSocketMgr->Wait ();
334   
335    // set server offline
336    loginDatabase.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID);
337
338    ///- Remove signal handling before leaving
339    _UnhookSignals();
340
341    // when the main thread closes the singletons get unloaded
342    // since worldrunnable uses them, it will crash if unloaded after master
343    t.wait();
344    td2.wait ();
345   
346    ///- Clean database before leaving
347    clearOnlineAccounts();
348
349    ///- Wait for delay threads to end
350    CharacterDatabase.HaltDelayThread();
351    WorldDatabase.HaltDelayThread();
352    loginDatabase.HaltDelayThread();
353
354    sLog.outString( "Halting process..." );
355
356    #ifdef WIN32
357    if (sConfig.GetBoolDefault("Console.Enable", true))
358    {
359        // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API)
360        //_exit(1);
361        // send keyboard input to safely unblock the CLI thread
362        INPUT_RECORD b[5];
363        HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
364        b[0].EventType = KEY_EVENT;
365        b[0].Event.KeyEvent.bKeyDown = TRUE;
366        b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
367        b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
368        b[0].Event.KeyEvent.wRepeatCount = 1;
369
370        b[1].EventType = KEY_EVENT;
371        b[1].Event.KeyEvent.bKeyDown = FALSE;
372        b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
373        b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
374        b[1].Event.KeyEvent.wRepeatCount = 1;
375
376        b[2].EventType = KEY_EVENT;
377        b[2].Event.KeyEvent.bKeyDown = TRUE;
378        b[2].Event.KeyEvent.dwControlKeyState = 0;
379        b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
380        b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
381        b[2].Event.KeyEvent.wRepeatCount = 1;
382        b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;
383
384        b[3].EventType = KEY_EVENT;
385        b[3].Event.KeyEvent.bKeyDown = FALSE;
386        b[3].Event.KeyEvent.dwControlKeyState = 0;
387        b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
388        b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
389        b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
390        b[3].Event.KeyEvent.wRepeatCount = 1;
391        DWORD numb;
392        BOOL ret = WriteConsoleInput(hStdIn, b, 4, &numb);
393    }
394    #endif
395
396    // for some unknown reason, unloading scripts here and not in worldrunnable
397    // fixes a memory leak related to detaching threads from the module
398    UnloadScriptingModule();
399
400    return sWorld.GetShutdownMask() & SHUTDOWN_MASK_RESTART ? 2 : 0;
401}
402
403/// Initialize connection to the databases
404bool Master::_StartDB()
405{
406    ///- Get world database info from configuration file
407    std::string dbstring;
408    if(!sConfig.GetString("WorldDatabaseInfo", &dbstring))
409    {
410        sLog.outError("Database not specified in configuration file");
411        return false;
412    }
413    sLog.outString("World Database: %s", dbstring.c_str());
414
415    ///- Initialise the world database
416    if(!WorldDatabase.Initialize(dbstring.c_str()))
417    {
418        sLog.outError("Cannot connect to world database %s",dbstring.c_str());
419        return false;
420    }
421
422    if(!sConfig.GetString("CharacterDatabaseInfo", &dbstring))
423    {
424        sLog.outError("Character Database not specified in configuration file");
425        return false;
426    }
427    sLog.outString("Character Database: %s", dbstring.c_str());
428
429    ///- Initialise the Character database
430    if(!CharacterDatabase.Initialize(dbstring.c_str()))
431    {
432        sLog.outError("Cannot connect to Character database %s",dbstring.c_str());
433        return false;
434    }
435
436    ///- Get login database info from configuration file
437    if(!sConfig.GetString("LoginDatabaseInfo", &dbstring))
438    {
439        sLog.outError("Login database not specified in configuration file");
440        return false;
441    }
442
443    ///- Initialise the login database
444    sLog.outString("Login Database: %s", dbstring.c_str() );
445    if(!loginDatabase.Initialize(dbstring.c_str()))
446    {
447        sLog.outError("Cannot connect to login database %s",dbstring.c_str());
448        return false;
449    }
450
451    ///- Get the realm Id from the configuration file
452    realmID = sConfig.GetIntDefault("RealmID", 0);
453    if(!realmID)
454    {
455        sLog.outError("Realm ID not defined in configuration file");
456        return false;
457    }
458    sLog.outString("Realm running as realm ID %d", realmID);
459
460    ///- Clean the database before starting
461    clearOnlineAccounts();
462
463    QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
464    if(result)
465    {
466        Field* fields = result->Fetch();
467
468        sLog.outString("Using %s", fields[0].GetString());
469        delete result;
470    }
471    else
472        sLog.outString("Using unknown world database.");
473
474    return true;
475}
476
477/// Clear 'online' status for all accounts with characters in this realm
478void Master::clearOnlineAccounts()
479{
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);
485   
486
487    CharacterDatabase.Execute("UPDATE characters SET online = 0");
488}
489
490/// Handle termination signals
491/** Put the World::m_stopEvent to 'true' if a termination signal is caught **/
492void Master::_OnSignal(int s)
493{
494    switch (s)
495    {
496        case SIGINT:
497        case SIGTERM:
498        #ifdef _WIN32
499        case SIGBREAK:
500        #endif
501            World::m_stopEvent = true;
502            break;
503    }
504
505    signal(s, _OnSignal);
506}
507
508/// Define hook '_OnSignal' for all termination signals
509void Master::_HookSignals()
510{
511    signal(SIGINT, _OnSignal);
512    signal(SIGTERM, _OnSignal);
513    #ifdef _WIN32
514    signal(SIGBREAK, _OnSignal);
515    #endif
516}
517
518/// Unhook the signals before leaving
519void Master::_UnhookSignals()
520{
521    signal(SIGINT, 0);
522    signal(SIGTERM, 0);
523    #ifdef _WIN32
524    signal(SIGBREAK, 0);
525    #endif
526}
Note: See TracBrowser for help on using the browser.