123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755 |
- // mod_healthmanager.cpp : Defines the exported functions for the DLL application.
- //
- #include "stdafx.h"
- #if defined(RVC_OS_WIN)
- #include <TlHelp32.h>
- #include <iphlpapi.h>
- #include <ws2tcpip.h>
- #include <Winsock2.h>
- #include <io.h>
- #include <WinUser.h>
- #define GUARDIAN_FILENAME "GuardianBase.dll"
- #else
- #include <sys/wait.h>
- #include <unistd.h>
- #include <time.h>
- #include <signal.h>
- #include <dlfcn.h>
- #include <fcntl.h>
- #include <sys/reboot.h>
- #define GUARDIAN_FILENAME "libGuardianBase.so"
- #endif //RVC_OS_WIN
- #include <vector>
- #include <iostream>
- #include <fstream>
- #include "toolkit.h"
- #include "array.h"
- #include "fileutil.h"
- #include "iniutil.h"
- #include "osutil.h"
- #include <winpr/sysinfo.h>
- #include "mod_healthmanager.h"
- #include "CommEntityUtil.hpp"
- #include "TerminalInfoQueryConn.h"
- #include "Chromium_client_g.h" //启动浏览器接口
- using namespace std;
- using namespace Chromium;
- const DWORD HEALTHMANAGER_TIMER_ID = 1;
- const DWORD HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_ID = 2;
- const DWORD HEALTHMANAGER_SELFCHECK_TIMER_ID = 3;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL = 60000;
- const DWORD HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_INTERVAL = 60000;
- const DWORD HEALTHMANAGER_REBOOT_OS_IN_MINUTES_AFTER_TIME = 5;
- const DWORD HEALTHMANAGER_SELFCHECK_TIMER_INTERVAL = 60000;
- const int MAX_STOP_AYSNC_TIMEOUT = 20000;
- const int MAX_TERM_AYSNC_TIMEOUT = 30000;
- const int MAX_START_AYSNC_TIMEOUT = 20000;
- #define WORKING_BUFFER_SIZE 15000
- #define MAX_TRIES 3
- #define MediaDev_OutSpeaker 1
- #define MediaDev_InSpeaker 2
- #define MediaDev_OutMicrophone 3
- #define MediaDev_InMicrophone 4
- template<class T>
- 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;
- };
- namespace {
- void InitializeOtherLogSwitch(CEntityBase* pEntity, const CSimpleStringA& strModuleName)
- {
- if (pEntity == NULL || strModuleName.IsNullOrEmpty()) {
- return;
- }
- struct OtherLogConfig
- {
- OtherLogConfig() :strLevel("OFF"), strType("FILE"), strDllName(""), strLogPath("") {}
- OtherLogConfig(const CSimpleStringA& strModuleName) :strLevel("OFF"), strType("FILE"), strDllName(strModuleName), strLogPath("") {}
- CSimpleStringA strLevel;
- CSimpleStringA strType;
- CSimpleStringA strDllName;
- CSimpleStringA strLogPath;
- void Settle()
- {
- toolkit_setenv("VENDOR_RECODE_LEVEL", strLevel);
- toolkit_setenv("VENDOR_RECODE_TYPE", strType);
- toolkit_setenv("VENDOR_DLL_NAME", strDllName);
- toolkit_setenv("VENDOR_LOG_PATH", strLogPath);
- }
- } stLogConfig(strModuleName);
- CSmartPointer<IConfigInfo> centerConfig;
- pEntity->GetFunction()->OpenConfig(Config_CenterSetting, centerConfig);
- int nSaveFileOrNot(0);
- centerConfig->ReadConfigValueInt("Common", "SaveFile", nSaveFileOrNot);
- stLogConfig.strType = "UPLOAD";
- if ((nSaveFileOrNot & 1) == 1) {
- if (!stLogConfig.strType.IsNullOrEmpty()) stLogConfig.strType += "|";
- stLogConfig.strType += "FILE";
- }
- int nUploadLogLevel(1); /*INFO*/
- CSimpleStringA strUploadLogLevelEntity(true);
- centerConfig->ReadConfigValue(strModuleName.GetData(), "UpLoadLogLevel", strUploadLogLevelEntity);
- if (strUploadLogLevelEntity.IsNullOrEmpty()) {
- CSimpleStringA strUploadLogLevelComm(true);
- centerConfig->ReadConfigValue("Common", "UpLoadLogLevel", strUploadLogLevelComm);
- strUploadLogLevelEntity = strUploadLogLevelComm;
- }
- bool isValidDigit = !strUploadLogLevelEntity.IsNullOrEmpty();
- for (int i = 0; i < strUploadLogLevelEntity.GetLength(); ++i) {
- if (!(strUploadLogLevelEntity[i] >= '0' && strUploadLogLevelEntity[i] <= '9')) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("invalid param: %s", strUploadLogLevelEntity.GetData());
- isValidDigit = false;
- break;
- }
- }
- if (isValidDigit) {
- nUploadLogLevel = atoi(strUploadLogLevelEntity.GetData());
- }
- switch (nUploadLogLevel)
- {
- case 0: /*LOG_LEVEL_DEBUG*/
- stLogConfig.strLevel = "ALL";
- break;
- case 1: /*LOG_LEVEL_INFO*/
- stLogConfig.strLevel = "INFO";
- break;
- case 2: /*LOG_LEVEL_WARN*/
- stLogConfig.strLevel = "WARN";
- break;
- case 3: /*LOG_LEVEL_ERROR*/
- stLogConfig.strLevel = "ERROR";
- break;
- case 4: /*LOG_LEVEL_FATAL*/
- stLogConfig.strLevel = "FATAL";
- break;
- default:
- stLogConfig.strLevel = "OFF";
- break;
- }
- pEntity->GetFunction()->GetPath("Dbg", stLogConfig.strLogPath);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("DbgPath: %s", stLogConfig.strLogPath.GetData());
- stLogConfig.Settle();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{\"RecordLevel\":\"%s\", \"RecordType\":\"%s\}", stLogConfig.strLevel.GetData(), stLogConfig.strType.GetData());
- }
-
- }
- void HealthManagerSession::Handle_EnterState(SpReqAnsContext<HealthManagerService_EnterState_Req, HealthManagerService_EnterState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->EnterState(ctx);
- }
- void HealthManagerSession::Handle_ExitState(SpReqAnsContext<HealthManagerService_ExitState_Req, HealthManagerService_ExitState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->ExitState(ctx);
- }
- void HealthManagerSession::Handle_DoEvent(SpReqAnsContext<HealthManagerService_DoEvent_Req, HealthManagerService_DoEvent_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->DoEvent(ctx);
- }
- void HealthManagerSession::Handle_GetNetworkState(SpReqAnsContext<HealthManagerService_GetNetworkState_Req, HealthManagerService_GetNetworkState_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetNetworkState(ctx);
- }
- void HealthManagerSession::Handle_QueryHardwareInfo(SpReqAnsContext<HealthManagerService_QueryHardwareInfo_Req, HealthManagerService_QueryHardwareInfo_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->QueryHardwareInfo(ctx);
- }
- void HealthManagerSession::Handle_ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->ReadCenterConfigStr(ctx);
- }
- void HealthManagerSession::Handle_GetAuthErrMsg(SpReqAnsContext<HealthManagerService_GetAuthErrMsg_Req, HealthManagerService_GetAuthErrMsg_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetAuthErrMsg(ctx);
- }
- void HealthManagerSession::Handle_RealCheck(SpReqAnsContext<HealthManagerService_RealCheck_Req, HealthManagerService_RealCheck_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->RealCheck(ctx);
- }
- void HealthManagerSession::Handle_QueryCenterCfg(SpReqAnsContext<HealthManagerService_QueryCenterCfg_Req, HealthManagerService_QueryCenterCfg_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->QueryCenterCfg(ctx);
- }
- /**
- TerminalStage
- A: 准入通过?
- C: 准入不通过?
- D:设备故障
- B:
- N:
- U:
- */
- //almost disused.
- ErrorCodeEnum CHealthManagerEntity::RestartModule(const char* pEntityName)
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM)("restart mc NoPrivilege");
- return Error_NoPrivilege;
- }
- map<CSimpleStringA,ModuleRunInfo>::iterator it;
- it = m_modRunInfo.find(pEntityName);
- if (it == m_modRunInfo.end())
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("add %s to modfuninfo(%d).",pEntityName,m_modRunInfo.size());
- m_modRunInfo[pEntityName].dwStart = SP::Module::Comm::RVCGetTickCount();
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("modruninfo EntityName=%s", pEntityName);
- }
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum eErrCode = Error_Succeed;
- eErrCode = pFuncPrivilege->TerminateEntity(pEntityName,spWait);
- if (spWait != NULL)
- eErrCode = spWait->WaitAnswer(10000);
- if (eErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM)("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)
- {
- DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM)("start %s %d",pEntityName,eErrCode);
- return eErrCode;
- }
- return eErrCode;
- }
- void CHealthManagerEntity::AfterWaitRestartPC()
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("restart pc NoPrivilege");
- return;
- }
- ErrorCodeEnum eErr;
- CSimpleStringA csCustomerHandle("");
- eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("get CustomerHandle failed (%s).", SpStrError(eErr));
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CustomerHandle:%s", csCustomerHandle.GetData());
- if (csCustomerHandle[0] == 'N')
- {
- m_bWaitRestartPC = false;
- pFuncPrivilege->DisplayBlueScreen("PAUSE SERVICE");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("time comes,restart machine");
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_RunExcepition, RebootWay_OS);
- }
- }
- void CHealthManagerEntity::OnCheckTimeTimeout()
- {
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("OnCheckTimeTimeout");
- //oilyang@20220330 check if need restart framework by THE key CenterSetting updated.
- if (m_bToRestartByCenterSetting)
- {
- CSimpleStringA csTermStage("");
- ErrorCodeEnum eErrCode;
- eErrCode = GetFunction()->GetSysVar("TerminalStage", csTermStage);
- Dbg("OnCheckTimeTimeout::ToRestartByCenterSetting to get termstage %s", csTermStage.GetData());
- //oilyang@20250313 in Main page('UIState' is 'M') or TerminalStage is (NOT 'S') AND (NOT 'A'),that is in close page which caused by terminal app
- if (m_bInMainPage || (!m_bInMainPage && csTermStage.Compare("S") != 0 && csTermStage.Compare("A") != 0) )
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("THE key CenterSetting updated,we must restart framework right now.");
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Resource, RebootWay_Framework);
- }
- }
- SYSTEMTIME localTime;
- GetLocalTime(&localTime);
- //for example:[1----6]
- // ^ here we go
- //in reboot period
- if (localTime.wHour >= m_rebootHourBegin && localTime.wHour <= m_rebootHourEnd)
- {
- //reach setting reboot time
- if (localTime.wHour == m_restartHour && (localTime.wMinute >= m_restartMinute && localTime.wMinute <= m_restartMinute + HEALTHMANAGER_REBOOT_OS_IN_MINUTES_AFTER_TIME))
- {
- m_OSRunTicks = SP::Module::Comm::RVCGetTickCount();
- //the os haven't reboot today
- if (m_OSRunTicks > m_restartHour * 60 * 60 * 1000 + m_restartMinute * 60 * 1000)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to restart machine daily");
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Period, RebootWay_OS);
- }
- }
- }
- ErrorCodeEnum eErr = Error_Unexpect;
- CSmartPointer<IConfigInfo> spConfigRun;
- eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr != Error_Succeed)
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("timer open cfg file failed!");
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("m_fsm.GetFSMState():%d", m_fsm.GetFSMState());
- int iCheckGuardian = 0;
- if (m_fsm.GetFSMState() == HM_FSM_STATE_IDLE || (m_fsm.GetFSMState() == HM_FSM_STATE_CMS))
- {
- //oilyang@20210922 add comment
- //1、AccessAuth ok
- //2、have ever enter main page OR
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("m_fsm.GetAccessAuthFlag():%d, CheckIfHaveEnterMainPageEver:%d", m_fsm.CheckIfAccessAuthSuc(), CheckIfHaveEnterMainPageEver());
- //oilyang@20241230 check if have enter Main page ever
- if (CheckIfHaveEnterMainPageEver())
- {
- iCheckGuardian = CheckGuardianIsRun(true);
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("iCheckGuardian:%d", iCheckGuardian);
- if (!m_bSayIdle)
- {
- m_bSayIdle = true;
- if (iCheckGuardian > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("healthmanager say idle,so tell the guardian.%d", m_pfUpgradeRestart(3, 0));
- }
- }
- CSimpleStringA csRunCfgPath(""), csStartTime("");
- ErrorCodeEnum eErr = GetFunction()->GetPath("RunCfg", csRunCfgPath);
- csStartTime = csRunCfgPath + SPLIT_SLASH_STR + "starttime.dat";
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("csStartTime:%s", csStartTime.GetData());
- if (ExistsFileA(csStartTime)) {
- if (RemoveFileA(csStartTime))//删除成功,清理前次记录的guardian版本记录
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete start time file [%s] suc.", csStartTime.GetData());
- spConfigRun->WriteConfigValue("Run", "VersionEx", "");
- }
- else
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete time file [%s] error.[%d]", csStartTime.GetData(), GetLastError());
- }
- }
- if (iCheckGuardian > 0)
- {
- if (m_pfShake != NULL)
- {
- WorkStateEnum eShake;
- m_pfShake(eShake);
- m_ullGuardShakeCount++;
- }
- if (m_ullGuardShakeCount == 2)//in the next timeout(1 minute later than before,to restart guardian)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("准备重新启动guardian");
- bool bStop = StopGuardian();
- if (bStop)
- {
- bool bGuardian = StartGuardian();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("restart guardian %d", bGuardian);
- }
- }
- else if (m_ullGuardShakeCount % 5 == 0)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("the %d shake hand(guardian)", m_ullGuardShakeCount);
- }
- }
- else if (iCheckGuardian == -1)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("未启动guardian,准备启动guardian");
- bool bGuardian = StartGuardian();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start guardian %d", bGuardian);
- }
- }
- else
- {
- //oilyang@20190905 add if auth suc,tell guardian,for upgrade
- if (m_fsm.CheckIfAccessAuthSuc())
- {
- if (CheckGuardianIsRun(true) > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("auth suc,so tell the guardian.%d", m_pfUpgradeRestart(5, 0));
- }
- }
- }
- }
- }
- //oilyang@20210331 if accessauth told me not to restart framework,so that it can have time to retry
- if (!m_bNeedGuardianRestart)
- {
- if (CheckGuardianIsRun(true) > 0)
- {
- if (m_pfShake != NULL)
- {
- WorkStateEnum eShake;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("accessauth told me not to restart framework,so that it can have time to retry.%d", m_pfShake(eShake));
- }
- }
- }
- if (m_fsm.GetFSMState() == HM_FSM_STATE_CMS)
- {
- GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL);
- return;
- }
- if (m_bWaitRestartPC)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("finally we the restart time come,no wait.");
- //m_bWaitRestartPC = false;
- AfterWaitRestartPC();
- }
- GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL);
- }
- #if defined(RVC_OS_LINUX)
- bool FindGuardianPid(CAutoArray<int> &pIDArr)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to check guardian process");
- char* relate_processes[] = { "guardian" };
- int relate_processes_count = 1;
- alive_process_info processes[64];
- int alive_process_info_count = 64;
- memset(processes, 0, sizeof(processes));
- int retOfDetect = osutil_detect_unique_app(relate_processes, relate_processes_count, &alive_process_info_count, processes);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("detect guardian return:%d, alive_process_info_count:%d", retOfDetect, alive_process_info_count);
- if (alive_process_info_count > 0) {
- if (alive_process_info_count > 64)
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("too many guardian:%d", alive_process_info_count);
- else
- {
- if (alive_process_info_count == 1)
- pIDArr.Append(&processes[0].pid, 0, 1);
- else
- {
- for (int i = 0; i < alive_process_info_count; i++)
- {
- pIDArr.Append(&processes[i].pid, 0, 1);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The %d(th) guardian's pid is:%d", i + 1, processes[i].pid);
- }
- }
- }
- return true;
- }
- return false;
- }
- #endif //RVC_OS_LINUX
- int CHealthManagerEntity::CheckGuardianIsRun(bool bStart)
- {
- #ifdef RVC_OS_WIN
- 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)
- {
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("guardian is running.");
- return 1;
- }
- } while (Process32Next(hSnapshot, &pe));
- }
- CloseHandle(hSnapshot);
- }
- Sleep(1000);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("cannot find guardian.");
- if (!m_bNeedGuardian)//no need guardian
- {
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("no need guardian, so don't care about bStart flag");
- return 0;
- }
- else
- {
- bool bStartResult = false;
- if (bStart)
- bStartResult = StartGuardian();
- if (bStartResult)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("start guardian ok.");
- return 1;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("start guardian failed.");
- return -1;
- }
- }
- #else
- CAutoArray<int> pIDArr;
- bool bFind = false;
- bFind = FindGuardianPid(pIDArr);
- if (bFind)
- {
- for (int i = 0; i < pIDArr.GetCount(); i++)
- {
- int ret = kill(pIDArr[i], 0);
- if (0 == ret)
- {
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("guardian.exe is active, pid:%d", pIDArr[i]);
- return 1;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("process: guardian.exe inactive, pID:%d,ret:%d", pIDArr[i], ret);
- }
- }
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("cannot find guardian.");
- if (!m_bNeedGuardian)//no need guardian
- {
- if (!m_bSayIdle)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("no need guardian, so don't care about bStart flag");
- return 0;
- }
- else
- {
- bool bStartResult = false;
- if (bStart)
- bStartResult = StartGuardian();
- if (bStartResult)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("start guardian ok.");
- return 1;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("start guardian failed.");
- return -1;
- }
- }
- #endif //RVC_OS_WIN
- }
- bool CHealthManagerEntity::StopGuardian()
- {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("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 )
- {
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM)("Fail to open process(%d)!",GetLastError());
- CloseHandle(hSnapshot);
- return false;
- }
- else
- {
- result = TerminateProcess(hProcess,-1);
- if (result)
- {
- CloseHandle(hProcess);
- CloseHandle(hSnapshot);
- Sleep(3000);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Terminate guardian suc.");
- return true;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM)("Terminate guardian failed(%d).",GetLastError());
- CloseHandle(hProcess);
- CloseHandle(hSnapshot);
- return false;
- }
- }
- }
- } while (Process32Next(hSnapshot, &pe));
- }
- CloseHandle(hSnapshot);
- }
- Sleep(3000);
- return false;
- #else
- //why add the fallowing before ?oiltmp@20240407
- //int ret = m_pfUpgradeRestart(6, 0);
- //Dbg("healthmanager tell the guardian to quit.%d", ret);
- Sleep(5000);
- CAutoArray<int> pIDArr;
- bool bFind = false;
- bFind = FindGuardianPid(pIDArr);
- if (bFind)
- {
- for (int i = 0; i < pIDArr.GetCount(); i++)
- {
- if (pIDArr[i] == 0)
- continue;
- int ret = kill(pIDArr[i], 9 /*SIGKILL*/);
- if (ret < 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("kill guardian(pid:%d) failed:%d", pIDArr[i], errno);
- return false;
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("kill guardian(pid:%d) successfully.", pIDArr[i]);
- }
- return true;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("can't find guardian pid.");
- return true;
- #endif //RVC_OS_WIN
- }
- bool CHealthManagerEntity::StartGuardian()
- {
- LOG_FUNCTION();
- //oiltmp TODO 如果是未安装,不启动guardian
- //root.ini 不存在,表示未安装
- CSystemStaticInfo staticInfo;
- GetFunction()->GetSystemStaticInfo(staticInfo);
- /** 添加日志控制逻辑 Gifur@202414]*/
- InitializeOtherLogSwitch(this, "guardian");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("to start guardian");
- // Start the child process.
- CSimpleStringA csBinPath, csAll, csSep("\"");
- ErrorCodeEnum Error = GetFunction()->GetPath("Bin", csBinPath);
- #if defined(RVC_OS_WIN)
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
- ZeroMemory( &si, sizeof(si) );
- si.cb = sizeof(si);
- ZeroMemory( &pi, sizeof(pi) );
- GetFunction()->FlushLogFile();
- csBinPath +="\\guardian.exe";
- if (m_fsm.IfInUpgradeProcess() && !m_versionEx.IsNullOrEmpty())
- {
- string xTmp = csBinPath;//路径值
- xTmp = xTmp.replace(xTmp.find(m_currentVer), m_currentVer.GetLength(), m_versionEx);
- if(ExistsFileA(xTmp.c_str())){
- csBinPath = xTmp.c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("current version:%s,ex version:%s", m_currentVer.GetData(), m_versionEx.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ex version file is not exist [%s],use current Version, current version:%s,ex version:%s",xTmp.c_str(),m_currentVer.GetData(), m_versionEx.GetData());
- }
- }
- csAll = csSep + csBinPath + csSep + " " + staticInfo.strTerminalID;//add terminalno to guardian
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("guardian path[%s], run script[%s]", csBinPath.GetData(), csAll.GetData());
-
-
- LPTSTR szCmdline = _strdup(csAll);
- if( !CreateProcessA( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateProcess failed (%d).\n", GetLastError());
- return false;
- }
- return true;
- #else
- char app[MAX_PATH];
- memset(app, 0, sizeof(app));
- tk_process_t* process = NULL;
- tk_process_option_t option;
- csBinPath += "/guardian";
- sprintf(app, "%s %s %s %d", (const char*)csBinPath, staticInfo.strTerminalID.GetData(), "shouhu", 1);
- Dbg("path:%s, app:%s", (const char*)csBinPath, (const char*)app);
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- option.params = app;
- if (0 == process_spawn(&option, &process)) {
- Dbg("process_spawn guardian");
- FREE(process);
- return true;
- }
- Dbg("end of StartGuardian");
- return false;
- #endif //RVC_OS_WIN
- }
- bool CHealthManagerEntity::DoRestart()
- {
- LOG_FUNCTION();
- CSmartPointer<IConfigInfo> spCerConfig;
- ErrorCodeEnum err = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
- if (err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM)("open cfg file failed!");
- return false;
- }
- ErrorCodeEnum eErr = GetFunction()->GetSystemStaticInfo(m_sysStaticInfo);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Get system static info failed(%s).", SpStrError(eErr));
- m_sysStaticInfo.strMachineType = "";
- m_sysStaticInfo.strSite = "";
- m_sysStaticInfo.InstallVersion = CVersion();
- }
- m_restartHour = m_restartMinute = 1;
- //the region (RestartHourBegin,RestartHourEnd) that we should reboot VTM
- m_rebootHourBegin = 1;
- m_rebootHourEnd = 6;
- do
- {
- int value(0);
- spCerConfig->ReadConfigValueInt(GetEntityName(), "RestartHourBegin", value);
- if (value > 0 && value < 8) {
- m_rebootHourBegin = value;
- }
- } while (false);
- do {
- int value(0);
- spCerConfig->ReadConfigValueInt(GetEntityName(), "RestartHourEnd", value);
- if (value > 0 && value < 8) {
- m_rebootHourEnd = value;
- }
- } while (false);
- //to calculate the restartHour & restartMinute of the Terminal
- ToCalcRebootHourAndMinute(m_rebootHourBegin, m_rebootHourEnd);
- do {
- m_maxAbnormalTimes = 30;
- int value(0);
- spCerConfig->ReadConfigValueInt(GetEntityName(), "MaxAbnormalTimes", value);
- if (value > 0) {
- m_maxAbnormalTimes = value;
- }
- } while (false);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("MaxAbnormalTimes:%d", m_maxAbnormalTimes);
- do {
- int value(0);
- spCerConfig->ReadConfigValueInt(GetEntityName(), "StopSelfCheck", value);
- if (value == 1) {
- m_stopSelfCheck = 1;
- }
- } while (false);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_restartHour:m_restartMinute=%d:%d",m_restartHour,m_restartMinute);
- CSmartPointer<IConfigInfo> spConfigRun;
- eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->ReadConfigValue("Run", "VersionEx", m_versionEx);
- //判断上个版本号值是否为空
- if(m_versionEx.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get VersionEx is null");
- }
- spCerConfig->ReadConfigValueInt(GetEntityName(), "MaxTimeWaitMainPageMS", m_maxWaitMainpageTime);
- if (m_maxWaitMainpageTime < 5000)
- m_maxWaitMainpageTime = HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_INTERVAL;
- CSimpleStringA csimpleStrMachineTypeCfg;
- auto rc = spCerConfig->ReadConfigValue("NonExclusive", "NonGuardian", csimpleStrMachineTypeCfg);
- m_currentVer = m_sysStaticInfo.InstallVersion.ToString();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get current version [%s]", m_currentVer.GetData());
- CSimpleStringA csTermStage("");
- GetFunction()->GetSysVar("TerminalStage", csTermStage);
- if(csimpleStrMachineTypeCfg.IndexOf(m_sysStaticInfo.strMachineType)>=0 || csTermStage.Compare("N") == 0)//oilyang@20240104 N for install vtm app
- {
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_Need_No_Guardian, "terminal is not need start up guardian");
- m_bNeedGuardian = false;
- if (CheckGuardianIsRun() > 0)//or true?
- {
- bool bStop = StopGuardian();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("no need for guardian, to stop guardian:%d", bStop);
- }
-
- //设置一个系统变量给关门页面使用
- //liuwt@20220104 N noguardian Y needguardian
- eErr = GetFunction()->SetSysVar("NeedGuardian","N");
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("set NeedGuardian N failed (%s).", SpStrError(eErr));
- }
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[NonExclusive],NonGuardian=%s", csimpleStrMachineTypeCfg.GetData());
- SYSTEMTIME localTime;
- GetLocalTime(&localTime);
- ITimerListener *pListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnCheckTimeTimeout);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("set check timer %d(ms)", HEALTHMANAGER_TIMER_INTERVAL);
- GetFunction()->SetTimer(HEALTHMANAGER_TIMER_ID, pListener, HEALTHMANAGER_TIMER_INTERVAL);
- CSimpleStringA deamonBasePath = "";
- err = GetFunction()->GetPath("bin",deamonBasePath);
- if (err != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("get bin path failed(%s).", SpStrError(err));
- return false;
- }
- deamonBasePath += SPLIT_SLASH_STR;
- deamonBasePath += GUARDIAN_FILENAME;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to check if in upgrade process");
- if (m_fsm.IfInUpgradeProcess() && !m_versionEx.IsNullOrEmpty())
- {
- string xTmp(deamonBasePath.GetData());
- xTmp = xTmp.replace(xTmp.find(m_currentVer), m_currentVer.GetLength(), m_versionEx);
- //判断文件是否存在,如果不存在,则启动当前版本guardian.
- if(ExistsFileA(xTmp.c_str())){
- deamonBasePath = xTmp.c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("current version:%s,ex version:%s", m_currentVer.GetData(), m_versionEx.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ex version guardian dll(so) is not exist ,use current Version file, current version:%s,ex version:%s", m_currentVer.GetData(), m_versionEx.GetData());
- }
-
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("guardian file path [%s]", deamonBasePath.GetData());
- do
- {
- if (!ExistsFileA(deamonBasePath)) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Load guardian %s failed: no exist", (const char*)deamonBasePath);
- return false;
- }
- toolkit_lib_t guardianLib;
- int res = toolkit_dlopen(deamonBasePath, &guardianLib);
- if (res != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("toolkit_dlopen[%s] failed with error %s.", deamonBasePath.GetData(), toolkit_dlerror(&guardianLib));
- return false;
- }
- if ((res = toolkit_dlsym(&guardianLib, "ShakeHands", (void**)&m_pfShake)) != 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get 'ShakeHands' Func address failed with error: %s", toolkit_dlerror(&guardianLib));
- toolkit_dlclose(&guardianLib);
- return false;
- }
- if ((res = toolkit_dlsym(&guardianLib, "UpgradeRestart", (void**)&m_pfUpgradeRestart)) != 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get 'UpgradeRestart' Func address failed with error: %s", toolkit_dlerror(&guardianLib));
- toolkit_dlclose(&guardianLib);
- return false;
- }
- } while (false);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("have load guardian base file (dll/so).");
- if (CheckGuardianIsRun(true) > 0)
- {
- Sleep(500);
- if (m_bNeedGuardian)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("to tell guardian framework is starting.");
- //tell guardian framework is starting...oilyang 20150514
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("feedback of framework is starting.%d", m_pfUpgradeRestart(4, 0));
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("need Upgrade guardian only");
- //tell guardian framework we need Upgrade !!!Only!!! oilyang@20211221
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("feedback of need Upgrade guardian only.%d", m_pfUpgradeRestart(6, 0));
- }
- }
- return true;
- }
- bool CHealthManagerEntity::SaveCurrentVersion()
- {
- CSimpleStringA csRootVer,csRunInfo,csBakFile,csVerFile;
- ErrorCodeEnum eErr;
- if ((eErr = GetFunction()->GetPath("RootVer",csRootVer)) != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM)("Get version path failed(%s).", SpStrError(eErr));
- return false;
- }
- if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM)("get runinfo path failed(%s)", SpStrError(eErr));
- return false;
- }
- csBakFile = csRunInfo + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "version.dat";
- ofstream outfile (csBakFile,std::ofstream::binary);
- CSmartPointer<IConfigInfo> spConfigRun;
- eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("SaveCurrentVersion open run cfg file failed(%s)!", SpStrError(eErr));
- return -1;
- }
- else
- spConfigRun->WriteConfigValue("Run", "VersionEx", m_currentVer);
- int size = m_currentVer.GetLength();
- char* buffer = new char[size];
- ZeroMemory(buffer,size);
- //infile.read (buffer,size);
- memcpy(buffer, m_currentVer,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)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("get runinfo path failed(%s)", SpStrError(eErr));
- return false;
- }
- csBakFile = csRunInfo + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "starttime.dat";
- ofstream outfile (csBakFile,std::ofstream::binary);
- CSystemRunInfo sysRunInfo;
- GetFunction()->GetSystemRunInfo(sysRunInfo);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get system run info failed(%s).", SpStrError(eErr));
- return false;
- }
- CSimpleStringA csStartTime = sysRunInfo.tmStart.ToTimeString();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get current time start [%s]", csStartTime.GetData());
- 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;
- }
- void CHealthManagerEntity::ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
- {
- if (ctx->Req.key.IsNullOrEmpty() || ctx->Req.entity.IsNullOrEmpty())
- ctx->Answer(Error_Param);
- else
- {
- CSimpleStringA str = "";
- CSmartPointer<IConfigInfo> spCerConfig;
- ErrorCodeEnum eErrCode = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
- if (eErrCode == Error_Succeed)
- spCerConfig->ReadConfigValue(ctx->Req.entity, ctx->Req.key, str);
- ctx->Ans.value = str;
- ctx->Answer(Error_Succeed);
- }
- }
- void CHealthManagerEntity::QueryCenterCfg(SpReqAnsContext<HealthManagerService_QueryCenterCfg_Req, HealthManagerService_QueryCenterCfg_Ans>::Pointer ctx)
- {
- if (ctx->Req.key.IsNullOrEmpty() || ctx->Req.module.IsNullOrEmpty())
- ctx->Answer(Error_Param);
- else
- {
- CSimpleStringA str = "";
- CSmartPointer<IConfigInfo> spCerConfig;
- ErrorCodeEnum eErrCode = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
- if (eErrCode == Error_Succeed)
- spCerConfig->ReadConfigValue(ctx->Req.module.GetData(), ctx->Req.key, str);
- ctx->Ans.value = str;
- ctx->Answer(Error_Succeed);
- }
- }
- void CHealthManagerEntity::GetAuthErrMsg(SpReqAnsContext<HealthManagerService_GetAuthErrMsg_Req, HealthManagerService_GetAuthErrMsg_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- CSimpleStringA tmp;
- GetFunction()->GetSysVar("AuthErrMsg", tmp);//获取错误页信息
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetAuthErrMsg msg = %s", tmp.GetData());
- ctx->Ans.errMsg = tmp;
- ctx->Answer(Error_Succeed);
- }
- void CHealthManagerEntity::OnLog(const CAutoArray<CUUID>& SubIDs, const CUUID nLogID, const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
- const DWORD dwSysError, const DWORD dwUserCode, const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
- const CAutoArray<DWORD>& Param, const char* pszEntityName, const char* pszModuleName, const char* pszMessage, const linkContext& pLinkInfo)
- {
- if (dwUserCode != LOG_EVT_IEBROWSER_MOUSE_OP)
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("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 Event_Req_Framework_No_Upgrade_Restart://升级请求重启框架(体系外升级等等)
- case Event_Req_Framework_Rollback_Restart:
- case Event_DeviceAdapterUpgrade_Framework_Restart://适配器升级,重启应用
- case Event_DeviceAdapterRollBack_Framework_Restart://适配器回退,重启应用
- {
- //TODO oilyang@20230613 all of the Privilege CMD need to been collated
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_PrivilegeCMD, CSimpleStringA::Format("%x", dwUserCode));
- int iCheckGuardian = CheckGuardianIsRun();
- if (iCheckGuardian < 0)
- {
- bool bStartGuardian = StartGuardian();
- if (!bStartGuardian)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Before restart frame,start guardian failed.");
- break;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Before restart frame,start guardian suc.");
- Sleep(2000);
- }
- if (dwUserCode == Event_Req_Framework_Restart)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_Req_Framework_Restart.!!!!");
- FrameworkRestartTask* task = new FrameworkRestartTask(this); //版本升级,有监控
- task->eWarmPageType = WarmPageType_TerminalUpgrade;
- task->needVerctrl = true;
- task->eTrigger = RebootTrigger_FrameUpgrade;
- task->eWay = RebootWay_Framework;
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- else if (dwUserCode == Event_Req_Framework_Rollback)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("version rollback succeed.to restart framework");
- FrameworkRestartTask* task = new FrameworkRestartTask(this); //心跳重启,无监控
- task->eWarmPageType = WarmPageType_HeartBeatRollBack;
- task->eTrigger = RebootTrigger_RollBack;
- task->eWay = RebootWay_Framework;
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- else if (dwUserCode == Event_Req_Framework_No_Upgrade_Restart)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_Req_Framework_No_Upgrade_Restart.!!!!");
- FrameworkRestartTask* task = new FrameworkRestartTask(this); //体系外升级,无监控
- task->eWarmPageType = WarmPageType_ThirdPartyUpgrade;
- task->eTrigger = RebootTrigger_ThirdPartyUpgrade;
- task->eWay = RebootWay_Framework;
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- else if (dwUserCode == Event_Req_Framework_Rollback_Restart)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("version rollback succeed.to restart framework");
- FrameworkRestartTask* task = new FrameworkRestartTask(this); //回退,无监控
- task->eWarmPageType = WarmPageType_UpgradeRollBack;
- task->eTrigger = RebootTrigger_RollBack;
- task->eWay = RebootWay_Framework;
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- else if (dwUserCode == Event_DeviceAdapterUpgrade_Framework_Restart || dwUserCode == Event_DeviceAdapterRollBack_Framework_Restart)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("DeviceAdapter upgrade/rollback succeed.to restart framework");
- FrameworkRestartTask* task = new FrameworkRestartTask(this);
- task->eWarmPageType = WarmPageType_DeviceAdapterUpgrade;
- task->eTrigger = RebootTrigger_DeviceAdapterUpgrade;
- task->eWay = RebootWay_Framework;
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Unknown, RebootWay_Framework);
- }
- break;
- case EVENT_RESTART_MACHINE:
- case Event_Req_OS_Restart://case os restart after outside update
- case Event_Req_OS_Upgrade_Restart:
- case EVENT_CONSOLE_REQ_RESTART_POWER:
- case Event_DeviceAdapterUpgrade_OS_Restart:
- case Event_DeviceAdapterRollBack_OS_Restart:
- {
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_PrivilegeCMD, CSimpleStringA::Format("%x", dwUserCode));
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("restart [%x]", dwUserCode);
- if (dwUserCode == Event_Req_OS_Restart)
- {
- FrameworkRestartTask* task = new FrameworkRestartTask(this);
- task->eTrigger = RebootTrigger_OSUpgrade;
- task->eWay = RebootWay_OS;
- GetFunction()->PostThreadPoolTask(task);
- }
- else if (dwUserCode == Event_Req_OS_Upgrade_Restart)
- {
- FrameworkRestartTask* task = new FrameworkRestartTask(this);
- task->eWarmPageType = WarmPageType_TerminalUpgrade;
- task->needVerctrl = true;
- task->eTrigger = RebootTrigger_OSUpgrade;
- task->eWay = RebootWay_OS;
- GetFunction()->PostThreadPoolTask(task);
- }
- else if (dwUserCode == Event_DeviceAdapterUpgrade_OS_Restart || dwUserCode == Event_DeviceAdapterRollBack_OS_Restart)
- {
- FrameworkRestartTask* task = new FrameworkRestartTask(this);
- task->eWarmPageType = WarmPageType_DeviceAdapterUpgrade;
- task->eTrigger = RebootTrigger_DeviceAdapterUpgrade;
- task->eWay = RebootWay_OS;
- GetFunction()->PostThreadPoolTask(task);
- }
- else
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Unknown, RebootWay_OS);
- }
- break;
- case LOG_EVT_IEBROWSER_RESTART_MACHINE:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("machine restart now [%x]", dwUserCode);
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_IEBROWSER_RESTART_MACHINE, "ClosePage/UserDeskTop to call restart machine.");
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Unknown, RebootWay_OS);
- break;
- }
- case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ClosePage/UserDeskTop to call shutdown machine. [%x]", dwUserCode);
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE, "ClosePage/UserDeskTop to call shutdown machine.");
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_OS);
- break;
- }
- case EVENT_MOD_SIP_RESART:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SIPPhone said to wait chance to restart(power) pc.");
- m_bWaitRestartPC = true;
- break;
- case EVENT_ACCESSAUTH_SUCCEED:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501B1")("access auth succeed.");
- m_fsm.SetVtmLoadResult(VtmLoad_AccessAuth_Suc);
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = true;
- m_dwTimeOfAuthSuc = SP::Module::Comm::RVCGetTickCount() / 1000;
- GetFunction()->SetTimer(HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_ID, this, m_maxWaitMainpageTime);
- CSimpleStringA msg(true);
- GetFunction()->GetSysVar("AuthErrMsg", msg);
- Dbg("AuthErrMsg 在healthmanager的内容是: %s.", msg.GetData());
- if (msg.GetLength() != 0)
- {
- WarnPromptTask* task = new WarnPromptTask(this); //通过工作线程弹窗并告警
- GetFunction()->PostThreadPoolTask(task);
- }
- ITimerListener* pListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnSelfCheckTimeout);
- GetFunction()->SetTimer(HEALTHMANAGER_SELFCHECK_TIMER_ID, pListener, HEALTHMANAGER_SELFCHECK_TIMER_INTERVAL);
- break;
- } //oilyang@20210331 distinguish reasons of accessauth failed to decide what to do next
- //case EVENT_ACCESSAUTH_FAILED:
- //case EVENT_ACCESSAUTH_TIMEOUT:
- case CONTROL_ACCESSAUTH_NORETRY_NORESTART:
- case CONTROL_ACCESSAUTH_RETRY_NORESTART:
- case CONTROL_ACCESSAUTH_RETRY_RESTART:
- case CONTROL_ACCESSAUTH_UNKNOWN:
- {
- if (dwUserCode == CONTROL_ACCESSAUTH_NORETRY_NORESTART) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501F1").setResultCode("RTA5108")("receive accessauth failed result:%d. no retry,no restart.", dwUserCode);
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = false;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_NORESTART) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501F1").setResultCode("RTA5109")("receive accessauth failed result:%d. retry,no restart.", dwUserCode);
- m_bNeedAuthRetry = true;
- m_bNeedGuardianRestart = false;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_RESTART) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501F1").setResultCode("RTA510A")("receive accessauth failed result:%d. retry,restart.", dwUserCode);
- m_bNeedAuthRetry = true;
- m_bNeedGuardianRestart = true;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_UNKNOWN) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501F1").setResultCode("RTA510B")("receive accessauth failed result:%d. unknown access failed.no retry,restart.", dwUserCode);
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = true;
- }
- m_fsm.SetVtmLoadResult(VtmLoad_AccessAuth_Fail);
- if (m_bNeedAuthRetry)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501F2")("retry AccessAuth");
- m_fsm.ToReAccessAuth();
- }
- }
- break;
- case ERR_ACCESSAUTH_SERVICE_FAILED: //准入服务告知禁止此终端准入,无需重试,无需guardian重启
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501F1").setResultCode("RTA510C")("service forbid this terminal, no retry, no restart:(usercode)%d", dwUserCode);
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = false;
- m_fsm.SetVtmLoadResult(VtmLoad_AccessAuth_servFail);
- }
- //m_fsm.SetVtmLoadResult(VtmLoad_AccessAuth_Suc);//oiltest
- break;
- case EVENT_MOD_RELEASESIP_TIMEOUT:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RELEASESIP_TIMEOUT.");
- RestartModule("SIPPhone");
- break;
- case LOG_EVT_HEALTHMANAGER_BROWSER_IDLE:
- //IE重启之后,重置是否进入主页变量
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Browser(Chromuim) to idle.");
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_Receive_Browser_Idle
- , "Browser(Chromuim) to idle.");
- break;
- case LOG_EVT_PINPAD_OPEN_SUC:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("PinPad open suc.");
- m_fsm.SetPinPadOpenSuc();
- break;
- case EVENT_MOD_CENTERSETTING_CRITICAL_UPDATE:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CenterSetting update some critical item,we need to restart framework.");
- m_bToRestartByCenterSetting = true;
- 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 (!CheckIfHaveEnterMainPageEver())
- {
- CSystemRunInfo sysRunInfo;
- if (GetFunction()->GetSystemRunInfo(sysRunInfo) != Error_Succeed || sysRunInfo.eAppBootState == AppBootState_CallAccessAuth)
- GetFunction()->GetPrivilegeFunction()->RefreshAppBootState(AppBootState_FirstEnterMainPage);
-
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartTimes", 0);
- spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartOSTimes", 0);
- ULONGLONG dwElapse = SP::Module::Comm::RVCGetTickCount();//使用机器启动时间秒数
- DWORD elapseTimeTemp = dwElapse / 1000;
- DWORD dwToMainPageCostTime = elapseTimeTemp - m_dwTimeOfAuthSuc;//从准入通过到首次收到进入首页事件
- CSimpleStringA xMsg = CSimpleStringA::Format("{\"Decripstion\":\"the first enter main page from HealthManger started.\",\"version\":\"%s\",\"elapseTime\":\"%d\",\"enterMainPageTime\":\"%d\"}"
- , m_sysStaticInfo.InstallVersion.ToString().GetData(), elapseTimeTemp, dwToMainPageCostTime);
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START, xMsg.GetData());
- //oilyang@20230518 最大设置时间的3倍、2倍、1倍还没进入首页
- if (dwToMainPageCostTime > m_maxWaitMainpageTime / 1000 * 3)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501B2").setResultCode("RTA5106").setCostTime(dwToMainPageCostTime)(m_sysStaticInfo.InstallVersion.ToString().GetData());
- else if (dwToMainPageCostTime > m_maxWaitMainpageTime / 1000 * 2)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501B2").setResultCode("RTA5105").setCostTime(dwToMainPageCostTime)(m_sysStaticInfo.InstallVersion.ToString().GetData());
- else if (dwToMainPageCostTime > m_maxWaitMainpageTime / 1000)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501B2").setResultCode("RTA5104").setCostTime(dwToMainPageCostTime)(m_sysStaticInfo.InstallVersion.ToString().GetData());
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501B2").setCostTime(dwToMainPageCostTime)(m_sysStaticInfo.InstallVersion.ToString().GetData());
- }
- }
- else
- m_bInMainPage = false;
- }
- }
- void CHealthManagerEntity::OnBroadcastEvent(CUUID SubID, const char *pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer)
- {
- }
- void CHealthManagerEntity::OnTimeout(DWORD dwTimeID)
- {
- switch (dwTimeID)
- {
- case HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_ID:
- if (!CheckIfHaveEnterMainPageEver())
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setResultCode("RTA5101")
- ("After receive accessauth success event, havn't receive enter main page.", m_maxWaitMainpageTime / 1000);
- break;
- default:
- break;
- }
- }
- bool CHealthManagerEntity::StartManagerDesktopPage(CSimpleStringA pageName)
- {
- Sleep(10000);
- ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(this);
- ErrorCodeEnum error = chromiumClient->Connect();
- if (error == Error_Succeed)
- {
- ChromiumSrv_OpenBrowser_Req req;
- ChromiumSrv_OpenBrowser_Ans ans;
- int width = 0;
- int height = 0;
- #ifdef RVC_OS_WIN
- width = GetSystemMetrics(SM_CXSCREEN);
- height = GetSystemMetrics(SM_CYSCREEN);
- #else
- struct winsize size;
- ioctl(STDIN_FILENO, TIOCGWINSZ, &size);
- width = size.ws_row;
- height = size.ws_col;
- #endif // RVC_OS_WIN
- auto pFunc = GetFunction();
- CSimpleStringA strPath, statusPagePath, fileStart;
- fileStart = "file:///";
- pFunc->GetPath("Bin", strPath);
- strPath += "\\Chromium\\cefclient.exe";
- pFunc->GetPath("Bin", statusPagePath);
- statusPagePath = statusPagePath + CSimpleStringA("/../res/ManagerDesktop/") + pageName;
- statusPagePath = fileStart + statusPagePath;
- req.mainUrl = statusPagePath;
- req.type = "SpecialPageFromOtherEntity";
- req.name = "tempMessage";
- req.param1 = CSimpleStringA::Format("%d*%d", width, height);
- req.param2 = CSimpleStringA::Format("0*0");
- req.top = -1;
- error = (*chromiumClient)(EntityResource::getLink().upgradeLink())->OpenBrowser(req, ans, 10000);
- chromiumClient->GetFunction()->CloseSession();
- if (error != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] failed.", statusPagePath.GetData());
- return false;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] success.", statusPagePath.GetData());
- return true;
- }
- }
- return false;
- }
- void CHealthManagerEntity::WarnAndRestartFunc(RebootTriggerEnum eTrigger, RebootWayEnum eWay, WarmPageTypeEnum eWarmPageType, bool needVerctrl)
- {
- switch (eWarmPageType)
- {
- case WarmPageType_TerminalUpgrade:
- StartManagerDesktopPage("TerminalUpgradeRestart.html");
- Sleep(5000);//oiltmp to be defined ???
- break;
- case WarmPageType_DeviceAdapterUpgrade:
- StartManagerDesktopPage("DeviceAdapterUpgradeRestart.html");
- Sleep(5000);//oiltmp to be defined ???
- break;
- case WarmPageType_HeartBeatRollBack:
- StartManagerDesktopPage("HeartBeatRollBackRestart.html");
- Sleep(5000);//oiltmp to be defined ???
- break;
- case WarmPageType_UpgradeRollBack:
- StartManagerDesktopPage("UpgradeRollBackRestart.html");
- Sleep(5000);//oiltmp to be defined ???
- break;
- case WarmPageType_ThirdPartyUpgrade:
- StartManagerDesktopPage("ThirdPartyUpgradeRestart.html");
- Sleep(5000);//oiltmp to be defined ???
- break;
- case WarmPageType_None:
- default:
- break;
- }
- if (needVerctrl)
- {
- SaveCurrentVersion();
- SaveFrameStartTimeForUpgrade();
- if (CheckGuardianIsRun(true) > 0)
- {
- ErrorCodeEnum eErr = Error_Unexpect;
- //Dbg("to tell guardian framework is restarting.%d",eErr);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to tell guardian framework is restarting.%d", m_pfUpgradeRestart(1, 0));
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("framework shutdown in restart task");
- }
- m_fsm.QuitFrameworkAndSaveInfo(eTrigger, eWay);
- }
- void CHealthManagerEntity::OnEntityStateHook(const char* pszEntityName, const char* pszTriggerEntity, EntityStateEnum eState, EntityStateEnum eLastState)
- {
- if (m_fsm.CheckIsRebooting())//oilyang@20250415 no need to process entity state changing event while in rebooting
- return;
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("NoPrivilege");
- return;
- }
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum errCode;
- {
- switch (eState)
- {
- case EntityState_Lost:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s trigger by %s: from %s to %s", pszEntityName, pszTriggerEntity, SpStrEntityState(eLastState), SpStrEntityState(eState));
- CSimpleStringA tmpWarnMsg = CSimpleStringA::Format("%s lost. trig entity:%s,lastState:%s", pszEntityName, pszTriggerEntity, SpStrEntityState(eLastState));
- CEntityStaticInfo esi = { 0 };
- ErrorCodeEnum ec = GetFunction()->GetEntityStaticInfo(pszEntityName, esi);
- //0x101 0x21D
- int iByteHigh, iByteLow;
- iByteHigh = (esi.wEntityDevelopID & 0xF00) >> 8;
- iByteLow = esi.wEntityDevelopID & 0xFF;
- if (iByteHigh < 1 || iByteHigh > 9)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Unexpected entity id:%x", esi.wEntityDevelopID);
- break;
- }
- CSimpleStringA csResultCode(true);
- //实体lost的RTAxxxx的后两位xx,规则同RTAxxxx的前两位xx(实体标识码),由实体编号自动生成。健康实体本身的自定义RTAxxxx应该避开这些自定义
- //'0':0x30 'A':0x41
- if (iByteLow > 0 && iByteLow < 10)
- csResultCode = CSimpleStringA::Format("RTA51%c%c", iByteHigh + 0x30, iByteLow + 0x30);
- else
- csResultCode = CSimpleStringA::Format("RTA51%c%c", iByteHigh + 0x30, iByteLow - 10 + 0x41);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("resultcode:%s", csResultCode.GetData());
- LogWarn(Severity_High, Error_Unexpect, HealthManager_UserErrorCode_EntityLost_Start + esi.wEntityDevelopID, tmpWarnMsg.GetData());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501S1").setResultCode(csResultCode.GetData())(tmpWarnMsg.GetData());
- //doing nothing before enter main page. HandShake will take it.
- //AND if selfcheck is doing, no action at all
- if (CheckIfHaveEnterMainPageEver() && m_modRunInfo[pszEntityName].abnormalCount < m_maxAbnormalTimes && !m_modRunInfo[pszEntityName].bAbnormalBusy)
- {
- m_modRunInfo[pszEntityName].bAbnormalBusy = true;
- m_modRunInfo[pszEntityName].abnormalCount++;
- EntityLostProcTask* task;
- task = new EntityLostProcTask(this, pszEntityName);
- GetFunction()->PostThreadPoolTask(task);
- }
- }
- break;
- case EntityState_Idle:
- {
- if (_strnicmp("Chromium", pszEntityName, strlen("Chromium")) == 0)
- LogEvent(Severity_Middle, LOG_EVT_HEALTHMANAGER_BROWSER_IDLE, "Chromium to idle.");
- }
- default:
- break;
- }
- }
- }
- void CHealthManagerEntity::ToCalcRebootHourAndMinute(int restartBegin, int restartEnd)
- {
- if (m_sysStaticInfo.strTerminalID.GetLength() < 6)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("wrong terminalNo:[%s]", m_sysStaticInfo.strTerminalID.GetData());
- return;
- }
- if ((restartBegin <= 0 || restartEnd <= 0) || restartEnd < restartBegin || restartEnd > 7)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("wrong setting,restartBegin:%d,restartEnd:%d, use default (1-6)", restartBegin, restartEnd);
- restartBegin = 1;
- restartEnd = 6;
- }
- //以1分钟对重启区间进行切片,截取终端号前6位+最后1位,进行取模hash到重启区间
- int modNum = (restartEnd - restartBegin) * 60 -1;//if the modNum like 300 or 200 ,the remainder is not random ,because the TerminalNo is not random
- int xTerm = atoi(m_sysStaticInfo.strTerminalID.SubString(0, 6) + m_sysStaticInfo.strTerminalID.SubString(m_sysStaticInfo.strTerminalID.GetLength() - 1, 1));
- int minutes = xTerm % modNum;
- m_restartHour = 1 + (minutes / 60);
- m_restartMinute = minutes - (m_restartHour - 1) * 60;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("restartBegin:%d, restartEnd:%d, xTerm:%d, minutes:%d, m_restartHour:%d, m_restartMinute:%d", restartBegin, restartEnd, xTerm, minutes, m_restartHour, m_restartMinute);
- }
- void CHealthManagerEntity::RealCheck(SpReqAnsContext<HealthManagerService_RealCheck_Req, HealthManagerService_RealCheck_Ans>::Pointer ctx)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501R1")("%s", ctx->Req.name.GetData());
- CheckEntity(ctx->Req.name, Test_ShakeHand);
- ctx->Answer(Error_Succeed);
- }
- void CHealthManagerEntity::OnAnswer(CSmartPointer<IAsynWaitSp> pAsynWaitSp)
- {
- CSmartPointer<ICallbackListener> spCallback;
- CSmartPointer<IReleasable> pData;
- pAsynWaitSp->GetCallback(spCallback, pData);
- //LOG_ASSERT(pData);
- callback_entry* entry = dynamic_cast<callback_entry*>((IReleasable*)pData.GetRawPointer());
- entry->ErrorResult = pAsynWaitSp->AsyncGetAnswer();
- callback_entry* new_entry = new callback_entry();
- new_entry->EntityName = entry->EntityName;
- new_entry->ErrorResult = entry->ErrorResult;
- new_entry->op = entry->op;
- new_entry->state = entry->state;
- if (new_entry->op == Test_ShakeHand && new_entry->ErrorResult != Error_Succeed) {
- if (!m_modRunInfo[new_entry->EntityName].bAbnormalBusy)
- {
- ExceptionErrorProcess((const char*)new_entry->EntityName, new_entry->ErrorResult);
- std::map<std::string, std::string> msgInfo;
- msgInfo["EntityName"] = new_entry->EntityName.GetData();
- msgInfo["EntityState"] = SpStrEntityState((EntityStateEnum)new_entry->state);
- msgInfo["SelfTestReturnCode"] = SpStrError(new_entry->ErrorResult);
- std::pair<bool, std::string> strResult;
- strResult = generateJsonStr(msgInfo);
- //oilyang@20250604 don't log "Error_DevNotAvailable" any more
- if (new_entry->ErrorResult != Error_DevNotAvailable)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501S2")(strResult.second.c_str());
- }
- }
- }
- ErrorCodeEnum CHealthManagerEntity::ExceptionErrorProcess(const char* pszEntityName, ErrorCodeEnum eTestResult)
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum eErrCode = Error_Unexpect;
- switch (eTestResult)
- {
- case Error_TimeOut:
- case Error_Unexpect:
- case Error_InvalidState:
- {
- m_modRunInfo[pszEntityName].bAbnormalBusy = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ExceptionErrorProcess %s, abnormalCount:%d", pszEntityName, m_modRunInfo[pszEntityName].abnormalCount);
- m_modRunInfo[pszEntityName].abnormalCount++;
- eErrCode = pFuncPrivilege->StopEntity(pszEntityName, spWait);
- if (eErrCode == Error_Succeed)
- {
- eErrCode = spWait->WaitAnswer(MAX_STOP_AYSNC_TIMEOUT);
- if (eErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("spwait stop %s failed: %s.", pszEntityName, SpStrError(eErrCode));
- eErrCode = pFuncPrivilege->TerminateEntity(pszEntityName, spWait);
- eErrCode = spWait->WaitAnswer(MAX_TERM_AYSNC_TIMEOUT);
- if (eErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("spwait terminate %s failed: %s.", pszEntityName, SpStrError(eErrCode));
- m_modRunInfo[pszEntityName].bAbnormalBusy = false;
- break;
- }
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Stop %s failed(%d).", pszEntityName, eErrCode);
- m_modRunInfo[pszEntityName].bAbnormalBusy = false;
- break;
- }
- Sleep(2000);
- eErrCode = pFuncPrivilege->StartEntity(pszEntityName, NULL, spWait);
- if (eErrCode == Error_Succeed)
- {
- eErrCode = spWait->WaitAnswer(MAX_START_AYSNC_TIMEOUT);
- if (eErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("spwait start %s failed(%d).", pszEntityName, eErrCode);
- m_modRunInfo[pszEntityName].bAbnormalBusy = false;
- break;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start entity %s suc.", pszEntityName);
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("(re)Start %s failed(%d).", pszEntityName, eErrCode);
- m_modRunInfo[pszEntityName].bAbnormalBusy = false;
- break;
- }
- m_modRunInfo[pszEntityName].bAbnormalBusy = false;
- }
- break;
- default:
- break;
- }
- return eErrCode;
- }
- ErrorCodeEnum CHealthManagerEntity::CheckEntity(const char* pszEntityName, EntityTestEnum eTestType)
- {
- //oilyang@20170926 no need to check by self.Let the HealthManager entity to do it.
- //oilyang@20231106 no need to check VtmLoader
- if (pszEntityName != NULL && (strnicmp(pszEntityName, GetEntityName(), strlen(GetEntityName())) == 0
- || strnicmp(pszEntityName, "VtmLoader", strlen("VtmLoader")) == 0))
- return Error_Succeed;
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum errCode;
- errCode = pFuncPrivilege->TestEntity(pszEntityName, eTestType, spWait);
- if (errCode == Error_Succeed)
- {
- callback_entry* entry = new callback_entry();
- entry->pRawData = NULL;
- entry->EntityName = pszEntityName;
- entry->ErrorResult = Error_Unexpect;
- entry->op = Test_ShakeHand;
- spWait->SetCallback(this, entry);
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Test %s,%d", pszEntityName, errCode);
- return errCode;
- }
- void CHealthManagerEntity::OnSelfCheckTimeout()
- {
- if (m_stopSelfCheck == 1 || m_fsm.CheckIsRebooting())
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("stop self check OR is rebooting");
- return;
- }
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum errCode;
- int activeEnCount = m_activeEntity.GetCount();
- //oilyang@20230426 ,常规自检时,针对"TerminalStage"做对应处理(自检分常规自检和即时自检)
- //"S":准入服务告知准入不过,不再进行实体自检
- //非"A":其他启动失败导致进关门页,不再对硬件以及其他没必要自检的实体进行自检
- CSimpleStringA tmpTerminalStage("");
- GetFunction()->GetSysVar("TerminalStage", tmpTerminalStage);
- for (int i = 0; i < activeEnCount; ++i)
- {
- if (m_fsm.CheckIsRebooting())
- break;
- CSimpleStringA pszEntityName(m_activeEntity[i]);
- //invalid or "HealthManager" itself,no need to check
- //
- if (m_activeEntity[i].IsNullOrEmpty() || m_activeEntity[i].Compare(GetEntityName()) == 0)
- continue;
- if (tmpTerminalStage.Compare("S") == 0)
- continue;
- else if (tmpTerminalStage.Compare("A") != 0)
- {
- //the hardward entity and some other entity no need to test
- if (_strnicmp("PinPad", pszEntityName, strlen("PinPad")) == 0
- || _strnicmp("CardIssuerStand", pszEntityName, strlen("CardIssuerStand")) == 0 || _strnicmp("CardIssuerStore", pszEntityName, strlen("CardIssuerStore")) == 0
- || _strnicmp("ContactlessCard", pszEntityName, strlen("ContactlessCard")) == 0
- || _strnicmp("IDCertificate", pszEntityName, strlen("IDCertificate")) == 0
- || _strnicmp("gpio", pszEntityName, strlen("gpio")) == 0 || _strnicmp("HSPScanner", pszEntityName, strlen("HSPScanner")) == 0
- || _strnicmp("FingerPrint", pszEntityName, strlen("FingerPrint")) == 0
- )
- continue;
- }
- //oilyang@20240524 abnormal within MAX limited times, AND NOT in lost process, else no check at all
- if (m_modRunInfo[pszEntityName].abnormalCount < m_maxAbnormalTimes && !m_modRunInfo[pszEntityName].bAbnormalBusy)
- CheckEntity(m_activeEntity[i].GetData(), Test_ShakeHand);
- }
- GetFunction()->ResetTimer(HEALTHMANAGER_SELFCHECK_TIMER_ID, HEALTHMANAGER_SELFCHECK_TIMER_INTERVAL);
- }
- void CHealthManagerEntity::EntityLostProc(CSimpleStringA entityName)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EntityLostProc %s, lost %d times from VTM started", entityName.GetData(), m_modRunInfo[entityName].abnormalCount);
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum eErrCode = pFuncPrivilege->TerminateEntity(entityName, spWait);
- if (eErrCode == Error_Succeed)
- {
- eErrCode = spWait->WaitAnswer(10000);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("on lost kill wait %d", eErrCode);
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("on lost kill %d", eErrCode);
- Sleep(5000);
- eErrCode = pFuncPrivilege->StartEntity(entityName, NULL, spWait);
- if (eErrCode == Error_Succeed)
- {
- eErrCode = spWait->WaitAnswer(10000);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("on lost start wait %d", eErrCode);
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("on lost start %d", eErrCode);
- if (CheckIfHaveEnterMainPageEver() && _strnicmp("TokenKeeper", entityName, strlen("TokenKeeper")) == 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("TokenKeeper lost");
- m_fsm.ToReAccessAuth();
- }
- m_modRunInfo[entityName].bAbnormalBusy = false;
- }
- bool CHealthManagerEntity::CheckIfHaveEnterMainPageEver()
- {
- if (!m_bSayIdle)
- {
- CSystemRunInfo sysRunInfo;
- if (GetFunction()->GetSystemRunInfo(sysRunInfo) == Error_Succeed && sysRunInfo.eAppBootState == AppBootState_FirstEnterMainPage)
- return true;
- else
- return false;
- }
- else
- return true;
- }
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(CHealthManagerEntity)
- SP_END_ENTITY_MAP()
|