// mod_healthmanager.cpp : Defines the exported functions for the DLL application. #if (defined(_WIN32) || defined(_WIN64)) #include "stdafx.h" #include #include #include #include #include #define RVC_OS_WIN//oiltmp??? #else #include #include #include #include #include #include #endif //RVC_OS_WIN #include #include #include using namespace std; #include "mod_healthmanager.h" #include "GetDevInfoHelper.h" #pragma comment( lib, "advapi32.lib" ) const DWORD HEALTHMANAGER_TIMER_ID = 1; const DWORD HEALTHMANAGER_WD_TIMER_ID = 2; const DWORD HEALTHMANAGER_TIMER_INTERVAL = 60000; const DWORD HEALTHMANAGER_WD_TIMER_INTERVAL = 50000; const DWORD HEALTHMANAGER_TIMER_INTERVAL_MINUTE = (HEALTHMANAGER_TIMER_INTERVAL/60000)*3; //the following 20151009 #pragma comment(lib, "IPHLPAPI.lib") #define WORKING_BUFFER_SIZE 15000 #define MAX_TRIES 3 #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) #define FREE(x) HeapFree(GetProcessHeap(), 0, (x)) void GetLocalTimeRVC(SYSTEMTIME &stTime) { #ifdef RVC_OS_WIN GetLocalTime(&stTime); #else struct tm* pst = NULL; time_t t = time(NULL); pst = localtime(&t); stTime.wYear = pst->tm_year + 1900; stTime.wMonth = pst->tm_mon + 1;//because the range of tm_mon is:0-11 stTime.wDay = pst->tm_mday; stTime.wHour = pst->tm_hour; stTime.wMinute = pst->tm_min; stTime.wDayOfWeek = pst->tm_wday; stTime.wSecond = pst->tm_sec; stTime.wMilliseconds = 0; //Dbg("oiltest,time:%d,%d,%d,%d", stTime.wYear, stTime.wHour, stTime.wMinute, stTime.wDayOfWeek); #endif } template class TimerOutHelper : public ITimerListener { public: typedef void (T::*FuncTimer)(); TimerOutHelper(T *p, FuncTimer pTimerFunc, bool bDeleteSelf = false) : m_pObject(p), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf) {} virtual void OnTimeout(DWORD dwTimerID) { (m_pObject->*m_pTimer)(); if (m_bDeleteSelf) delete this; } private: T *m_pObject; FuncTimer m_pTimer; bool m_bDeleteSelf; }; void HealthManagerSession::Handle_EnterState(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->EnterState(ctx); } void HealthManagerSession::Handle_ExitState(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->ExitState(ctx); } void HealthManagerSession::Handle_DoEvent(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->DoEvent(ctx); } void HealthManagerSession::Handle_GetEntityCfgInfo(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->GetEntityCfgInfo(ctx); } void HealthManagerSession::Handle_GetNetworkState(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->GetNetworkState(ctx); } void HealthManagerSession::Handle_QueryHardwareInfo(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->QueryHardwareInfo(ctx); } void HealthManagerSession::Handle_ReadCenterConfigStr(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); } bool CHealthManagerEntity::DoWatchDog(WatchDogOp eOp) { switch(eOp) { case WD_OP_START: { if (m_pWatchDogClient == NULL) { m_pWatchDogClient = new WatchDogService_ClientBase(this); ErrorCodeEnum eErrConn = m_pWatchDogClient->Connect(); if (eErrConn != Error_Succeed) { Dbg("WatchDog connected failed."); //m_pWatchDogClient->SafeDelete(); m_pWatchDogClient = NULL; break; } else Dbg("WatchDog connected."); } WatchDogService_StartWatch_Req req; req.Delay = 120;//oiltmp req.Timeout = 60; WatchDogService_StartWatch_Ans ans; ErrorCodeEnum eErrStart = m_pWatchDogClient->StartWatch(req,ans,10000); if (eErrStart == Error_Succeed) m_bWatchDog = true; Dbg("start watch %d.",eErrStart); } break; case WD_OP_STOP: { if (!m_bWatchDog) break; WatchDogService_StopWatch_Req req; WatchDogService_StopWatch_Ans ans; ErrorCodeEnum eErrStop = m_pWatchDogClient->StopWatch(req,ans,10000); if (eErrStop == Error_Succeed) m_bWatchDog = false; Dbg("stop watchd %d.",eErrStop); } break; case WD_OP_REFRESH: { if (!m_bWatchDog) break; WatchDogService_Refresh_Req req; WatchDogService_Refresh_Ans ans; ErrorCodeEnum eErrRefresh = m_pWatchDogClient->Refresh(req,ans,10000); Dbg("refresh watchdog %d.",eErrRefresh); } break; default: break; } return true; } void CHealthManagerEntity::OnWatchDogTimeout() { xxx++; if (m_bWatchDog && xxx == 5) { DoWatchDog(WD_OP_STOP); //oiltmp Sleep(180000); Dbg("have sleep 18000,wake up."); //DoWatchDog(WD_OP_START); } else if (m_bWatchDog && xxx<5) { DoWatchDog(WD_OP_REFRESH); GetFunction()->ResetTimer(HEALTHMANAGER_WD_TIMER_ID, HEALTHMANAGER_WD_TIMER_INTERVAL); } } int CHealthManagerEntity::SystemRestart(bool bPeriod, bool bImmediately,bool bNow) { if (bPeriod) { Dbg("restart periodly."); m_restartTimes = 0; } if (bNow) { m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay); int x = SystemShutdown(TRUE); Dbg("From ie to shutdown %d",x); return 0; } SYSTEMTIME localTime; GetLocalTimeRVC(localTime); CSmartPointer spConfigRun; ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Run, spConfigRun); if (err != Error_Succeed) { LOG_TRACE("open cfg file failed!"); return -1; } // //ups restart if (m_pUpsClient != NULL) { if (!m_bToRestart) { m_restartTimes++; if (m_restartTimes > m_maxRestartTimes) { Dbg("restart too many times(%d,%d),give up.",m_restartTimes,m_maxRestartTimes); m_restartTimes--; return -1; } Dbg("the %d restart.",m_restartTimes); spConfigRun->WriteConfigValueInt("Run","RestartTimes",m_restartTimes); if (m_lastHour != localTime.wHour) { m_lastHour = localTime.wHour; Dbg("set last hour to %d", m_lastHour); spConfigRun->WriteConfigValueInt("Run", "LastHour", m_lastHour); } } else return 0; UpsService_Shutdown_Req req; UpsService_Shutdown_Ans ans; if (bImmediately) { req.ShutdownTime = 1; req.UpTime = 1; } else { req.ShutdownTime = 1;//oiltmp req.UpTime = 3; //oiltmp } ErrorCodeEnum eErrShutdown = m_pUpsClient->Shutdown(req,ans,10000); if (eErrShutdown == Error_Succeed) { //m_lastHour = localTime.wHour; Dbg("to shutdown"); m_bToRestart = true; Sleep(20000); m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger,m_eRebootWay); int ret; if (m_bGetUpsStateFlag) ret = SystemShutdown(); else ret = SystemShutdown(TRUE); Dbg("after ups,SystemShutdown result %d",ret); } else Dbg("shutdown failed(%d)",eErrShutdown); } else { Dbg("no ups,so to restart directly."); if (!m_bToRestart) { m_restartTimes++; if (m_restartTimes > m_maxRestartTimes) { Dbg("restart too many times(%d,%d),give up.",m_restartTimes,m_maxRestartTimes); m_restartTimes--; return -1; } Dbg("the %d restart.",m_restartTimes); spConfigRun->WriteConfigValueInt("Run","RestartTimes",m_restartTimes); if (m_lastHour != localTime.wHour) { m_lastHour = localTime.wHour; Dbg("set last hour to %d", m_lastHour); spConfigRun->WriteConfigValueInt("Run", "LastHour", m_lastHour); } //oilyang 20140606 //framework to reboot os //int ret = SystemShutdown(TRUE); m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger,RebootWay_OS); //Dbg("no ups,SystemShutdown result %d",ret); } } return 0; } //system api shutdown int CHealthManagerEntity::SystemShutdown(BOOL bReboot) { #ifdef RVC_OS_WIN HANDLE hToken; // handle to process token TOKEN_PRIVILEGES tkp; // pointer to token structure BOOL fResult; // system shutdown flag // Get the current process token handle so we can get shutdown // privilege. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return FALSE; // Get the LUID for shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); // Cannot test the return value of AdjustTokenPrivileges. if (GetLastError() != ERROR_SUCCESS) return FALSE; // Display the shutdown dialog box and start the countdown. fResult = InitiateSystemShutdown( NULL, // shut down local computer NULL, // message for user 0, // time-out period, in seconds FALSE, // ask user to close apps bReboot); // reboot after shutdown if (!fResult) return FALSE; // Disable shutdown privilege. tkp.Privileges[0].Attributes = 0; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); return 0; #else sync(); if (bReboot) system("init 6"); else system("init 0"); return 0;//oiltestlinux #endif //RVC_OS_WIN } int CHealthManagerEntity::FrameworkShutdown(bool bRestart) { #ifdef RVC_OS_WIN STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); GetFunction()->FlushLogFile(); // LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\\Program Files\\MyApp\" -L -S")); //CreateProcess(NULL, szCmdline, /*...*/); // Start the child process. CSimpleStringA csRestart,csVerPath,csAll,csSep("\""),csBlank(" "),csScript("wscript.exe"),csReFlag("r"); csRestart = "sprestart.exe "; ErrorCodeEnum Error = GetFunction()->GetPath("RootVer", csVerPath); csVerPath +="\\spexplorerfast.vbs"; if (!bRestart) csReFlag = "n"; csAll = csSep + csRestart + csSep + csBlank + csSep + csScript+csBlank + csVerPath + csSep + csBlank + csSep + csReFlag + csSep; Dbg("allpath[%s]",(LPCTSTR)csAll); LPTSTR szCmdline = _strdup(csAll); if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)) { Dbg("CreateProcess failed (%d).\n", GetLastError()); return -1; } m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay); //MessageBoxA(0,0,0,0); DWORD dwErr = GetLastError(); // Wait until child process exits. WaitForSingleObject( pi.hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); return 0; #else return 0;//oiltestlinux #endif } //almost disused. //the function moved to Entity "SelfChecker" ErrorCodeEnum CHealthManagerEntity::RestartModule(const char* pEntityName) { CSmartPointer pFunc = GetFunction(); CSmartPointer pFuncPrivilege = pFunc.ConvertCase(); if (pFuncPrivilege == NULL) { Dbg("restart mc NoPrivilege"); return Error_NoPrivilege; } map::iterator it; it = m_modRunInfo.find(pEntityName); if (it == m_modRunInfo.end()) { Dbg("add %s to modfuninfo(%d).",pEntityName,m_modRunInfo.size()); m_modRunInfo[pEntityName].count = 1; m_modRunInfo[pEntityName].dwStart = GetTickCountRVC(); } else { Dbg("modruninfo size %d",m_modRunInfo.size()); Dbg("%d",m_modRunInfo[pEntityName].count); (m_modRunInfo[pEntityName].count)++; Dbg("%d",m_modRunInfo[pEntityName].count); } CSmartPointer spWait; ErrorCodeEnum eErrCode = Error_Succeed; eErrCode = pFuncPrivilege->TerminateEntity(pEntityName,spWait); if (spWait != NULL) eErrCode = spWait->WaitAnswer(10000); if (eErrCode != Error_Succeed) { Dbg("kill %s %d",pEntityName,eErrCode); return eErrCode; } Sleep(3000); eErrCode = pFuncPrivilege->StartEntity(pEntityName,NULL,spWait); if (spWait != NULL) eErrCode = spWait->WaitAnswer(10000); if (eErrCode != Error_Succeed) { Dbg("start %s %d",pEntityName,eErrCode); return eErrCode; } //m_modRestartCount++; //if (m_modRestartCount == 1) // m_MCStart = GetTickCount(); DWORD dwMaxTimes,dwInternal; if (m_modCfgInfo.find(pEntityName) == m_modCfgInfo.end()) { dwMaxTimes = m_restartMode[RESTART_MODE_DEFAULT].dwTimes; dwInternal = m_restartMode[RESTART_MODE_DEFAULT].dwInternal; } else { dwMaxTimes = m_restartMode[m_modCfgInfo[pEntityName]].dwTimes; dwInternal = m_restartMode[m_modCfgInfo[pEntityName]].dwInternal; } Dbg("%d,%d,%s restart %d times",dwMaxTimes,dwInternal,pEntityName,m_modRunInfo[pEntityName].count); if (m_modRunInfo[pEntityName].count > dwMaxTimes) { m_MCEnd = GetTickCountRVC(); if (m_MCEnd-m_modRunInfo[pEntityName].dwStart < dwInternal) { Dbg("wait chance to restart pc."); if (_strnicmp(pEntityName, "FaceTracking", strlen("FaceTracking")) != 0) m_bWaitRestartPC = true; } else { m_modRunInfo[pEntityName].dwStart = m_MCEnd; m_modRunInfo[pEntityName].count = 0; LogWarn(Severity_Low,Error_Unexpect,LOG_WARN_HEALTH_MODULE_RESTART_TIMES ,"restart x times in more than 10mins"); } } return eErrCode; } void CHealthManagerEntity::AfterWaitRestartPC() { ReadMachineDataBySyncSerivce(); Dbg("menu:[%s]",(LPCTSTR)m_menuChoice); CSmartPointer pFunc = GetFunction(); CSmartPointer pFuncPrivilege = pFunc.ConvertCase(); if (pFuncPrivilege == NULL) { Dbg("restart pc NoPrivilege"); return; } ErrorCodeEnum eErr; CSimpleStringA csCustomerHandle(""); eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle); Dbg("cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle); if (eErr != Error_Succeed) { Dbg("get CustomerHandle failed (%d).",eErr); } else if (csCustomerHandle[0] == 'N') { m_bWaitRestartPC = false; pFuncPrivilege->DisplayBlueScreen("暂停服务test"); Dbg("time comes,restart machine"); m_eRebootTrigger = RebootTrigger_RunExcepition; m_eRebootWay = RebootWay_Power; SystemRestart(false, true); } } void CHealthManagerEntity::UpsSupplyLockScreen() { ErrorCodeEnum eErr; CSimpleStringA csCustomerHandle(""); eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle); Dbg("upslockscreen cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle); if (eErr != Error_Succeed) { Dbg("get CustomerHandle failed (%d).",eErr); } else// if (csCustomerHandle[0] == 'N') { CSmartPointer pFunc = GetFunction(); CSmartPointer pFuncPrivilege = pFunc.ConvertCase(); if (pFuncPrivilege == NULL) { Dbg("display screen NoPrivilege"); return; } pFuncPrivilege->DisplayBlueScreen("暂停服务"); LogEvent(Severity_High,LOG_EVT_HEALTH_UPS_NO_ELECTOR,"ups no elector,to shutdown machine"); Dbg("ups no elector,display screen."); //oiltmp eject card and sth else Sleep(30000); if (m_bUpsWaitLock) { m_bUpsWaitLock = false; m_bScreenLock = true; int ret = SystemShutdown(); Dbg("SystemShutdown result %d",ret); } else { pFuncPrivilege->UndisplayBlueScreen(); m_bUpsWaitLock = false; m_bScreenLock = false; } } } void CHealthManagerEntity::OnCheckTimeTimeout() { if (m_bNeedToRestartIE) { //oilyang 20160704 //to judge in main page & the phone is offline CSimpleStringA csCustHandle(""); ErrorCodeEnum eErr = Error_Unexpect; eErr = GetFunction()->GetSysVar("CustomerHandle", csCustHandle); if (eErr == Error_Succeed) { if (csCustHandle.Compare("C") != 0 && csCustHandle.Compare("T") != 0 && csCustHandle.Compare("G") != 0) { if (m_bInMainPage) { Dbg("to restart iebrowser."); RestartIE(); } } } } SYSTEMTIME localTime; GetLocalTimeRVC(localTime); //99 is initial value of m_preDay if (m_preDay != 99 && m_preDay != localTime.wDayOfWeek && m_bNeedToRestartPAD == false) m_bNeedToRestartPAD = true; m_preDay = localTime.wDayOfWeek; CSmartPointer spConfigRun; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun); if (eErr != Error_Succeed) Dbg("timer open cfg file failed!"); else { if (localTime.wHour != m_lastHour) { Dbg("hour changed,to set restart times to 0"); spConfigRun->WriteConfigValueInt("Run", "RestartTimes", 0); } } GetNetDeviceState(); if (_strnicmp(m_sysStaticInfo.strMachineType.GetData(), "RVC.PAD", strlen("RVC.PAD")) == 0) { if (m_bNeedToRestartPAD) { ULONGLONG ull = 0; ull = GetTickCountRVC(); int osRunHours = 0, osRunDays = 0; osRunHours = (ull / (1000 * 60 * 60)); osRunDays = osRunHours / 24; CSmartPointer spConfigRun; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun); if (m_maxRunDays <= 0) m_maxRunDays = 7; if (osRunDays >= m_maxRunDays) { Dbg("os has run %d hour,to restart os.", osRunHours); spConfigRun->WriteConfigValueInt("Restart", "DayNum", 0); m_eRebootTrigger = RebootTrigger_Period; m_eRebootWay = RebootWay_Power; SystemRestart(true,true); } else if (osRunDays >= 1) { if (osRunDays > m_dayNum) { Dbg("os has run %d hour,to restart framework.", osRunHours); spConfigRun->WriteConfigValueInt("Restart", "DayNum", osRunDays); m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Period, RebootWay_Framework); } } } } else //not RVC.PAD { if (m_wDayOfWeek != localTime.wDayOfWeek) { if (localTime.wHour == m_restartHour && localTime.wMinute >= m_restartMinute && localTime.wMinute <= (m_restartMinute + HEALTHMANAGER_TIMER_INTERVAL_MINUTE)) { m_wDayOfWeek = localTime.wDayOfWeek; m_eRebootTrigger = RebootTrigger_Period; m_eRebootWay = RebootWay_Power; BOOL bRet = SystemRestart(true,true); Dbg("restart machine[%d][%d] bRet=%d, LastError=%d", localTime.wHour, localTime.wMinute, bRet, GetLastError()); Dbg("not rvc.pad %s,%s", m_sysStaticInfo.strMachineType.GetData(), (const char*)m_sysStaticInfo.strMachineType); } } } if (m_pUpsClient == NULL) { CSimpleStringA csRunState("B"); GetFunction()->GetSysVar("RunState",csRunState); if (csRunState[0] != 'B' || csRunState[0] != 'I') { if (_strnicmp(m_sysStaticInfo.strMachineType.GetData(), "RVC.Stand2S", strlen("RVC.Stand2S") == 0)) { int ret = ConnectUps(); Dbg("connect ups %d.", ret); } } } else { UpsService_GetStatus_Req req; UpsService_GetStatus_Ans ans; ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req,ans,3000); if (eErrState == Error_Succeed) { m_bGetUpsStateFlag = true; switch(ans.Status) { case UPS_STATUS_NORMAL: m_bUpsWaitLock = false; m_upsNoElectorCount = 0; break; case UPS_STATUS_ERROR_TO_GET_STATUS: m_upsStateCount++; if (m_upsStateCount > 3) { //logwarn oiltmp } break; case UPS_STATUS_NO_ELECTOR: m_bUpsWaitLock = true; m_upsNoElectorCount++; if (m_upsNoElectorCount > 2) { //logwarn oiltmp //notify front end //shutdown pc or not? } break; default: break; } //Dbg("current state %d",ans.Status); } else { Dbg("get ups state failed(%d).",eErrState); m_bGetUpsStateFlag = false; if (eErrState == Error_NetBroken) { //m_pUpsClient->SafeDelete(); m_pUpsClient = NULL; } } } ReadMachineDataBySyncSerivce(); //Dbg("fsm:%d,menu:%s", m_fsm.GetFSMState(),(const char*)m_menuChoice); bool bCheckGuardian = false; if (m_fsm.GetFSMState() == HM_FSM_STATE_IDLE || (m_fsm.GetFSMState() == HM_FSM_STATE_CMS)) { if (m_fsm.GetAccessAuthFlag() && (m_bEnterMainPageEver || (!m_bEnterMainPageEver && m_fsm.IfIEBeforeHealth())))//oilyang 20161219 改成通过是否成功进入主页来判断IE情况 { bCheckGuardian = CheckGuardianIsRun(true); if (!m_bSayIdle) { m_bSayIdle = true; if (bCheckGuardian) { eErr = m_pfUpgradeRestart(3, 0); Dbg("healthmanager say idle,so tell the guardian.%d",eErr); } CSimpleStringA csRunInfo,csStartTime; if ((GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed) { Dbg("get runinfo path failed(%d)"); //oillinuxtmp //remove(csRunInfo + "/runcfg/starttime.dat"); } else { csStartTime = csRunInfo + "/runcfg/starttime.dat"; int ret = remove(csStartTime); if (ret == 0) Dbg("delete time file error.[%d]",GetLastError()); } } if (bCheckGuardian) { WorkStateEnum eShake; Dbg("to shake..."); ErrorCodeEnum eErrShake = m_pfShake(eShake); //if (eErrShake != Error_Succeed) Dbg("shake hand result:%d,work state %d",eErrShake,eShake); if (!m_bHealthInit) { bool bStop = StopGuardian(); if (bStop) { m_bHealthInit = true; bool bGuardian = StartGuardian(); Dbg("restart guardian %d", bGuardian); } } } else { Dbg("to start guardian"); bool bGuardian = StartGuardian(); Dbg("start guardian %d",bGuardian); } } else { //oilyang@20190905 add if auth suc,tell guardian,for upgrade if (m_fsm.GetAccessAuthFlag()) { if (CheckGuardianIsRun(true)) { eErr = m_pfUpgradeRestart(5, 0); Dbg("auth suc,so tell the guardian.%d", eErr); } } } } else { m_bSayIdle = false; } if (m_fsm.GetFSMState() == HM_FSM_STATE_CMS) { GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL); return; } if (m_bWaitRestartPC) { Dbg("finally we the restart time come,no wait."); //m_bWaitRestartPC = false; AfterWaitRestartPC(); } if (m_bUpsWaitLock) { UpsSupplyLockScreen(); } else { //no need to un-display blue screen? oiltest 20140320 //if (m_bScreenLock) //{ // CSmartPointer pFunc = GetFunction(); // CSmartPointer pFuncPrivilege = pFunc.ConvertCase(); // if (pFuncPrivilege == NULL) // { // Dbg("unlock screen NoPrivilege"); // return; // } // pFuncPrivilege->UndisplayBlueScreen(); // m_bScreenLock = false; //} } GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL); } #ifdef linux bool FindGuardianPid(pid_t &pid) { FILE* pstr; char cmd[128], buff[512]; pid_t pID; int pidnum; char* name = "guardian.exe";/*进程名*/ char* p = NULL; int ret = 3; memset(cmd, 0, sizeof(cmd)); sprintf(cmd, "ps -ef|grep %s|grep -v grep", name); pstr = popen(cmd, "r"); if (pstr == NULL) { return false; } memset(buff, 0, sizeof(buff)); fgets(buff, 512, pstr); Dbg("%s\n", buff); p = strtok(buff, " "); p = strtok(NULL, " "); pclose(pstr); //这句是否去掉,取决于当前系统中ps后,进程ID号是否是第一个字段 if (p == NULL) { return false; } //printf( "pid:%s\n",p); if (strlen(p) == 0) { return false; } if ((pidnum = atoi(p)) == 0) { return false; } Dbg("pidnum: %d", pidnum); pid = (pid_t)pidnum; return pid; } #endif bool CHealthManagerEntity::CheckGuardianIsRun(bool bStart) { #ifdef RVC_OS_WIN //LOG_FUNCTION(); HANDLE hSnapshot; //find guardian.exe hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot) { PROCESSENTRY32 pe; pe.dwSize = sizeof(pe); if (Process32First(hSnapshot, &pe)) { do { if (_stricmp(&pe.szExeFile[0], "guardian.exe") == 0) { //Dbg("guardian is running."); return true; } } while (Process32Next(hSnapshot, &pe)); } CloseHandle(hSnapshot); } Sleep(1000); Dbg("cannot find guardian."); if (bStart) return StartGuardian(); else return false; #else pid_t pID; bool bFind = false; bFind = FindGuardianPid(pID); if (bFind) { int ret = kill(pID, 0); Dbg("ret= %d ", ret); if (0 == ret) { Dbg("process: guardian.exe exist!"); return true; } else { Dbg("process: guardian.exe not exist!"); return false; } } return false; #endif //RVC_OS_WIN } bool CHealthManagerEntity::StopGuardian() { #ifdef RVC_OS_WIN Dbg("to stop guardian"); HANDLE hSnapshot; int rc = TRUE; int result; HANDLE hProcess; //find and kill guardian.exe hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot) { PROCESSENTRY32 pe; pe.dwSize = sizeof(pe); if (Process32First(hSnapshot, &pe)) { do { if (_stricmp(&pe.szExeFile[0], "guardian.exe") == 0) { hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID ); if( hProcess == NULL ) { Dbg("Fail to open process(%d)!",GetLastError()); return false; } else { result = TerminateProcess(hProcess,-1); if (result) { Dbg("Terminate guardian suc."); return true; } else { Dbg("Terminate guardian failed(%d).",GetLastError()); return false; } CloseHandle( hProcess ); } Sleep(3000); WaitForSingleObject(&pe.th32ProcessID, INFINITE ); break; } } while (Process32Next(hSnapshot, &pe)); } CloseHandle(hSnapshot); } Sleep(3000); return false; #else pid_t pID; bool bFind = false; bFind = FindGuardianPid(pID); if (bFind) { int ret = kill(pID, 9); } #endif //RVC_OS_WIN } bool CHealthManagerEntity::StartGuardian() { LOG_FUNCTION(); if (m_sysStaticInfo.strMachineType.Compare("RVC.IL") == 0) { Dbg("machine type is RVC.IL,no need to start guardian.exe"); return false; } Dbg("to start guardian"); #ifdef RVC_OS_WIN STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); GetFunction()->FlushLogFile(); // Start the child process. CSimpleStringA csBinPath,csAll,csSep("\""); ErrorCodeEnum Error = GetFunction()->GetPath("Bin", csBinPath); csBinPath +="\\guardian.exe"; csAll = csSep + csBinPath + csSep; Dbg("guardian path[%s]",(LPCTSTR)csAll); LPTSTR szCmdline = _strdup(csAll); if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)) { Dbg("CreateProcess failed (%d).\n", GetLastError()); return false; } DWORD dwErr = GetLastError(); return true; #else int i; pid_t pid; if (pid = fork() != 0) { cout << "parent" << endl; //_exit(0); } if (pid == 0) { setsid(); //子进程调用execle if ((i = execl("/home/yangsy/progtest/guardian/guardian.exe", "guardian.exe", (char*)NULL)) == -1) { printf("execle failed_error ID:%d,%s\n", errno, strerror(errno)); } else { printf("execle Successed!"); } sleep(1); int fd0, fd1, fd2; fd0 = open("/dev/null", O_RDWR); fd1 = dup(0); fd2 = dup(0); } #endif //RVC_OS_WIN } bool CHealthManagerEntity::DoRestart() { LOG_FUNCTION(); CSmartPointer spConfig; ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Software, spConfig); if (err != Error_Succeed) { LOG_TRACE("open cfg file failed!"); return false; } m_restartHour = m_restartMinute = 1; m_maxRestartTimes = 3; int defaultTimesMax,defaultInternal,lowTimesMax,lowInternal; defaultTimesMax = 10; defaultInternal = 600000; lowTimesMax = 5; lowInternal = 600000; spConfig->ReadConfigValueInt("init","RestartHour",m_restartHour); spConfig->ReadConfigValueInt("init","RestartMinute",m_restartMinute); int testflag; spConfig->ReadConfigValueInt("init","TestFlag",testflag); m_testFlag = testflag; spConfig->ReadConfigValueInt("Run","MaxRestartTimes",m_maxRestartTimes); Dbg("m_maxRestartTimes(%d)",m_maxRestartTimes); spConfig->ReadConfigValueInt("ModRestartSettings","DefaultTimesMax",defaultTimesMax); spConfig->ReadConfigValueInt("ModRestartSettings","DefaultInternal",defaultInternal); spConfig->ReadConfigValueInt("ModRestartSettings","LowTimesMax",lowTimesMax); spConfig->ReadConfigValueInt("ModRestartSettings","LowInternal",lowInternal); m_restartMode[RESTART_MODE_DEFAULT].dwTimes = defaultTimesMax; m_restartMode[RESTART_MODE_DEFAULT].dwInternal = defaultInternal; m_restartMode[RESTART_MODE_LOW].dwTimes = lowTimesMax; m_restartMode[RESTART_MODE_LOW].dwInternal = lowInternal; CSimpleStringA csDefaultModule,csLowModule; spConfig->ReadConfigValue("ModRestartSettings","DefaultModule",csDefaultModule); spConfig->ReadConfigValue("ModRestartSettings","LowModule",csLowModule); SplitModuleNames(csDefaultModule,RESTART_MODE_DEFAULT); SplitModuleNames(csLowModule,RESTART_MODE_LOW); Dbg("%d:%d",m_restartHour,m_restartMinute); CSmartPointer spConfigRun; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->ReadConfigValueInt("Run", "LastHour", m_lastHour); m_dayNum = 1; spConfigRun->ReadConfigValueInt("Restart", "DayNum", m_dayNum); if (m_dayNum == 0) { spConfigRun->WriteConfigValueInt("Restart", "DayNum", 0); } spConfigRun->ReadConfigValueInt("Run", "RestartTimes", m_restartTimes); CSmartPointer spCerConfig; eErr = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig); spCerConfig->ReadConfigValueInt(GetEntityName(), "MaxRunDays", m_maxRunDays); Dbg("central setting:m_maxRunDays:%d,DayNum:%d", m_maxRunDays,m_dayNum); SYSTEMTIME localTime; GetLocalTimeRVC(localTime); if (m_bInit) { m_bInit = false; m_wDayOfWeek = localTime.wDayOfWeek; } eErr = GetFunction()->GetSystemStaticInfo(m_sysStaticInfo); if (eErr != Error_Succeed) { Dbg("Get system static info failed(%d).", eErr); m_sysStaticInfo.strMachineType = ""; m_sysStaticInfo.strSite = ""; m_sysStaticInfo.InstallVersion = CVersion(); } ReadMachineDataBySyncSerivce(); ITimerListener *pListener = new TimerOutHelper(this, &CHealthManagerEntity::OnCheckTimeTimeout); Dbg("set timer"); GetFunction()->SetTimer(HEALTHMANAGER_TIMER_ID, pListener, HEALTHMANAGER_TIMER_INTERVAL); //oiltmp 20131204 commented,the following upline(...)add it //DoWatchDog(WD_OP_START); //ITimerListener *pWDListener = new TimerOutHelper(this, &CHealthManagerEntity::OnWatchDogTimeout); //GetFunction()->SetTimer(HEALTHMANAGER_WD_TIMER_ID, pWDListener, HEALTHMANAGER_WD_TIMER_INTERVAL); CSimpleStringA deamonBasePath = ""; err = GetFunction()->GetPath("bin",deamonBasePath); if (err != Error_Succeed) { Dbg("for wait deamon get bin path failed(%d).",err); return Error_IO; } #ifdef linux deamonBasePath += "/GuardianBase.so"; Dbg("gd path [%s]", (LPCTSTR)deamonBasePath); void* handle = dlopen(deamonBasePath, RTLD_LAZY); if (handle == NULL) { Dbg("load GuardianBase.so failed(%d)", errno); return Error_IO; } m_pfShake = (pfShakeHands)dlsym(handle, "ShakeHands"); if (m_pfShake == NULL) { Dbg("get ShakeHands failed(%d)", GetLastError()); return Error_IO; } m_pfUpgradeRestart = (pfUpgradeRestart)dlsym(handle, "UpgradeRestart"); if (m_pfUpgradeRestart == NULL) { Dbg("get UpgradeRestart failed(%d)", GetLastError()); return Error_IO; } #else deamonBasePath += "\\GuardianBase.dll"; HMODULE hDll = LoadLibraryA(deamonBasePath); Dbg("gd path [%s]", (LPCTSTR)deamonBasePath); if (hDll == NULL) { Dbg("load guardianbase.dll failed(%d)", GetLastError()); return Error_IO; } m_pfShake = (pfShakeHands)GetProcAddress(hDll,"ShakeHands"); if (m_pfShake == NULL) { Dbg("get shakehands failed(%d)",GetLastError()); return Error_IO; } m_pfUpgradeRestart = (pfUpgradeRestart)GetProcAddress(hDll,"UpgradeRestart"); if (m_pfUpgradeRestart == NULL) { Dbg("get UpgradeRestart failed(%d)",GetLastError()); return Error_IO; } #endif //linux Dbg("have load guardian."); if (CheckGuardianIsRun(true)) { Sleep(500); Dbg("to tell guardian framework is starting."); eErr = m_pfUpgradeRestart(4, 0);//tell guardian framework is starting...oilyang 20150514 Dbg("feedback of framework is starting.%d",eErr); } m_currentVer = ""; UpdateSiteToRuncfg(); return true; } void CHealthManagerEntity::SplitModuleNames(CSimpleStringA csLine, ModuleReMode eMode) { string str((const char*)csLine); size_t pos = 0,nameEnd = 0; size_t len = str.length(); while(1) { nameEnd = str.find(',',pos); if (nameEnd != string::npos) { m_modCfgInfo[str.substr(pos,nameEnd-pos).c_str()] = eMode; pos = nameEnd + 1; } else { if (pos < len) m_modCfgInfo[str.substr(pos,nameEnd-pos).c_str()] = eMode; break; } } } int CHealthManagerEntity::ConnectUps() { if (m_pUpsClient == NULL) { m_pUpsClient = new UpsService_ClientBase(this); ErrorCodeEnum eErrConn = m_pUpsClient->Connect(); if (eErrConn != Error_Succeed) { Dbg("Ups connected failed(%d).",eErrConn); //m_pUpsClient->SafeDelete(); m_pUpsClient = NULL; } else { Dbg("ups entity connected."); UpsService_GetStatus_Req req; UpsService_GetStatus_Ans ans; ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req,ans,3000); if (eErrState == Error_Succeed) { m_bGetUpsStateFlag = true; Dbg("current state %d",ans.Status); return 0; } else Dbg("connect get ups state failed(%d).",eErrState); } } return -1; } bool CHealthManagerEntity::SaveCurrentVersion() { CSimpleStringA csRootVer,csRunInfo,csBakFile,csVerFile; ErrorCodeEnum eErr; if ((eErr = GetFunction()->GetPath("RootVer",csRootVer)) != Error_Succeed) { LOG_TRACE("Get version path failed(%d).",eErr); return false; } if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed) { Dbg("get runinfo path failed(%d)",eErr); return false; } //csVerFile = csRootVer + "\\active.txt"; csBakFile = csRunInfo + "/runcfg/version.dat"; //ifstream infile(csVerFile,std::ifstream::binary); ofstream outfile (csBakFile,std::ofstream::binary); //infile.seekg (0,infile.end); //long size = infile.tellg(); //infile.seekg (0,infile.beg); CSimpleStringA csCurrVer = m_sysStaticInfo.InstallVersion.ToString(); Dbg("get current version [%s]",(LPCTSTR)csCurrVer); int size = csCurrVer.GetLength(); char* buffer = new char[size]; ZeroMemory(buffer,size); //infile.read (buffer,size); memcpy(buffer,csCurrVer,size); outfile.write (buffer,size); delete[] buffer; outfile.close(); //infile.close(); return true; } bool CHealthManagerEntity::SaveFrameStartTimeForUpgrade() { CSimpleStringA csRunInfo,csBakFile; ErrorCodeEnum eErr; if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed) { Dbg("get runinfo path failed(%d)",eErr); return false; } //csVerFile = csRootVer + "\\active.txt"; csBakFile = csRunInfo + "/runcfg/starttime.dat"; //ifstream infile(csVerFile,std::ifstream::binary); ofstream outfile (csBakFile,std::ofstream::binary); CSystemRunInfo sysRunInfo; GetFunction()->GetSystemRunInfo(sysRunInfo); if (eErr != Error_Succeed) { Dbg("Get system run info failed(%d).",eErr); return false; } CSimpleStringA csStartTime = sysRunInfo.tmStart.ToTimeString(); Dbg("get current time start [%s]",(LPCTSTR)csStartTime); int size = csStartTime.GetLength(); char* buffer = new char[size]; ZeroMemory(buffer,size); //infile.read (buffer,size); memcpy(buffer,csStartTime,size); outfile.write (buffer,size); delete[] buffer; outfile.close(); //infile.close(); return true; } bool CHealthManagerEntity::VersionRollBack(const char *pVerion) { CSimpleStringA csCurrVer = m_sysStaticInfo.InstallVersion.ToString(); if (_stricmp(csCurrVer,pVerion) == 0) { Dbg("destination version identified the current version."); return false; } m_pUpgMgr = new UpgradeMgrService_ClientBase(this); if (m_pUpgMgr == NULL) { Dbg("create UpgradeMgr client failed."); return false; } CSmartPointer pAsyncWait; ErrorCodeEnum eErr = m_pUpgMgr->Connect(pAsyncWait); if (eErr != Error_Succeed) { Dbg("connect to UpgradeMgr failed(%d)",eErr); return false; } else eErr = pAsyncWait->WaitAnswer(10000); UpgradeMgrService_RollbackUpdate_Req req; req.strVersion = pVerion; UpgradeMgrService_RollbackUpdate_Ans ans; eErr = m_pUpgMgr->RollbackUpdate(req,ans,10000); if (eErr == Error_Succeed) { Dbg("version rollback doing."); m_bVerRollback = true; return true; } else { Dbg("UpgradeMgr rollback failed(%d)",eErr); return false; } } void CHealthManagerEntity::ReadMachineDataBySyncSerivce() { ErrorCodeEnum eSync; if (m_pSync == NULL) { m_pSync = new SyncService_ClientBase(this); if (m_pSync != NULL) { ErrorCodeEnum eSync = m_pSync->Connect(); if (eSync != Error_Succeed) { Dbg("connect to SyncService failed %d.",eSync); //m_pSync->SafeDelete(); m_pSync = NULL; } } } else { SyncService_GetMachineData_Req req; SyncService_GetMachineData_Ans ans; req.key = "MenuChoice"; eSync = m_pSync->GetMachineData(req,ans,10000); if (eSync == Error_Succeed) { m_menuChoice = ans.value; if (m_menuPre.Compare(m_menuChoice) != 0) { m_menuPre = m_menuChoice; Dbg("menu:[%s]", (LPCTSTR)m_menuChoice); if (m_menuChoice.Compare("Main") == 0) { //according to yangzixiong,comment it. by oilyang 20160615 //LogEvent(Severity_Middle, LOG_EVT_USB_CONTROL_OFF, "usb off");//just for Stand2S } } } else { m_menuChoice = ""; } } } int CHealthManagerEntity::GetNetDeviceState() { return 0; } int CHealthManagerEntity::UpdateSiteChangeFlag() { CSmartPointer spConfig; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig); if (eErr != Error_Succeed) { Dbg("UpdateSiteChangeFlag open run cfg file failed!"); return -1; } eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 1); Dbg("Write SiteChanged 1.err[%d]",eErr); return 0; } int CHealthManagerEntity::UpdateSiteToRuncfg(bool bWriteSite,bool bClearSiteFlag) { Dbg("bClearSiteFlag[%d]",bClearSiteFlag); CSmartPointer spConfig; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig); if (eErr != Error_Succeed) { Dbg("UpdateSiteToRuncfg open run cfg file failed!"); return -1; } if (!bClearSiteFlag) { int siteChangedFlag = 0; eErr = spConfig->ReadConfigValueInt("AboutSite", "SiteChanged", siteChangedFlag); if (eErr == Error_Succeed) { if (siteChangedFlag != 0) { bWriteSite = false; } } } else { eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 0); Dbg("UpdateSiteToRuncfg.Write Site (%d).", eErr); } if (bWriteSite) { spConfig->WriteConfigValue("AboutSite", "Site", m_sysStaticInfo.strSite); } return 0; } int CHealthManagerEntity::WriteSiteToRootIni() { LOG_FUNCTION(); CSmartPointer spConfig; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig); if (eErr != Error_Succeed) { Dbg("UpdateSiteToRuncfg open run cfg file failed!"); return -1; } CSimpleStringA csSite(""); eErr = spConfig->ReadConfigValue("AboutSite", "Site", csSite); if (eErr == Error_Succeed) { CSimpleStringA path(""); GetFunction()->GetPath("HardwareCfg", path); path.Append("\\"); path.Append("root.ini"); Dbg("WriteSiteToRootIni[%s]",(LPCTSTR)path); //oiltestlinux comment the following 2 lines //BOOL bRet = ::WritePrivateProfileStringA("Terminal", "Site", csSite, path); //Dbg("WriteSiteToRootIni:write site bRet = %d", bRet); } } int CHealthManagerEntity::RestartIE() { m_bNeedToRestartIE = false; CSmartPointer spWait; CSmartPointer pFuncPrivilege = GetFunction().ConvertCase(); ErrorCodeEnum eErr = pFuncPrivilege->TerminateEntity("IEBrowser", spWait); if (eErr == Error_Succeed) { if (spWait != NULL) spWait->WaitAnswer(10000); } else Dbg("TerminateEntity ie failed.%d", eErr); Dbg("Url value:%s", (const char*)m_fsm.GetUrlValue()); eErr = pFuncPrivilege->StartEntity("IEBrowser", m_fsm.GetUrlValue(), spWait); if (eErr == Error_Succeed) { if (spWait != NULL) eErr = spWait->WaitAnswer(15000); } else { Dbg("Start IEBrowser failed(%d).", eErr); } return 0; } void CHealthManagerEntity::QueryHardwareInfo(SpReqAnsContext::Pointer ctx) { CSystemStaticInfo info; GetFunction()->GetSystemStaticInfo(info); NetworkAddressesList macAddrs; NetworkAddressesList ipAddrs; GetINETMacAddresses(macAddrs, ipAddrs); ctx->Ans.ip = ipAddrs; ctx->Ans.mac = macAddrs; ctx->Ans.machineType = info.strMachineType; ctx->Ans.site = info.strSite; ctx->Ans.terminalNo = info.strTerminalID; ctx->Ans.termLimit = __ReadCenterConfigStr("TermLimitSwitch", "IEBrowser"); ctx->Ans.termVersion = info.InstallVersion.ToString(); ctx->Answer(Error_Succeed); } void CHealthManagerEntity::ReadCenterConfigStr(SpReqAnsContext::Pointer ctx) { ctx->Ans.value = __ReadCenterConfigStr(ctx->Req.key, ctx->Req.entity); ctx->Answer(Error_Succeed); } CSimpleStringA CHealthManagerEntity::__ReadCenterConfigStr(CSimpleStringA key, CSimpleStringA entityName = "") { CSimpleStringA str = ""; CSmartPointer spCerConfig; ErrorCodeEnum err = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig); if (entityName == "") { spCerConfig->ReadConfigValue("IEBrowser", key, str); } else { spCerConfig->ReadConfigValue(entityName, key, str); } return str; } void CHealthManagerEntity::GetINETMacAddresses(NetworkAddressesList &macList, NetworkAddressesList &ipList) { #ifdef RVC_OS_WIN PIP_ADAPTER_ADDRESSES pAddresses = NULL; ULONG family = AF_INET; ULONG flags = GAA_FLAG_INCLUDE_PREFIX; ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES); Dbg("GetINETMacAddresses"); // Make an initial call to GetAdaptersAddresses to get the // size needed into the outBufLen variable if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW) { pAddresses = static_cast(HeapAlloc(GetProcessHeap(), 0, outBufLen)); } Dbg("GetAdaptersAddresses 1"); if (NULL == pAddresses) { Dbg("pAddresses = NULL"); return; } // _ASSERT( pAddresses ); // Make a second call to GetAdapters Addresses to get the // actual data we want DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen); Dbg("GetAdaptersAddresses 2"); /* MACAddresses vAddress;*/ if (dwRetVal != ERROR_SUCCESS) { Dbg("dwRetVal = %d", dwRetVal); return; } PIP_ADAPTER_ADDRESSES pFirst = pAddresses; while (pAddresses) { if (pAddresses->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET && pAddresses->OperStatus == IfOperStatusUp && pAddresses->IfType != IF_TYPE_SOFTWARE_LOOPBACK) { Dbg("in while if 1"); BYTE* pa = pAddresses->PhysicalAddress; if (!pa) { pAddresses = pAddresses->Next ? pAddresses->Next : NULL; continue; } Dbg("in while if 2"); char bAddressBytes[MACSESION]; int bAddressInt[MACSESION]; memset(bAddressBytes, 0, MACSESION); size_t nAddressSize = pAddresses->PhysicalAddressLength; memcpy(bAddressBytes, pa, (nAddressSize < MACSESION ? nAddressSize : MACSESION)); char CommarSeperatedAddress[MACSESION * 3] = { 0 }; for (int i = 0; i < MACSESION; ++i) { bAddressInt[i] = bAddressBytes[i]; bAddressInt[i] &= 0x000000ff; // avoid "ff" leading bytes when "char" is lager then 0x7f } Dbg("in while if 3"); sprintf(CommarSeperatedAddress, "%02x:%02x:%02x:%02x:%02x:%02x", bAddressInt[0], bAddressInt[1], bAddressInt[2], bAddressInt[3], bAddressInt[4], bAddressInt[5]); // Should use scl::FormatString inside CSimpleStringA tmpmac = CSimpleStringA(CommarSeperatedAddress); Dbg("in while if 4"); macList.Append(&tmpmac, 0, 1); // macList.push_back( std::string( CommarSeperatedAddress ) ); Dbg("Description : %s", pAddresses->Description); Dbg("OperStatus : %d, IfType = %d, mac = %s", pAddresses->OperStatus, pAddresses->IfType, CommarSeperatedAddress); sockaddr_in *sa_in = (sockaddr_in *)pAddresses->FirstUnicastAddress->Address.lpSockaddr; char buf_addr[100] = { 0 }; CSimpleStringA tmpip = CSimpleStringA(inet_ntop(AF_INET, &(sa_in->sin_addr), buf_addr, 100)); ipList.Append(&tmpip, 0, 1); } pAddresses = pAddresses->Next ? pAddresses->Next : NULL; } HeapFree(GetProcessHeap(), 0, pFirst); return; #else return;//oiltestlinux #endif //RVC_OS_WIN } void CHealthManagerEntity::OnLog(const CAutoArray &SubIDs, const CUUID nLogID, const LogTypeEnum eLogType, const SeverityLevelEnum eLevel, const DWORD dwSysError, const DWORD dwUserCode, const DWORD dwEntityInstanceID, const WORD wEntityDevelID, const CAutoArray &Param, const char *pszEntityName, const char *pszModuleName, const char *pszMessage) { // MessageBoxA(0,0,0,0); //if (dwUserCode != LOG_EVT_HEARTBEAT_UN_CONNECTED) // Dbg("user code:%x,from entity:%s",dwUserCode,pszEntityName); switch (dwUserCode) { case EVENT_RESTART_SHELL: case Event_Req_Framework_Restart: //case framework restart after upgrade case EVENT_CONSOLE_REQ_RESTART_SHELL: case Event_Req_Framework_Rollback://case after rollback //according to zl commented the following line 20150828 //case EVENT_UKEY_CUSTOMER_MANANAGER_SYS_EXIT: case LOG_EVT_IEBROWSER_RESET_SITE_RESTART: //重设root.ini的site,重启框架 case LOG_EVT_HEARTBEAT_UN_CONNECTED: //重设site后框架分行服务连接不上,再次重启回退到前一版本 { bool bCheckGuardian = CheckGuardianIsRun(); if (!bCheckGuardian) { bool bStartGuardian = StartGuardian(); if (!bStartGuardian) { Dbg("Before restart frame,start guardian failed."); break; } Dbg("Before restart frame,start guardian suc."); Sleep(2000); } if (dwUserCode == Event_Req_Framework_Restart) { SaveCurrentVersion(); SaveFrameStartTimeForUpgrade(); if (CheckGuardianIsRun(true)) { ErrorCodeEnum eErr = Error_Unexpect; eErr = m_pfUpgradeRestart(1, 0); Dbg("to tell guardian framework is restarting.%d",eErr); } m_eRebootTrigger = RebootTrigger_FrameUpgrade; } else if (dwUserCode == Event_Req_Framework_Rollback) { Dbg("version rollback succeed.to restart framework"); m_bVerRollback = false; m_eRebootTrigger = RebootTrigger_RollBack; } else if (dwUserCode == LOG_EVT_IEBROWSER_RESET_SITE_RESTART) { UpdateSiteChangeFlag(); m_eRebootTrigger = RebootTrigger_Resource; } else if (dwUserCode == LOG_EVT_HEARTBEAT_UN_CONNECTED) { CSmartPointer spConfig; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig); int tmpFlag = 99; spConfig->ReadConfigValueInt("AboutSite", "SiteChanged", tmpFlag); if (tmpFlag != 1) { //Dbg("heartbeat can't connect(normal).no need to rollback."); break; } WriteSiteToRootIni(); UpdateSiteToRuncfg(false, true); } m_eRebootWay = RebootWay_Framework; BOOL bRet = FrameworkShutdown(); Dbg("framework shutdown [%d]", bRet); } break; case EVENT_CONSOLE_REQ_SHUTDOWN_SHELL: { BOOL bRet = FrameworkShutdown(false); Dbg("framework shutdown [%d]", bRet); } break; case EVENT_RESTART_MACHINE: case Event_Req_OS_Restart://case os restart after outside update case EVENT_CONSOLE_REQ_RESTART_POWER: { if (dwUserCode == Event_Req_OS_Restart) m_eRebootTrigger = RebootTrigger_OSUpgrade; else m_eRebootTrigger = RebootTrigger_Unknown; m_eRebootWay = RebootWay_Power; BOOL bRet = SystemRestart(false,true); Dbg("os restart [%d]", bRet); } break; case LOG_EVT_IEBROWSER_RESTART_MACHINE: { m_eRebootTrigger = RebootTrigger_Unknown; m_eRebootWay = RebootWay_Power; BOOL bRet = SystemRestart(false, true,true); Dbg("machine restart now [%d]", bRet); break; } case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE: { Dbg("User descktop said to shutdown machine now."); SystemShutdown(); break; } case LOG_EVT_SELFCHECK_OS_RESTART: Dbg("selfcheck to wait chance to restart(os) pc."); m_eRebootTrigger = RebootTrigger_RunExcepition; m_eRebootWay = RebootWay_Power; m_bWaitRestartPC = true; break; case LOG_EVT_SELFCHECK_POWER_RESTART: Dbg("selfcheck to wait chance to restart(power) pc."); m_eRebootTrigger = RebootTrigger_RunExcepition; m_eRebootWay = RebootWay_Power; m_bWaitRestartPC = true; break; //commented the following 4 event oilyang 20140616 //case ERROR_MOD_MEDIACONTROLLER_ENVCAMERA_BUG://environment camera error //case EVENT_MOD_FACE_ENVCAM_ERROR: // Dbg("Environment camera restart"); // RestartModule("MediaController"); // break; //case ERROR_MOD_MEDIACONTROLLER_OPECAMERA_BUG://operation camera error //case EVENT_MOD_FACE_OPECAM_ERROR: // Dbg("Operation camera restart"); // RestartModule("MediaController"); // break; case EVENT_ACCESSAUTH_SUCCEED: Dbg("access auth succeed."); m_fsm.SetAccessAuth(); m_bAccessSuc = true; break; case EVENT_ACCESSAUTH_FAILED: case EVENT_ACCESSAUTH_TIMEOUT: Dbg("access auth failed or timeout(%d).", dwUserCode); m_fsm.SetAccessFailedFlag(); m_bAccessSuc = false; break; case EVENT_MOD_INITIALIZER_MK_LOADED: Dbg("init succeed."); m_fsm.SetInitSucFlag(); break; case EVENT_MOD_INITIALIZER_MK_FAILED: Dbg("init failed."); m_fsm.SetInitFailFlag(); break; case EVENT_MOD_FACE_OPENCV_ERROR: RestartModule("FaceTracking"); break; case LOG_EVT_INC_VERSION_ROLLBACK: Dbg("version to be rollback to %s", pszMessage); if (!m_bVerRollback) { Dbg("rollbacking"); VersionRollBack(pszMessage); } break; case LOG_EVT_SELFCHECK_TOKEN_KEEPER_LOST: { ErrorCodeEnum eErr = RestartModule("TokenKeeper"); Dbg("to re accessauth"); m_fsm.ToReAccessAuth(); } break; case EVENT_UKEY_CUSTOMER_MANANAGER_SYS_ENTER: { Dbg("to enter customer manager system."); m_fsm.SetCustomerMngerState(CM_ENTER);//set enter state FSMEvent *pEvt = new FSMEvent(USER_EVT_ENTER_CUSTOMER_MANAGER); m_fsm.PostEventFIFO(pEvt); } break; case LOG_EVT_HEARTBEAT_CONNECTED: UpdateSiteToRuncfg(true, true); break; case EVENT_MOD_CENTERSETTING_RVCWEBVER_CHANGE: m_bNeedToRestartIE = true; break; //case EVENT_UKEY_NOT_ENTER_CUSTOMER_MANANAGER: // { // Dbg("NOT to enter customer manager system."); // m_fsm.SetCustomerMngerState(CM_NOT_ENTER);//set enter state // } // break; case EVENT_MOD_RELEASESIP_TIMEOUT: RestartModule("SIPPhone"); break; case LOG_EVT_SELFCHECK_IEBROWSER_IDLE: //IE重启之后,重置是否进入主页变量 m_bFisrtEnterMainPage = true; m_bEnterMainPageEver = false; break; case LOG_EVT_INC_TRADE_MANAGER_NORMAL: case LOG_EVT_INC_TRADE_MANAGER_ON: case LOG_EVT_INC_TRADE_MANAGER_OFF: { TradeManage tm; if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_NORMAL) tm.op = 0; else if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_ON) tm.op = 1; else if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_OFF) tm.op = 2; tm.time = pszMessage; Dbg("trademanager:%d,%s",tm.op,(const char*)tm.time); SpSendBroadcast(GetFunction(), SP_MSG_OF(TradeManage), SP_MSG_SIG_OF(TradeManage), tm); } case LOG_EVT_INC_DEVICE_LOCK_ON: case LOG_EVT_INC_DEVICE_UNLOCK: case LOG_EVT_INC_DEVICE_KICK_OFF: { TerminalManager tm; if (dwUserCode == LOG_EVT_INC_DEVICE_LOCK_ON) tm.op = 0; else if (dwUserCode == LOG_EVT_INC_DEVICE_UNLOCK) { if (m_bAccessSuc) tm.op = 1; else tm.op = 99;//oilyang@20170818 according to xingzichen } else if (dwUserCode == LOG_EVT_INC_DEVICE_KICK_OFF) tm.op = 2; Dbg("terminal manager:%d", tm.op); SpSendBroadcast(GetFunction(), SP_MSG_OF(TerminalManager), SP_MSG_SIG_OF(TerminalManager), tm); } break; case LOG_EVT_SYSTMECUSTOM_START_ACCESSAUTH: Dbg("receive md5 ok event."); m_fsm.SetMD5OK(1); break; default: //Dbg("unknown event(%d)...", dwUserCode); return; } } void CHealthManagerEntity::OnSysVarEvent(const char *pszKey, const char *pszValue, const char *pszOldValue, const char *pszEntityName) { if ((_strnicmp(pszKey, "UIState", strlen("UIState")) == 0)) { if (_strnicmp(pszValue, "M", strlen("M")) == 0) { m_bInMainPage = true; if (m_bFisrtEnterMainPage) { Dbg("the first enter main page from healthmanager started."); m_bFisrtEnterMainPage = false; m_bEnterMainPageEver = true; LogEvent(Severity_Middle, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE, "enter main page"); CSmartPointer spConfigRun; ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartTimes", 0); Dbg("As have been in main page,reset UpgradeRestartTimes."); } } else m_bInMainPage = false; } } void CHealthManagerEntity::OnBroadcastEvent(CUUID SubID, const char *pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer) { if (_strnicmp(pszEntityName, "CardSwiper", strlen("CardSwiper")) == 0) { if (dwMessageSignature == eMsgSig_ConnectStatus) { CSimpleStringA tmpDevSN(""); GetFunction()->GetSysVar("FWBDevSN", tmpDevSN); if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2) { Dbg("This is fwb device.no need to reconnect here."); return; } CardSwiper::ConnectStatus cs; SpBuffer2Object(Buffer, cs); if (cs.status == 0) { if (m_connectStatus == 1) { m_connectStatus = 0; } } else if (cs.status == 1) { if (m_connectStatus == 0) { m_connectStatus = 1; m_fsm.DeviceReConnect(); } } } } } SP_BEGIN_ENTITY_MAP() SP_ENTITY(CHealthManagerEntity) SP_END_ENTITY_MAP()