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

Revision 102, 16.2 kB (checked in by yumileroy, 17 years ago)

[svn] Fixed copyright notices to comply with GPL.

Original author: w12x
Date: 2008-10-23 03:29:52-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21/** \file
22    \ingroup Trinityd
23*/
24
25#include <ace/OS_NS_signal.h>
26
27#include "WorldSocketMgr.h"
28#include "Common.h"
29#include "Master.h"
30#include "WorldSocket.h"
31#include "WorldRunnable.h"
32#include "World.h"
33#include "Log.h"
34#include "Timer.h"
35#include "Policies/SingletonImp.h"
36#include "SystemConfig.h"
37#include "Config/ConfigEnv.h"
38#include "Database/DatabaseEnv.h"
39#include "CliRunnable.h"
40#include "RASocket.h"
41#include "ScriptCalls.h"
42#include "Util.h"
43
44#include "sockets/TcpSocket.h"
45#include "sockets/Utility.h"
46#include "sockets/Parse.h"
47#include "sockets/Socket.h"
48#include "sockets/SocketHandler.h"
49#include "sockets/ListenSocket.h"
50
51#ifdef WIN32
52#include "ServiceWin32.h"
53extern int m_ServiceStatus;
54#endif
55
56/// \todo Warning disabling not useful under VC++2005. Can somebody say on which compiler it is useful?
57#pragma warning(disable:4305)
58
59INSTANTIATE_SINGLETON_1( Master );
60
61volatile uint32 Master::m_masterLoopCounter = 0;
62
63class FreezeDetectorRunnable : public ZThread::Runnable
64{
65public:
66    FreezeDetectorRunnable() { _delaytime = 0; }
67    uint32 m_loops, m_lastchange;
68    uint32 w_loops, w_lastchange;
69    uint32 _delaytime;
70    void SetDelayTime(uint32 t) { _delaytime = t; }
71    void run(void)
72    {
73        if(!_delaytime)
74            return;
75        sLog.outString("Starting up anti-freeze thread (%u seconds max stuck time)...",_delaytime/1000);
76        m_loops = 0;
77        w_loops = 0;
78        m_lastchange = 0;
79        w_lastchange = 0;
80        while(!World::m_stopEvent)
81        {
82            ZThread::Thread::sleep(1000);
83            uint32 curtime = getMSTime();
84            //DEBUG_LOG("anti-freeze: time=%u, counters=[%u; %u]",curtime,Master::m_masterLoopCounter,World::m_worldLoopCounter);
85
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//            }
100
101            // normal work
102            if(w_loops != World::m_worldLoopCounter)
103            {
104                w_lastchange = curtime;
105                w_loops = World::m_worldLoopCounter;
106            }
107            // possible freeze
108            else if(getMSTimeDiff(w_lastchange,curtime) > _delaytime)
109            {
110                sLog.outError("World Thread hangs, kicking out server!");
111                *((uint32 volatile*)NULL) = 0;                       // bang crash
112            }
113        }
114        sLog.outString("Anti-freeze thread exiting without problems.");
115    }
116};
117
118class RARunnable : public ZThread::Runnable
119{
120public:
121  uint32 numLoops, loopCounter;
122
123  RARunnable ()
124  {
125    uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
126    numLoops = (sConfig.GetIntDefault ("MaxPingTime", 30) * (MINUTE * 1000000 / socketSelecttime));
127    loopCounter = 0;
128  }
129
130  void
131  checkping ()
132  {
133    // ping if need
134    if ((++loopCounter) == numLoops)
135      {
136        loopCounter = 0;
137        sLog.outDetail ("Ping MySQL to keep connection alive");
138        delete WorldDatabase.Query ("SELECT 1 FROM command LIMIT 1");
139        delete loginDatabase.Query ("SELECT 1 FROM realmlist LIMIT 1");
140        delete CharacterDatabase.Query ("SELECT 1 FROM bugreport LIMIT 1");
141      }
142  }
143
144  void
145  run (void)
146  {
147    SocketHandler h;
148
149    // Launch the RA listener socket
150    ListenSocket<RASocket> RAListenSocket (h);
151    bool usera = sConfig.GetBoolDefault ("Ra.Enable", false);
152
153    if (usera)
154      {
155        port_t raport = sConfig.GetIntDefault ("Ra.Port", 3443);
156        std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0");
157        ipaddr_t raip;
158        if (!Utility::u2ip (stringip, raip))
159          sLog.outError ("Trinity RA can not bind to ip %s", stringip.c_str ());
160        else if (RAListenSocket.Bind (raip, raport))
161          sLog.outError ("Trinity RA can not bind to port %d on %s", raport, stringip.c_str ());
162        else
163          {
164            h.Add (&RAListenSocket);
165
166            sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ());
167          }
168      }
169
170    // Socket Selet time is in microseconds , not miliseconds!!
171    uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);
172
173    // if use ra spend time waiting for io, if not use ra ,just sleep
174    if (usera)
175      while (!World::m_stopEvent)
176        {
177          h.Select (0, socketSelecttime);
178          checkping ();
179        }
180    else
181      while (!World::m_stopEvent)
182        {
183          ZThread::Thread::sleep (static_cast<unsigned long> (socketSelecttime / 1000));
184          checkping ();
185        }
186  }
187};
188
189Master::Master()
190{
191}
192
193Master::~Master()
194{
195}
196
197/// Main function
198int Master::Run()
199{
200    sLog.outString( "%s (core-daemon)", _FULLVERSION );
201    sLog.outString( "<Ctrl-C> to stop.\n" );
202
203    sLog.outTitle( " ______                       __");
204    sLog.outTitle( "/\\__  _\\       __          __/\\ \\__");
205    sLog.outTitle( "\\/_/\\ \\/ _ __ /\\_\\    ___ /\\_\\ \\ ,_\\  __  __");
206    sLog.outTitle( "   \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\");
207    sLog.outTitle( "    \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\");
208    sLog.outTitle( "     \\ \\_\\ \\_\\  \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\");
209    sLog.outTitle( "      \\/_/\\/_/   \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\");
210    sLog.outTitle( "                                 C O R E  /\\___/");
211    sLog.outTitle( "http://TrinityCore.org                    \\/__/\n");
212
213    /// worldd PID file creation
214    std::string pidfile = sConfig.GetStringDefault("PidFile", "");
215    if(!pidfile.empty())
216    {
217        uint32 pid = CreatePIDFile(pidfile);
218        if( !pid )
219        {
220            sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str() );
221            return 1;
222        }
223
224        sLog.outString( "Daemon PID: %u\n", pid );
225    }
226
227    ///- Start the databases
228    if (!_StartDB())
229        return 1;
230
231    ///- Initialize the World
232    sWorld.SetInitialWorldSettings();
233
234    ///- Catch termination signals
235    _HookSignals();
236
237    ///- Launch WorldRunnable thread
238    ZThread::Thread t(new WorldRunnable);
239    t.setPriority ((ZThread::Priority )2);
240
241    // set server online
242    loginDatabase.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID);
243
244#ifdef WIN32
245    if (sConfig.GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
246#else
247    if (sConfig.GetBoolDefault("Console.Enable", true))
248#endif
249    {
250        ///- Launch CliRunnable thread
251        ZThread::Thread td1(new CliRunnable);
252    }
253   
254    ZThread::Thread td2(new RARunnable);
255
256    ///- Handle affinity for multiple processors and process priority on Windows
257    #ifdef WIN32
258    {
259        HANDLE hProcess = GetCurrentProcess();
260
261        uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
262        if(Aff > 0)
263        {
264            ULONG_PTR appAff;
265            ULONG_PTR sysAff;
266
267            if(GetProcessAffinityMask(hProcess,&appAff,&sysAff))
268            {
269                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors
270
271                if(!curAff )
272                {
273                    sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for Trinityd. Accessible processors bitmask (hex): %x",Aff,appAff);
274                }
275                else
276                {
277                    if(SetProcessAffinityMask(hProcess,curAff))
278                        sLog.outString("Using processors (bitmask, hex): %x", curAff);
279                    else
280                        sLog.outError("Can't set used processors (hex): %x",curAff);
281                }
282            }
283            sLog.outString();
284        }
285
286        bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
287
288//        if(Prio && (m_ServiceStatus == -1)/* need set to default process priority class in service mode*/)
289        if(Prio)
290        {
291            if(SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
292                sLog.outString("TrinityCore process priority class set to HIGH");
293            else
294                sLog.outError("ERROR: Can't set Trinityd process priority class.");
295            sLog.outString();
296        }
297    }
298    #endif
299
300    uint32 realCurrTime, realPrevTime;
301    realCurrTime = realPrevTime = getMSTime();
302
303    uint32 socketSelecttime = sWorld.getConfig(CONFIG_SOCKET_SELECTTIME);
304
305    // maximum counter for next ping
306    uint32 numLoops = (sConfig.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE * 1000000 / socketSelecttime));
307    uint32 loopCounter = 0;
308
309    ///- Start up freeze catcher thread
310    uint32 freeze_delay = sConfig.GetIntDefault("MaxCoreStuckTime", 0);
311    if(freeze_delay)
312    {
313        FreezeDetectorRunnable *fdr = new FreezeDetectorRunnable();
314        fdr->SetDelayTime(freeze_delay*1000);
315        ZThread::Thread t(fdr);
316        t.setPriority(ZThread::High);
317    }
318
319    ///- Launch the world listener socket
320  port_t wsport = sWorld.getConfig (CONFIG_PORT_WORLD);
321  std::string bind_ip = sConfig.GetStringDefault ("BindIP", "0.0.0.0");
322
323  if (sWorldSocketMgr->StartNetwork (wsport, bind_ip.c_str ()) == -1)
324    {
325      sLog.outError ("Failed to start network");
326      World::m_stopEvent = true;
327      // go down and shutdown the server
328    }
329
330    sWorldSocketMgr->Wait ();
331   
332    // set server offline
333    loginDatabase.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID);
334
335    ///- Remove signal handling before leaving
336    _UnhookSignals();
337
338    // when the main thread closes the singletons get unloaded
339    // since worldrunnable uses them, it will crash if unloaded after master
340    t.wait();
341    td2.wait ();
342   
343    ///- Clean database before leaving
344    clearOnlineAccounts();
345
346    ///- Wait for delay threads to end
347    CharacterDatabase.HaltDelayThread();
348    WorldDatabase.HaltDelayThread();
349    loginDatabase.HaltDelayThread();
350
351    sLog.outString( "Halting process..." );
352
353    #ifdef WIN32
354    if (sConfig.GetBoolDefault("Console.Enable", true))
355    {
356        // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API)
357        //_exit(1);
358        // send keyboard input to safely unblock the CLI thread
359        INPUT_RECORD b[5];
360        HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
361        b[0].EventType = KEY_EVENT;
362        b[0].Event.KeyEvent.bKeyDown = TRUE;
363        b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
364        b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
365        b[0].Event.KeyEvent.wRepeatCount = 1;
366
367        b[1].EventType = KEY_EVENT;
368        b[1].Event.KeyEvent.bKeyDown = FALSE;
369        b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
370        b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
371        b[1].Event.KeyEvent.wRepeatCount = 1;
372
373        b[2].EventType = KEY_EVENT;
374        b[2].Event.KeyEvent.bKeyDown = TRUE;
375        b[2].Event.KeyEvent.dwControlKeyState = 0;
376        b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
377        b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
378        b[2].Event.KeyEvent.wRepeatCount = 1;
379        b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;
380
381        b[3].EventType = KEY_EVENT;
382        b[3].Event.KeyEvent.bKeyDown = FALSE;
383        b[3].Event.KeyEvent.dwControlKeyState = 0;
384        b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
385        b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
386        b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
387        b[3].Event.KeyEvent.wRepeatCount = 1;
388        DWORD numb;
389        BOOL ret = WriteConsoleInput(hStdIn, b, 4, &numb);
390    }
391    #endif
392
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();
396
397    return sWorld.GetShutdownMask() & SHUTDOWN_MASK_RESTART ? 2 : 0;
398}
399
400/// Initialize connection to the databases
401bool Master::_StartDB()
402{
403    ///- Get world database info from configuration file
404    std::string dbstring;
405    if(!sConfig.GetString("WorldDatabaseInfo", &dbstring))
406    {
407        sLog.outError("Database not specified in configuration file");
408        return false;
409    }
410    sLog.outString("World Database: %s", dbstring.c_str());
411
412    ///- Initialise the world database
413    if(!WorldDatabase.Initialize(dbstring.c_str()))
414    {
415        sLog.outError("Cannot connect to world database %s",dbstring.c_str());
416        return false;
417    }
418
419    if(!sConfig.GetString("CharacterDatabaseInfo", &dbstring))
420    {
421        sLog.outError("Character Database not specified in configuration file");
422        return false;
423    }
424    sLog.outString("Character Database: %s", dbstring.c_str());
425
426    ///- Initialise the Character database
427    if(!CharacterDatabase.Initialize(dbstring.c_str()))
428    {
429        sLog.outError("Cannot connect to Character database %s",dbstring.c_str());
430        return false;
431    }
432
433    ///- Get login database info from configuration file
434    if(!sConfig.GetString("LoginDatabaseInfo", &dbstring))
435    {
436        sLog.outError("Login database not specified in configuration file");
437        return false;
438    }
439
440    ///- Initialise the login database
441    sLog.outString("Login Database: %s", dbstring.c_str() );
442    if(!loginDatabase.Initialize(dbstring.c_str()))
443    {
444        sLog.outError("Cannot connect to login database %s",dbstring.c_str());
445        return false;
446    }
447
448    ///- Get the realm Id from the configuration file
449    realmID = sConfig.GetIntDefault("RealmID", 0);
450    if(!realmID)
451    {
452        sLog.outError("Realm ID not defined in configuration file");
453        return false;
454    }
455    sLog.outString("Realm running as realm ID %d", realmID);
456
457    ///- Clean the database before starting
458    clearOnlineAccounts();
459
460    QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
461    if(result)
462    {
463        Field* fields = result->Fetch();
464
465        sLog.outString("Using %s", fields[0].GetString());
466        delete result;
467    }
468    else
469        sLog.outString("Using unknown world database.");
470
471    return true;
472}
473
474/// Clear 'online' status for all accounts with characters in this realm
475void Master::clearOnlineAccounts()
476{
477    // Cleanup online status for characters hosted at current realm
478    /// \todo Only accounts with characters logged on *this* realm should have online status reset. Move the online column from 'account' to 'realmcharacters'?
479    loginDatabase.PExecute(
480        "UPDATE account SET online = 0 WHERE online > 0 "
481        "AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = '%d')",realmID);
482   
483
484    CharacterDatabase.Execute("UPDATE characters SET online = 0");
485}
486
487/// Handle termination signals
488/** Put the World::m_stopEvent to 'true' if a termination signal is caught **/
489void Master::_OnSignal(int s)
490{
491    switch (s)
492    {
493        case SIGINT:
494        case SIGTERM:
495        #ifdef _WIN32
496        case SIGBREAK:
497        #endif
498            World::m_stopEvent = true;
499            break;
500    }
501
502    signal(s, _OnSignal);
503}
504
505/// Define hook '_OnSignal' for all termination signals
506void Master::_HookSignals()
507{
508    signal(SIGINT, _OnSignal);
509    signal(SIGTERM, _OnSignal);
510    #ifdef _WIN32
511    signal(SIGBREAK, _OnSignal);
512    #endif
513}
514
515/// Unhook the signals before leaving
516void Master::_UnhookSignals()
517{
518    signal(SIGINT, 0);
519    signal(SIGTERM, 0);
520    #ifdef _WIN32
521    signal(SIGBREAK, 0);
522    #endif
523}
Note: See TracBrowser for help on using the browser.