Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.52 KB | None | 0 0
  1. // RAServerController.cpp : main Windows Service project file.
  2.  
  3. #include "stdafx.h"
  4. #include "RAServerController.h"
  5. #include "Global.h"
  6. #include "GameServerDescriptor.h"
  7. #include "MonitorDescriptor.h"
  8. #include "smallobj/SmallObj.h"
  9.  
  10. #undef GetCurrentDirectory
  11. // ************************************************************************************************************************************************************
  12. #define MAIN_THREAD_SLEEP_TIME_GAP 200
  13. #define PERFORMANCE_MEASURE_TIME_GAP 500        // 500 ms
  14. #define COUNTER_SERVER_TIME_GAP 600000          // 10 min
  15.  
  16. // ************************************************************************************************************************************************************
  17.  
  18. using namespace Runewaker;
  19.  
  20. // ************************************************************************************************************************************************************
  21.  
  22. //To install/uninstall the service, type: "RAServerController.exe -Install [-u]"
  23. int _tmain(int argc, _TCHAR* argv[])
  24. {
  25. #ifndef _DEBUG
  26.     if (argc >= 2)
  27.     {
  28.         if (argv[1][0] == _T('/'))
  29.         {
  30.             argv[1][0] = _T('-');
  31.         }
  32.  
  33.         if (_tcsicmp(argv[1], _T("-Install")) == 0)
  34.         {
  35.             array<String^>^ myargs = System::Environment::GetCommandLineArgs();
  36.             array<String^>^ args = gcnew array<String^>(myargs->Length - 1);
  37.  
  38.             // Set args[0] with the full path to the assembly,
  39.             Assembly^ assem = Assembly::GetExecutingAssembly();
  40.             args[0] = assem->Location;
  41.  
  42.             Array::Copy(myargs, 2, args, 1, args->Length - 1);
  43.             AppDomain^ dom = AppDomain::CreateDomain(L"execDom");
  44.             Type^ type = System::Object::typeid;
  45.             String^ path = type->Assembly->Location;
  46.             StringBuilder^ sb = gcnew StringBuilder(path->Substring(0, path->LastIndexOf(L"\\")));
  47.             sb->Append(L"\\InstallUtil.exe");
  48.             Evidence^ evidence = gcnew Evidence();
  49.             dom->ExecuteAssembly(sb->ToString(), evidence, args);
  50.         }
  51.     }
  52.     else
  53.     {
  54.         //----------------------------------------------------------------------
  55.         // Change Current Working Directory
  56.         System::Diagnostics::Process^ p = System::Diagnostics::Process::GetCurrentProcess();
  57.         String^ moduleFileName          = p->MainModule->FileName;
  58.         String^ workingDirectory        = moduleFileName->Remove(moduleFileName->LastIndexOf("\\"));
  59.  
  60.         Directory::SetCurrentDirectory(workingDirectory);
  61.         //----------------------------------------------------------------------
  62.  
  63.         ServiceBase::Run(gcnew RAServerController());
  64.     }
  65. #else
  66.     System::Diagnostics::Process^ p = System::Diagnostics::Process::GetCurrentProcess();
  67.     String^ moduleFileName          = p->MainModule->FileName;
  68.     String^ workingDirectory        = moduleFileName->Remove(moduleFileName->LastIndexOf("\\"));
  69.  
  70.     Directory::SetCurrentDirectory(workingDirectory);
  71.  
  72.     RAServerController^ myService = gcnew RAServerController();
  73.     myService->onDebug();
  74.     System::Threading::Thread::Sleep(System::Threading::Timeout::Infinite);
  75. #endif
  76. }
  77. // ************************************************************************************************************************************************************
  78.  
  79. namespace Runewaker
  80. {
  81.     void RAServerController::onDebug()
  82.     {
  83.         OnStart(nullptr);
  84.     }
  85.     //---------------------------------------------------------------------------------------------------------------------
  86.     //
  87.     //---------------------------------------------------------------------------------------------------------------------
  88.     void RAServerController::OnStart(array<String^>^ args)
  89.     {
  90. #ifndef _DEBUG
  91.         //----------------------------------------------------------------------
  92.         // Initialize event log
  93.         System::String^ eventSource = "RA Server Controller";
  94.         System::String^ logName     = "RA Server Controller Log";
  95.  
  96.         // Verify that the event source exists
  97.         if(!Diagnostics::EventLog::SourceExists(eventSource))
  98.         {
  99.             // Create event source if it does not exist
  100.             Diagnostics::EventLog::CreateEventSource(eventSource, logName);
  101.         }
  102.  
  103.         m_log = gcnew Diagnostics::EventLog(logName);
  104.         m_log->Source = eventSource;
  105.  
  106.         // Modify overflow policy
  107.         m_log->ModifyOverflowPolicy(Diagnostics::OverflowAction::OverwriteAsNeeded, 7);
  108.  
  109.         //----------------------------------------------------------------------
  110.  
  111.         //----------------------------------------------------------------------
  112.         // Acquire registry key
  113.         m_configuratonFilePath = "";
  114.         RegistryKey ^softwareRegKey = Registry::LocalMachine->OpenSubKey("Software");
  115.         RegistryKey ^runewakerRegKey = softwareRegKey->OpenSubKey("Runewaker");
  116.  
  117.         if(runewakerRegKey)
  118.         {
  119.             RegistryKey ^raSrvCtrlRegKey = runewakerRegKey->OpenSubKey("RA Server Controller");
  120.  
  121.             if(raSrvCtrlRegKey)
  122.             {
  123.                 // Load program settings from registry
  124.                 m_configuratonFilePath = safe_cast<System::String ^>(raSrvCtrlRegKey->GetValue("Configuration File Path", ""));
  125.             }
  126.         }
  127.         //----------------------------------------------------------------------
  128.         RAServerController::LogEvent("Registry keys read, log object generated.", Diagnostics::EventLogEntryType::Information);            
  129. #else
  130.         System::Diagnostics::Process^ p = System::Diagnostics::Process::GetCurrentProcess();
  131.         String^ moduleFileName          = p->MainModule->FileName;
  132.         String^ workingDirectory        = moduleFileName->Remove(moduleFileName->LastIndexOf("\\"));
  133.  
  134.         m_configuratonFilePath = System::String::Format("{0}\\RAServerController.ini", workingDirectory);
  135.  
  136.         RAServerController::LogEvent("Configuration loaded.", Diagnostics::EventLogEntryType::Information);    
  137. #endif
  138.  
  139.         m_PerformanceCounter = gcnew PerformanceCounter("Processor", "% Processor Time", "_Total");
  140.  
  141.         //Global Init
  142.         Global::Init();
  143.  
  144.         LoadServerDescriptions();
  145.  
  146.         // Initialize service thread
  147.         Threading::ThreadStart ^threadStart = gcnew Threading::ThreadStart(this, &RAServerController::ServiceLoop);    
  148.         m_serviceThread = gcnew Threading::Thread(threadStart);
  149.         m_serviceThread->Start();
  150.  
  151.         RAServerController::LogEvent("Main service thread started.", Diagnostics::EventLogEntryType::Information);
  152.     }
  153.  
  154.     //---------------------------------------------------------------------------------------------------------------------
  155.     //
  156.     //---------------------------------------------------------------------------------------------------------------------
  157.     void RAServerController::OnStop()
  158.     {
  159.         //CNetService::OnStop();
  160.         RAServerController::m_stopping = true;
  161.         // Terminate servers
  162.  
  163.         PG_CtoM_ClearServerInfo Packet;
  164.         MonitorDescriptorManager::SendToAllMonitor(sizeof(Packet), &Packet);
  165.  
  166.         Global::Release();
  167.     }
  168.  
  169.     //---------------------------------------------------------------------------------------------------------------------
  170.     //
  171.     //---------------------------------------------------------------------------------------------------------------------
  172.     bool RAServerController::LogEvent(System::String ^eventString, Diagnostics::EventLogEntryType entryType)
  173.     {
  174. #ifndef _DEBUG
  175.         try
  176.         {
  177.             m_log->WriteEntry(eventString, entryType);
  178.         }
  179.         catch (...)
  180.         {
  181.             return false;
  182.         }
  183. #else
  184.         System::String ^eventMessage = System::String::Format("[{0}] {1}\n", entryType, eventString);
  185.         printf(StringToChar(eventMessage));
  186. #endif
  187.  
  188.         return true;
  189.     }
  190.  
  191.     //---------------------------------------------------------------------------------------------------------------------
  192.     //
  193.     //---------------------------------------------------------------------------------------------------------------------
  194.     void RAServerController::ServiceLoop()
  195.     {
  196.         m_stopping = false;
  197.    
  198.         while(!m_stopping)
  199.         {
  200.             //check Schedular Event
  201.             SchedularEvent();
  202.  
  203.             //
  204.             Global::Process();
  205.  
  206.             // Sleep for some period of time
  207.             Threading::Thread::Sleep(MAIN_THREAD_SLEEP_TIME_GAP);
  208.         }      
  209.     }
  210.  
  211.     //---------------------------------------------------------------------------------------------------------------------
  212.     //
  213.     //---------------------------------------------------------------------------------------------------------------------
  214.     void RAServerController::SchedularEvent()
  215.     {
  216.         unsigned long dwNowTick = Global::GetNowTick();
  217.         unsigned long dwGap = 0;
  218.  
  219.         //-----------------------------------------------------------
  220.         if (GameServerDescriptorManager::LoadConfigRequest)
  221.         {
  222.             LoadServerDescriptions();
  223.         }
  224.         //-----------------------------------------------------------
  225.  
  226.         //-----------------------------------------------------------
  227.         if (GameServerDescriptorManager::SaveConfigRequest)
  228.         {
  229.             SaveServerDescriptions();
  230.         }
  231.         //-----------------------------------------------------------
  232.  
  233.         //-----------------------------------------------------------
  234.         // update Performance Counter
  235.         dwGap = dwNowTick - m_LastUpdatePerformanceCounterTick;
  236.         if (dwGap >= PERFORMANCE_MEASURE_TIME_GAP)
  237.         {
  238.             Global::UpdateGlobalPerformanceData((int)m_PerformanceCounter->NextValue());
  239.             m_LastUpdatePerformanceCounterTick = dwNowTick;
  240.         }
  241.         //-----------------------------------------------------------
  242.  
  243.         //-----------------------------------------------------------
  244.         // Log registered server count
  245.         dwGap = dwNowTick - m_LastCountServerTick;
  246.         if (dwGap >= COUNTER_SERVER_TIME_GAP)
  247.         {          
  248.             System::String ^eventMessage = System::String::Format("Registered server count is {0}.", GameServerDescriptorManager::GetServerCount());
  249.             LogEvent(eventMessage, Diagnostics::EventLogEntryType::Information);
  250.             m_LastCountServerTick = dwNowTick;
  251.         }
  252.         //-----------------------------------------------------------
  253.     }
  254.  
  255.     //---------------------------------------------------------------------------------------------------------------------
  256.     //
  257.     //---------------------------------------------------------------------------------------------------------------------
  258.     const char* RAServerController::StringToChar(String^ strValue)
  259.     {
  260.         static std::string Result = "";
  261.  
  262.         Encoding^ ec = Encoding::UTF8;
  263.         array<unsigned char>^ charArray = ec->GetBytes(strValue);
  264.         pin_ptr<char> pinnedChar = interior_ptr<char>(&charArray[0]);
  265.  
  266.         Result = pinnedChar;
  267.  
  268.         return Result.c_str();
  269.     }
  270.  
  271.     //---------------------------------------------------------------------------------------------------------------------
  272.     //
  273.     //---------------------------------------------------------------------------------------------------------------------
  274.     void RAServerController::LoadServerDescriptions()
  275.     {
  276.         std::vector<std::vector<std::string>>& vecDescs = GameServerDescriptorManager::vecLoadData;
  277.  
  278.         vecDescs.clear();
  279.  
  280.         String ^line = nullptr;
  281.         String^ strSplitor = "\t\"";
  282.  
  283.         // Open configuration file
  284.         if(File::Exists(m_configuratonFilePath))
  285.         {
  286.             StreamReader ^reader = File::OpenText(m_configuratonFilePath);
  287.  
  288.             // Read all lines in configuration file
  289.             while ((line = reader->ReadLine()) != nullptr)
  290.             {
  291.                 array<String^>^ arrayParas = line->Split(strSplitor->ToCharArray(), StringSplitOptions::RemoveEmptyEntries);
  292.  
  293.                 if (arrayParas->Length >= 5)
  294.                 {
  295.                     std::vector<std::string> vecTmp;
  296.                     vecTmp.clear();
  297.                     vecDescs.push_back(vecTmp);
  298.  
  299.                     std::vector<std::string>& vecParas = vecDescs[vecDescs.size() - 1];
  300.  
  301.                     System::Collections::IEnumerator^ enumParameters = arrayParas->GetEnumerator();
  302.  
  303.                     while ( (enumParameters->MoveNext()) && (enumParameters->Current != nullptr) )
  304.                     {
  305.                         std::string strTmp = StringToChar(dynamic_cast<System::String ^>(enumParameters->Current));
  306.                         vecParas.push_back(strTmp.c_str());
  307.                     }
  308.                 }
  309.             }
  310.  
  311.             reader->Close();
  312.         }
  313.  
  314.         GameServerDescriptorManager::LoadConfigRequest = false;
  315.         GameServerDescriptorManager::LoadServerDescription();
  316.  
  317.         unsigned long dwPacketSize = 0;
  318.         void* pData = GameServerDescriptorManager::GatherAllGameServerInfo(&dwPacketSize);
  319.  
  320.         MonitorDescriptorManager::SendToAllMonitor(dwPacketSize, pData);
  321.     }
  322.  
  323.     //---------------------------------------------------------------------------------------------------------------------
  324.     //
  325.     //---------------------------------------------------------------------------------------------------------------------
  326.     void RAServerController::SaveServerDescriptions()
  327.     {
  328.         std::vector<std::string>& vecDescs = GameServerDescriptorManager::vecSaveData;
  329.  
  330.         StringBuilder^ sb = gcnew StringBuilder(2048);
  331.  
  332.         for(int i = 0; i < (int)vecDescs.size(); ++i)
  333.         {
  334.             sb->Append(gcnew String(Utf8ToWchar(vecDescs[i].c_str()).c_str()));
  335.             sb->Append("\r\n");
  336.         }
  337.  
  338.         File::WriteAllText(m_configuratonFilePath, sb->ToString(), Encoding::Unicode);
  339.  
  340.         GameServerDescriptorManager::SaveConfigRequest = false;
  341.     }  
  342. }
  343. // ************************************************************************************************************************************************************
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement