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

Revision 39, 16.8 kB (checked in by yumileroy, 17 years ago)

[svn] * Various small changes here and there.
* Implementing MangChat? IRC system.
* Added new config option, MAX_WHO, can be used to set the limit of characters being sent in a /who request from client.

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