123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249 |
- // 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>
- #pragma comment( lib, "User32.lib" )
- #pragma comment( lib, "advapi32.lib" )
- #pragma comment(lib, "IPHLPAPI.lib")
- #include "..\mod_chromium\Chromium_client_g.h" //启动浏览器接口
- using namespace Chromium;
- #include <WinUser.h>
- #else
- #include <sys/wait.h>
- #include <unistd.h>
- #include <time.h>
- #include <signal.h>
- #include <dlfcn.h>
- #include <fcntl.h>
- #include <sys/reboot.h>
- #include "../mod_chromium/Chromium_client_g.h" //启动浏览器接口
- using namespace Chromium;
- #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"
- #if defined(RVC_OS_LINUX)
- #include "EntityBootStruct.h"
- #include <regex.h>
- #include "RestfulFunc.h"
- #include "api_manage_list.h"
- #include "api_manufacture_controller.h"
- #include "JsonConvertHelper.hpp"
- #endif
- using namespace std;
- #include "mod_healthmanager.h"
- #include "CommEntityUtil.hpp"
- #include "CommEntitySettings.hpp"
- #include "GetDevInfoHelper.h"
- #include "TerminalInfoQueryConn.h"
- const DWORD HEALTHMANAGER_TIMER_ID = 1;
- const DWORD HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_ID = 2;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL = 60000;
- const DWORD HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_INTERVAL = 60000;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL_MINUTE = (HEALTHMANAGER_TIMER_INTERVAL/60000)*3;
- #define WORKING_BUFFER_SIZE 15000
- #define MAX_TRIES 3
- #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
- #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
- #if defined(RVC_OS_LINUX)//oiltmp
- #include "CenterSetting_client_g.h"
- using namespace CenterSetting;
- //for defines in header file
- #include "Chromium_client_g.h"
- using namespace Chromium;
- #endif
- #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;
- };
- static void PrintTerminalRegistInfo(const TerminalRegistRet* info)
- {
- Dbg("TerminalNo: %s", info->TerminalNo);
- Dbg("DeviceNo: %s", info->DeviceNo);
- Dbg("OutletNo: %s", info->OutletNo);
- Dbg("Initializer: %s", info->Initializer);
- Dbg("PadDeviceID: %s", info->PadDeviceID);
- Dbg("MachineType: %s", info->MachineType);
- Dbg("MachineVersion: %s", info->MachineVersion);
- Dbg("Sites: %s", info->Sites);
- Dbg("EnrolAddr: %s", info->EnrolAddr);
- Dbg("Editor: %s", info->Editor);
- Dbg("State: %c", info->State);
- Dbg("PublicKey: %s", info->PublicKey);
- Dbg("FingerPrint: %s", info->FingerPrint);
- }
- 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_GetEntityCfgInfo(SpReqAnsContext<HealthManagerService_GetEntityCfgInfo_Req, HealthManagerService_GetEntityCfgInfo_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetEntityCfgInfo(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_ControlTerminalLife(
- SpReqAnsContext<HealthManagerService_ControlTerminalLife_Req, HealthManagerService_ControlTerminalLife_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->ControlTerminalLife(ctx);
- }
- void HealthManagerSession::Handle_DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->DeployTerminal(ctx);
- }
- void HealthManagerSession::Handle_ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->ControlEntityLife(ctx);
- }
- void HealthManagerSession::Handle_Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->Gateway(ctx);
- }
- //通过当前实施步骤判断当前为第几次的临时重启
- static inline int GetDeployStepFromStatus(int status)
- {
- int result(-1);
- switch (status) {
- case DeployStep_Begin:
- case DeployStep_3rdParty_FontInstall:
- case DeployStep_3rdParty_SogouInstall:
- case DeployStep_GetTerminalInfo:
- result = 0;
- break;
- case DeployStep_AdapterConfig:
- result = 1;
- break;
- case DeployStep_MediaConfig:
- case DeployStep_FetchCenterSettings:
- case DeployStep_AccessAuthorize:
- result = 2;
- break;
- default:
- result = 0;
- break;
- }
- return result;
- }
- /**
- TerminalStage
- A: 准入通过?
- C: 准入不通过?
- D:设备故障
- B:
- N:
- U:
- */
- int CHealthManagerEntity::SystemRestart(bool bPeriod, bool bImmediately, bool bNow)
- {
- if (bPeriod)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SystemRestart")("restart periodly.");
- m_restartTimes = 0;
- }
- if (bNow)
- {
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
- int x = SystemShutdown(TRUE);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SystemRestart")("From ie to shutdown %d", x);
- return 0;
- }
- SYSTEMTIME localTime;
- GetLocalTimeRVC(localTime);
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SystemRestart")("open cfg file failed!");
- return -1;
- }
- if (!m_bToRestart)
- {
- m_restartTimes++;
- if (m_restartTimes > m_maxRestartTimes)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SystemRestart")("restart too many times(%d,%d),give up.", m_restartTimes, m_maxRestartTimes);
- m_restartTimes--;
- return -1;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SystemRestart")("the %d restart.", m_restartTimes);
- spConfigRun->WriteConfigValueInt("Run", "RestartTimes", m_restartTimes);
- if (m_lastHour != localTime.wHour)
- {
- m_lastHour = localTime.wHour;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SystemRestart")("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);
- }
- return 0;
- }
- /** 这里建议改用调用框架提供的接口,关机、重启均支持 [Gifur@202135]*/
- //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)
- {
- #if defined(RVC_OS_WIN)
- //oilyang@20211213 if reboot Framework,just call "pFuncPrivilege->Reboot";if shutdown only,call sprestart
- if (bRestart)
- {
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
- return 0;
- }
- 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";
- csVerPath +="\\VTM.exe";
- if (!bRestart)
- csReFlag = "n";
- //csAll = csSep + csRestart + csSep + csBlank + csSep + csScript+csBlank + csVerPath + csSep
- // + csBlank + csSep + csReFlag + csSep;
- csAll = csSep + csRestart + csSep + csBlank + csSep + csVerPath + csSep
- + csBlank + csSep + csReFlag + csSep;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("FrameworkShutdown")("allpath[%s]",(LPCTSTR)csAll);
- LPTSTR szCmdline = _strdup(csAll);
- if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("FrameworkShutdown")("CreateProcess failed (%d).\n", GetLastError());
- return -1;
- }
- //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
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("FrameworkShutdown to call QuitFrameworkAndSaveInfo:%d,%d", m_eRebootTrigger, m_eRebootWay);
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
- return 0;//oiltestlinux
- #endif
- }
- //almost disused.
- //the function moved to Entity "SelfChecker"
- ErrorCodeEnum CHealthManagerEntity::RestartModule(const char* pEntityName)
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RestartModule")("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).setAPI("RestartModule")("add %s to modfuninfo(%d).",pEntityName,m_modRunInfo.size());
- m_modRunInfo[pEntityName].count = 1;
- m_modRunInfo[pEntityName].dwStart = GetTickCountRVC();
- }
- else
- {
- (m_modRunInfo[pEntityName].count)++;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RestartModule")("modruninfo EntityName=%s, count=%d",pEntityName,m_modRunInfo[pEntityName].count);
- }
- 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_INFO,LOG_TYPE_SYSTEM).setAPI("RestartModule")("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_INFO,LOG_TYPE_SYSTEM).setAPI("RestartModule")("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;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RestartModule")("RestartModule %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)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RestartModule")("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()
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("AfterWaitRestartPC")("restart pc NoPrivilege");
- return;
- }
- ErrorCodeEnum eErr;
- CSimpleStringA csCustomerHandle("");
- eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("AfterWaitRestartPC")("cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("AfterWaitRestartPC")("get CustomerHandle failed (%d).",eErr);
- }
- else if (csCustomerHandle[0] == 'N')
- {
- m_bWaitRestartPC = false;
- pFuncPrivilege->DisplayBlueScreen("暂停服务test");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("AfterWaitRestartPC")("time comes,restart machine");
- m_eRebootTrigger = RebootTrigger_RunExcepition;
- m_eRebootWay = RebootWay_Power;
- SystemRestart(false, true);
- }
- }
- void CHealthManagerEntity::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());
- if (m_bInMainPage || csTermStage.Compare("A"))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("THE key CenterSetting updated,we must restart framework right now.");
- m_eRebootTrigger = RebootTrigger_Resource;
- m_eRebootWay = RebootWay_Framework;
- FrameworkShutdown();
- }
- }
- SYSTEMTIME localTime;
- GetLocalTimeRVC(localTime);
- ErrorCodeEnum eErr = Error_Unexpect;
- //oilyang@20211229 add for Initializer automaticly
- if (m_bInMainPage)
- {
- //not work time
- CSmartPointer<IConfigInfo> spCerConfig;
- eErr = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
- int xTmpWorktime = 0;
- spCerConfig->ReadConfigValueInt(GetEntityName(), "WorkTimeStart", xTmpWorktime);
- if (xTmpWorktime >= 0 && xTmpWorktime <= 24)
- m_worktimeStart = xTmpWorktime;
- spCerConfig->ReadConfigValueInt(GetEntityName(), "WorkTimeEnd", xTmpWorktime);
- if (xTmpWorktime >= 0 && xTmpWorktime <= 24)
- m_worktimeEnd = xTmpWorktime;
- //oilyang@20230815 no need to do the useless things "cost so much,get almont none"
- //if (!(m_worktimeStart <= localTime.wHour && localTime.wHour < m_worktimeEnd))
- // m_fsm.CheckIfNeedAutoInit();
- }
- //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<IConfigInfo> spConfigRun;
- eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr != Error_Succeed)
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("timer open cfg file failed!");
- else
- {
- if (localTime.wHour != m_lastHour)
- {
- spConfigRun->WriteConfigValueInt("Run", "RestartTimes", 0);
- }
- }
- 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<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (m_maxRunDays <= 0)
- m_maxRunDays = 7;
- if (osRunDays >= m_maxRunDays)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("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)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("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);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("restart machine[%d][%d] bRet=%d, LastError=%d", localTime.wHour, localTime.wMinute, bRet, GetLastError()); }
- }
- }
- 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_fsm.GetAccessAuthFlag() && (m_bEnterMainPageEver || (!m_bEnterMainPageEver && m_fsm.IfIEBeforeHealth())))//oilyang 20161219 改成通过是否成功进入主页来判断IE情况
- {
- iCheckGuardian = CheckGuardianIsRun(true);
- if (!m_bSayIdle)
- {
- m_bSayIdle = true;
- if (iCheckGuardian > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- eErr = m_pfUpgradeRestart(3, 0);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("healthmanager say idle,so tell the guardian.%d", eErr);
- }
- }
- CSimpleStringA csRunInfo,csStartTime;
- if ((GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("get runinfo path failed");
- #if defined(RVC_OS_WIN)//oiltmp@20230801 ???为什么在失败时候要删除?
- DeleteFileA("d:\\Run\\runinfo\\runcfg\\starttime.dat");
- DeleteFileA("c:\\Run\\runinfo\\runcfg\\starttime.dat");
- #endif
- }
- else
- {
- #if defined(RVC_OS_WIN)
- csStartTime = csRunInfo + "\\runcfg\\starttime.dat";
- int ret = DeleteFileA(csStartTime);
- #else
- csStartTime = csRunInfo + "/runcfg/starttime.dat";
- int ret = remove(csStartTime);
- #endif
- if (ret == 0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("delete time file [%s] error.[%d]", csStartTime.GetData(),GetLastError());
- }else{
- //清理前次记录的guardian版本记录
- spConfigRun->WriteConfigValue("Run", "VersionEx", "");
- }
- }
- }
-
- if (iCheckGuardian > 0)
- {
- if (m_pfShake != NULL)
- {
- WorkStateEnum eShake;
- ErrorCodeEnum eErrShake = m_pfShake(eShake);
- }
- if (!m_bHealthInit)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("准备重新启动guardian");
- bool bStop = StopGuardian();
- if (bStop)
- {
- m_bHealthInit = true;
- bool bGuardian = StartGuardian();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("restart guardian %d", bGuardian);
- }
- }
- }
- else if (iCheckGuardian == -1)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("未启动guardian,准备启动guardian");
- bool bGuardian = StartGuardian();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("start guardian %d",bGuardian);
- }
- }
- else
- {
- //oilyang@20190905 add if auth suc,tell guardian,for upgrade
- if (m_fsm.GetAccessAuthFlag())
- {
- if (CheckGuardianIsRun(true) > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- eErr = m_pfUpgradeRestart(5, 0);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("auth suc,so tell the guardian.%d", eErr);
- }
- }
- }
- }
- }
- else
- {
- m_bSayIdle = false;
- }
- //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;
- eErr = m_pfShake(eShake);
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI("OnCheckTimeTimeout")("accessauth told me not to restart framework,so that it can have time to retry.%d", eErr);
- }
- }
- }
- 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).setAPI("OnCheckTimeTimeout")("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(pid_t &pid)
- {
- char* relate_processes[] = { "guardian" };
- int count = 1;
- alive_process_info processes[1];
- memset(processes, 0, sizeof(processes));
- osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
- if (count > 0) {
- pid = processes[0].pid;
- return true;
- }
- return false;
- }
- #endif //RVC_OS_LINUX
- int CHealthManagerEntity::CheckGuardianIsRun(bool bStart)
- {
- if (!m_bNeedGuardian)//no need guardian
- return 0;
- #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)
- {
- //Dbg("guardian is running.");
- return true;
- }
- } while (Process32Next(hSnapshot, &pe));
- }
- CloseHandle(hSnapshot);
- }
- Sleep(1000);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CheckGuardianIsRun")("cannot find guardian.");
- if (bStart)
- return StartGuardian();
- else
- return false;
- #else
- Dbg("to check guardian is online.");
- pid_t pID;
- bool bFind = false;
- bFind = FindGuardianPid(pID);
- if (bFind)
- {
- Dbg("find guardian");
- 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!");
- if (bStart)
- return StartGuardian();
- else
- return false;
- }
- }
- if (bStart)
- return StartGuardian();
- else
- return false;
- #endif //RVC_OS_WIN
- }
- bool CHealthManagerEntity::StopGuardian()
- {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopGuardian")("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_INFO,LOG_TYPE_SYSTEM).setAPI("StopGuardian")("Fail to open process(%d)!",GetLastError());
- return false;
- }
- else
- {
- result = TerminateProcess(hProcess,-1);
- if (result)
- {
- Sleep(3000);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopGuardian")("Terminate guardian suc.");
- return true;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopGuardian")("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
- int ret = m_pfUpgradeRestart(6, 0);
- Dbg("healthmanager tell the guardian to quit.%d", ret);
- Sleep(5000);
- pid_t pID;
- bool bFind = false;
- bFind = FindGuardianPid(pID);
- if (bFind)
- {
- int ret = kill(pID, 9);
- if (ret < 0)
- {
- Dbg("kill guardian failed:%d",errno);
- return false;
- }
- else
- {
- Dbg("killed guardian.");
- return true;
- }
- }
- Dbg("can't find guardian pid.");
- return true;
- #endif //RVC_OS_WIN
- }
- bool CHealthManagerEntity::StartGuardian()
- {
- LOG_FUNCTION();
- //oiltmp TODO 如果是未安装,不启动guardian
- //root.ini 不存在,表示未安装
- /** 添加日志控制逻辑 Gifur@202414]*/
- SP::Module::Comm::Settings::InitializeOtherLogSwitch(this, "guardian");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StartGuardian")("启动 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).setAPI("StartGuardian")("curr:%s,ex:%s", m_currentVer.GetData(), m_versionEx.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StartGuardian")("m_versionEx exe is not exist [%s],use current Version exe, curr:%s,ex:%s",xTmp.c_str(),m_currentVer.GetData(), m_versionEx.GetData());
- }
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StartGuardian")("guardian path[%s]",(LPCTSTR)csBinPath);
- csAll = csSep + csBinPath + csSep;
- LPTSTR szCmdline = _strdup(csAll);
- if( !CreateProcessA( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StartGuardian")("CreateProcess failed (%d).\n", GetLastError());
- return false;
- }
- DWORD dwErr = GetLastError();
- return true;
- #else
- char app[MAX_PATH];
- memset(app, 0, sizeof(app));
- tk_process_t* process = NULL;
- tk_process_option_t option;
- csBinPath += "/guardian";
- Dbg("path:%s", (const char*)csBinPath);
- sprintf(app, "%s %s %d", (const char*)csBinPath, "oiltest", 1);
- 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> spConfig;
- ErrorCodeEnum err = GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- if (err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("open cfg file failed!");
- return false;
- }
- ErrorCodeEnum eErr = GetFunction()->GetSystemStaticInfo(m_sysStaticInfo);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("DoRestart")("Get system static info failed(%s).", SpStrError(eErr));
- m_sysStaticInfo.strMachineType = "";
- m_sysStaticInfo.strSite = "";
- m_sysStaticInfo.InstallVersion = CVersion();
- }
- m_restartHour = m_restartMinute = 1;
- m_maxRestartTimes = 3;
- int defaultTimesMax, defaultInternal, lowTimesMax, lowInternal, tmpHourBegin, tmpHourEnd;
- //the region (RestartHourBegin,RestartHourEnd) that we should reboot VTM
- tmpHourBegin = 1;
- tmpHourEnd = 6;
- do
- {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "RestartHourBegin", value);
- if (value > 0) {
- tmpHourBegin = value;
- }
- } while (false);
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "RestartHourEnd", value);
- if (value > 0) {
- tmpHourEnd = value;
- }
- } while (false);
- //to calculate the restartHour & restartMinute of the Terminal
- ToCalcRebootHourAndMinute(tmpHourBegin, tmpHourEnd);
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "TestFlag", value);
- m_testFlag = value;
- } while (false);
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "MaxRestartTimes", value);
- if (value > 0) {
- m_maxRestartTimes = value;
- }
- } while (false);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("m_maxRestartTimes(%d)",m_maxRestartTimes);
- defaultTimesMax = 10;
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "DefaultTimesMax", value);
- if (value > 0) {
- defaultTimesMax = value;
- }
- } while (false);
- defaultInternal = 600000;
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "DefaultInternal", value);
- if (value > 0) {
- defaultInternal = value;
- }
- } while (false);
- lowTimesMax = 5;
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "LowTimesMax", value);
- if (value > 0) {
- lowTimesMax = value;
- }
- } while (false);
- lowInternal = 600000;
- do {
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityName(), "LowInternal", value);
- if (value > 0) {
- lowInternal = value;
- }
- } while (false);
- 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("MediaController"), csLowModule(true);
- do {
- CSimpleStringA strValue(true);
- spConfig->ReadConfigValue(GetEntityName(), "DefaultModule", strValue);
- if (!strValue.IsNullOrEmpty()) {
- csDefaultModule = strValue;
- }
- } while (false);
- do {
- CSimpleStringA strValue(true);
- spConfig->ReadConfigValue(GetEntityName(), "LowModule", strValue);
- if (!strValue.IsNullOrEmpty()) {
- csLowModule = strValue;
- }
- } while (false);
- SplitModuleNames(csDefaultModule,RESTART_MODE_DEFAULT);
- SplitModuleNames(csLowModule,RESTART_MODE_LOW);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("m_restartHour:m_restartMinute=%d:%d",m_restartHour,m_restartMinute);
- CSmartPointer<IConfigInfo> spConfigRun;
- 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);
- spConfigRun->ReadConfigValue("Run", "VersionEx", m_versionEx);
- //判断上个版本号值是否为空
- if(m_versionEx.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("get VersionEx is null");
- }
- CSmartPointer<IConfigInfo> spCerConfig;
- eErr = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
- spCerConfig->ReadConfigValueInt(GetEntityName(), "MaxRunDays", m_maxRunDays);
- 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).setAPI("DoRestart")("get current version [%s]", (LPCTSTR)m_currentVer);
- 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");
- bool bStop = StopGuardian();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("no need for guardian, to stop guardian:%d", bStop);
- m_bNeedGuardian = false;
- //设置一个系统变量给关门页面使用
- //liuwt@20220104 N noguardian Y needguardian
- eErr = GetFunction()->SetSysVar("NeedGuardian","N");
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("set NeedGuardian N failed (%d).",(int)eErr);
- }
- }else{
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_Need_Guardian, "terminal is need start up guardian");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("central setting:m_maxRunDays:%d,DayNum:%d,NonGuardian:%s", m_maxRunDays,m_dayNum,csimpleStrMachineTypeCfg.GetData());
- SYSTEMTIME localTime;
- GetLocalTimeRVC(localTime);
- if (m_bInit)
- {
- m_bInit = false;
- m_wDayOfWeek = localTime.wDayOfWeek;
- }
- ITimerListener *pListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnCheckTimeTimeout);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("set timer");
- GetFunction()->SetTimer(HEALTHMANAGER_TIMER_ID, pListener, HEALTHMANAGER_TIMER_INTERVAL);
- CSimpleStringA deamonBasePath = "";
- err = GetFunction()->GetPath("bin",deamonBasePath);
- if (err != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("for wait deamon get bin path failed(%d).",err);
- return false;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("加载guardian.dll");
- #if defined(RVC_OS_WIN)
- deamonBasePath += "\\GuardianBase.dll";
- #else
- deamonBasePath += "/libGuardianBase.so";
- #endif
- DbgWithLink(LOG_LEVEL_DEBUG, 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).setAPI("DoRestart")("curr:%s,ex:%s", m_currentVer.GetData(), m_versionEx.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("m_versionEx dll is not exist ,use current Version gd, curr:%s,ex:%s", m_currentVer.GetData(), m_versionEx.GetData());
- }
-
- }
- #if defined(RVC_OS_WIN)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("DoRestart")("gd path [%s]", deamonBasePath.GetData());
- HMODULE hDll = LoadLibraryA(deamonBasePath);
- if (hDll == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("load guardianbase.dll failed(%d)",GetLastError());
- return false;
- }
- m_pfShake = (pfShakeHands)GetProcAddress(hDll,"ShakeHands");
- if (m_pfShake == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("get shakehands failed(%d)",GetLastError());
- return false;
- }
- m_pfUpgradeRestart = (pfUpgradeRestart)GetProcAddress(hDll,"UpgradeRestart");
- if (m_pfUpgradeRestart == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("get UpgradeRestart failed(%d)",GetLastError());
- return false;
- }
- #else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("gd path [%s]", (LPCTSTR)deamonBasePath);
- void* handle = dlopen(deamonBasePath, RTLD_LAZY);
- if (handle == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("load libGuardianBase.so failed(%d)", errno);
- return false;
- }
- m_pfShake = (pfShakeHands)dlsym(handle, "ShakeHands");
- if (m_pfShake == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get ShakeHands failed(%d)", GetLastError());
- return false;
- }
- m_pfUpgradeRestart = (pfUpgradeRestart)dlsym(handle, "UpgradeRestart");
- if (m_pfUpgradeRestart == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get UpgradeRestart failed(%d)", GetLastError());
- return false;
- }
- #endif
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("have load guardian.");
- if (CheckGuardianIsRun(true) > 0)
- {
- Sleep(500);
- if (m_bNeedGuardian)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("to tell guardian framework is starting.");
- eErr = m_pfUpgradeRestart(4, 0);//tell guardian framework is starting...oilyang 20150514
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("feedback of framework is starting.%d", eErr);
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("need Upgrade guardian only");
- eErr = m_pfUpgradeRestart(6, 0);//tell guardian framework we need Upgrade !!!Only!!! oilyang@20211221
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DoRestart")("feedback of need Upgrade guardian only.%d", eErr);
- }
- }
- 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;
- }
- }
- }
- bool CHealthManagerEntity::SaveCurrentVersion()
- {
- CSimpleStringA csRootVer,csRunInfo,csBakFile,csVerFile;
- ErrorCodeEnum eErr;
- if ((eErr = GetFunction()->GetPath("RootVer",csRootVer)) != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SaveCurrentVersion")("Get version path failed(%d).",eErr);
- return false;
- }
- if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SaveCurrentVersion")("get runinfo path failed(%d)",eErr);
- return false;
- }
- #if defined(RVC_OS_WIN)
- csBakFile = csRunInfo + "\\runcfg\\version.dat";
- #else
- csBakFile = csRunInfo + "/runcfg/version.dat";
- #endif
- ofstream outfile (csBakFile,std::ofstream::binary);
- CSmartPointer<IConfigInfo> spConfigRun;
- eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SaveCurrentVersion")("SaveCurrentVersion open run cfg file failed!");
- 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_INFO,LOG_TYPE_SYSTEM).setAPI("SaveFrameStartTimeForUpgrade")("get runinfo path failed(%d)",eErr);
- return false;
- }
- #if defined(RVC_OS_WIN)
- csBakFile = csRunInfo + "\\runcfg\\starttime.dat";
- #else
- csBakFile = csRunInfo + "/runcfg/starttime.dat";
- #endif
- ofstream outfile (csBakFile,std::ofstream::binary);
- CSystemRunInfo sysRunInfo;
- GetFunction()->GetSystemRunInfo(sysRunInfo);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SaveFrameStartTimeForUpgrade")("Get system run info failed(%d).",eErr);
- return false;
- }
- CSimpleStringA csStartTime = sysRunInfo.tmStart.ToTimeString();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SaveFrameStartTimeForUpgrade")("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)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("VersionRollBack")("destination version identified the current version.");
- return false;
- }
- m_pUpgMgr = new UpgradeMgrService_ClientBase(this);
- if (m_pUpgMgr == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("VersionRollBack")("create UpgradeMgr client failed.");
- return false;
- }
- CSmartPointer<IAsynWaitSp> pAsyncWait;
- ErrorCodeEnum eErr = m_pUpgMgr->Connect(pAsyncWait);
- if (eErr != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("VersionRollBack")("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)(EntityResource::getLink().upgradeLink())->RollbackUpdate(req,ans,10000);
- if (eErr == Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("VersionRollBack")("version rollback doing.");
- m_bVerRollback = true;
- return true;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("VersionRollBack")("UpgradeMgr rollback failed(%d)",eErr);
- return false;
- }
- }
- int CHealthManagerEntity::UpdateSiteChangeFlag()
- {
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
- if (eErr != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateSiteChangeFlag")("UpdateSiteChangeFlag open run cfg file failed!");
- return -1;
- }
- eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 1);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateSiteChangeFlag")("Write SiteChanged 1.err[%d]",eErr);
- return 0;
- }
- int CHealthManagerEntity::UpdateSiteToRuncfg(bool bWriteSite,bool bClearSiteFlag)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateSiteToRuncfg")("bClearSiteFlag[%d]",bClearSiteFlag);
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
- if (eErr != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateSiteToRuncfg")("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);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateSiteToRuncfg")("UpdateSiteToRuncfg.Write Site (%d).", eErr);
- }
- if (bWriteSite)
- {
- spConfig->WriteConfigValue("AboutSite", "Site", m_sysStaticInfo.strSite);
- }
- return 0;
- }
- 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
- {
- ctx->Ans.value = __ReadCenterConfigStr(ctx->Req.key, ctx->Req.entity);
- ctx->Answer(Error_Succeed);
- }
- }
- void CHealthManagerEntity::ControlTerminalLife(
- SpReqAnsContext<HealthManagerService_ControlTerminalLife_Req, HealthManagerService_ControlTerminalLife_Ans>::Pointer ctx)
- {
- //< !--1:restart app; 2: shutdown app; 3:shutdown app and guardian; 4: restart pc; 5: poweroff; -- >
- int retCode = 0;
- ErrorCodeEnum result = Error_Unexpect;
- switch (ctx->Req.cmdType) {
- case 1:
- retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_Framework);
- result = Error_Succeed;
- break;
- case 2:
- retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Unknown, RebootWay_Framework);
- result = Error_Succeed;
- break;
- case 3:
- retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_Framework);
- result = Error_Succeed;
- break;
- case 4:
- retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_OS);
- result = Error_Succeed;
- break;
- case 5:
- retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_OS);
- result = Error_Succeed;
- break;
- default:
- result = Error_Param;
- break;
- }
- ctx->Ans.retCode = retCode;
- ctx->Answer(result);
- }
- CSimpleStringA CHealthManagerEntity::__ReadCenterConfigStr(CSimpleStringA key, CSimpleStringA entityName = "")
- {
- CSimpleStringA str = "";
- CSmartPointer<IConfigInfo> 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::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)
- {
- 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://升级请求重启框架(体系外升级等等)
- {
- //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)
- {
- FrameworkRestartTask* task = new FrameworkRestartTask(this); //通过工作线程弹窗并重启
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- else if (dwUserCode == Event_Req_Framework_Rollback)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("version rollback succeed.to restart framework");
- m_bVerRollback = false;
- m_eRebootTrigger = RebootTrigger_RollBack;
- }
- else if (dwUserCode == LOG_EVT_IEBROWSER_RESET_SITE_RESTART)
- {
- //oilyang@20211021 comment the following line
- //can't see why update this ,as browser haven't changed site
- //UpdateSiteChangeFlag();
- m_eRebootTrigger = RebootTrigger_Resource;
- }
- 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); //通过工作线程弹窗并重启
- GetFunction()->PostThreadPoolTask(task);
- break;
- }
- m_eRebootWay = RebootWay_Framework;
- BOOL bRet = FrameworkShutdown();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("framework shutdown [%d]", bRet);
- }
- break;
- case EVENT_CONSOLE_REQ_SHUTDOWN_SHELL:
- {
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_PrivilegeCMD, CSimpleStringA::Format("%x", dwUserCode));
- BOOL bRet = FrameworkShutdown(false);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("framework shutdown from console [%d]", bRet);
- }
- break;
- case EVENT_RESTART_MACHINE:
- case Event_Req_OS_Restart://case os restart after outside update
- case EVENT_CONSOLE_REQ_RESTART_POWER:
- {
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_PrivilegeCMD, CSimpleStringA::Format("%x", dwUserCode));
- if (dwUserCode == Event_Req_OS_Restart)
- m_eRebootTrigger = RebootTrigger_OSUpgrade;
- else
- m_eRebootTrigger = RebootTrigger_Unknown;
- m_eRebootWay = RebootWay_Power;
- BOOL bRet = SystemRestart(false, true);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("os restart [%d]", bRet);
- }
- break;
- case LOG_EVT_IEBROWSER_RESTART_MACHINE:
- {
- m_eRebootTrigger = RebootTrigger_Unknown;
- m_eRebootWay = RebootWay_Power;
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_IEBROWSER_RESTART_MACHINE, "ClosePage/UserDeskTop to call restart machine.");
- BOOL bRet = SystemRestart(false, true, true);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("machine restart now [%d]", bRet);
- break;
- }
- case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE:
- {
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE, "ClosePage/UserDeskTop to call shutdown machine.");
- SystemShutdown();
- break;
- }
- case LOG_EVT_SELFCHECK_OS_RESTART:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("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:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("selfcheck to wait chance to restart(power) pc.");
- m_eRebootTrigger = RebootTrigger_RunExcepition;
- m_eRebootWay = RebootWay_Power;
- m_bWaitRestartPC = true;
- break;
- case EVENT_MOD_SIP_RESART:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SIPPhone said to wait chance to restart(power) pc.");
- m_eRebootTrigger = RebootTrigger_RunExcepition;
- m_eRebootWay = RebootWay_Power;
- m_bWaitRestartPC = true;
- break;
- case EVENT_ACCESSAUTH_SUCCEED:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501Z10302")("access auth succeed.");
- m_fsm.SetAccessAuth(AccessAuth_Suc);
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = true;
- m_dwTimeOfAuthSuc = GetTickCount64() / 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);
- }
- 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_SYSTEM)("no retry,no restart.");
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = false;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_NORESTART) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("retry,no restart.");
- m_bNeedAuthRetry = true;
- m_bNeedGuardianRestart = false;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_RESTART) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("retry,restart.");
- m_bNeedAuthRetry = true;
- m_bNeedGuardianRestart = true;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_UNKNOWN) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("unkown access failed.no retry,restart.");
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = true;
- }
- m_fsm.SetAccessAuth(AccessAuth_Fail);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501Z10302").setResultCode("RTA5103")("receive accessauth failed result:%d", dwUserCode);
- if (m_bNeedAuthRetry)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("retry AccessAuth");
- m_fsm.ToReAccessAuth();
- }
- }
- break;
- case ERR_ACCESSAUTH_SERVICE_FAILED: //准入服务返回失败
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("unkown access failed.no retry, no restart.");
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = false; //服务端准入失败无需重启
- m_fsm.SetAccessAuth(AccessAuth_servFail);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("access auth failed %d. TerminalStage = S", dwUserCode);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501Z10302").setResultCode("RTA5103")("receive accessauth failed result:%d", dwUserCode);
- if (m_bNeedAuthRetry)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("retry AccessAuth");
- m_fsm.ToReAccessAuth();
- }
- break;
- break;
- case LOG_EVT_INC_VERSION_ROLLBACK:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("version to be rollback to %s", pszMessage);
- if (!m_bVerRollback)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("rollbacking");
- VersionRollBack(pszMessage);
- }
- break;
- case LOG_EVT_SELFCHECK_TOKEN_KEEPER_LOST:
- {
- ErrorCodeEnum eErr = RestartModule("TokenKeeper");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to re accessauth");
- m_fsm.ToReAccessAuth();
- }
- break;
- case LOG_EVT_HEARTBEAT_CONNECTED:
- UpdateSiteToRuncfg(true, true);
- break;
- case EVENT_MOD_RELEASESIP_TIMEOUT:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RELEASESIP_TIMEOUT.");
- RestartModule("SIPPhone");
- break;
- case LOG_EVT_SELFCHECK_IEBROWSER_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.");
- m_bBrowserIdleFirst = true;
- break;
- case LOG_EVT_PINPAD_OPEN_SUC:
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("PinPad open suc.");
- m_fsm.SetPinPadOpenSuc();
- m_fsm.JudgeIfNeedInitFWB();
- 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)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- m_bInMainPage = true;
- if (!m_bHaveThrowMainPage)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR0402501Z10401")(m_sysStaticInfo.InstallVersion.ToString().GetData());
- m_bHaveThrowMainPage = true;
- //the following lines from linux version
- CSmartPointer<IConfigInfo> spConfigShell;
- GetFunction()->OpenConfig(Config_Shell, spConfigShell);
- CSimpleStringA shellVersion(true);
- spConfigShell->ReadConfigValue("Main", "SoftwareVersion", shellVersion);
-
- ULONGLONG dwElapse = GetTickCount64();//使用机器启动时间秒数
- 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("QLR0402501Z10401").setResultCode("RTA5106")
- ("After receive accessauth success event, havn't receive enter main page in %d seconds.", m_maxWaitMainpageTime / 1000 * 3);
- else if (dwToMainPageCostTime > m_maxWaitMainpageTime / 1000 * 2)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501Z10401").setResultCode("RTA5105")
- ("After receive accessauth success event, havn't receive enter main page in %d seconds.", m_maxWaitMainpageTime / 1000 *2);
- else if (dwToMainPageCostTime > m_maxWaitMainpageTime / 1000)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501Z10401").setResultCode("RTA5104")
- ("After receive accessauth success event, havn't receive enter main page in %d seconds.", m_maxWaitMainpageTime / 1000);
- }
- if (m_bBrowserIdleFirst)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("the first enter main page from browser started.");
- m_bBrowserIdleFirst = false;
- m_bEnterMainPageEver = true;
- LogEvent(Severity_Middle, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE, "enter main page");
- ULONGLONG dwElapse = GetTickCount64();//使用机器启动时间秒数
- DWORD elapseTimeTemp = dwElapse / 1000;
- CSimpleStringA xMsg = CSimpleStringA::Format("{\"Decripstion\":\"the first enter main page from browser started.\",\"version\":\"%s\",\"elapseTime\":\"%d\"}"
- , m_sysStaticInfo.InstallVersion.ToString().GetData(), elapseTimeTemp);
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE, xMsg.GetData());
- spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartTimes", 0);
- spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartOSTimes", 0);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("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)
- {
- }
- void CHealthManagerEntity::OnTimeout(DWORD dwTimeID)
- {
- switch (dwTimeID)
- {
- case HEALTHMANAGER_WAIT_MAINPAGE_OPEN_TIMER_ID:
- if (!m_bHaveThrowMainPage)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode("QLR0402501Z10401").setResultCode("RTA5104")
- ("After receive accessauth success event, havn't receive enter main page in %d seconds.", 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::WarnAndRestartFramwork()
- {
- StartManagerDesktopPage("upgradeRestart.html");
- Sleep(5000);
- SaveCurrentVersion();
- SaveFrameStartTimeForUpgrade();
- if (CheckGuardianIsRun(true) > 0)
- {
- ErrorCodeEnum eErr = Error_Unexpect;
- eErr = m_pfUpgradeRestart(1, 0);
- //Dbg("to tell guardian framework is restarting.%d",eErr);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to tell guardian framework is restarting.%d", eErr);
- }
- m_eRebootTrigger = RebootTrigger_FrameUpgrade;
- m_eRebootWay = RebootWay_Framework;
- BOOL bRet = FrameworkShutdown();
- //Dbg("framework shutdown [%d]", bRet);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("framework shutdown in restart task [%d]", bRet);
- }
- void CHealthManagerEntity::ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.devId == 0 && ctx->Req.entityName.IsNullOrEmpty()) {
- result = Error_Param;
- }
- else {
- if (ctx->Req.entityName.IsNullOrEmpty()) {
- ///**TODO(Gifur@10/22/2021): */
- result = Error_NotImpl;
- }
- else {
- tmpResult = DealSpecifiedEntity((DealType)ctx->Req.option, ctx->Req.entityName, ctx->Req.param, ctx->Req.force, tmpMsg);
- }
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- }
- void CHealthManagerEntity::Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.type != 1) {
- result = Error_NotSupport;
- } else {
- result = Error_Deprecated;
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- }
- ErrorCodeEnum CHealthManagerEntity::GetTmpRootFilePath(CSimpleStringA& rootPath, CSimpleStringA& rootTmpPath, CSimpleStringA& rootBackPath)
- {
- CSimpleStringA strRootCfgPath;
- ErrorCodeEnum ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath);
- rootPath = strRootCfgPath;
- rootPath += SPLIT_SLASH_STR;
- rootPath += "root.ini";
- rootTmpPath = rootPath + ".tmp";
- SYSTEMTIME curTime = CSmallDateTime::GetNow().ToSystemTime();
- CSimpleStringA strBackupFileSuffix = CSimpleStringA::Format(".bak%04d%02d%02d%02d%02d%02d%03d",
- curTime.wYear, curTime.wMonth, curTime.wDay, curTime.wHour, curTime.wMinute, curTime.wSecond, curTime.wMilliseconds);
- rootBackPath = rootPath + strBackupFileSuffix;
- return ec;
- }
- void CHealthManagerEntity::RecordInstallBeginTimeStamp(const CSimpleString& strTimeStamp, BOOL forceReset)
- {
- if (!forceReset) {
- /** 有时间戳记录的情况下不再覆盖记录 [Gifur@2023823]*/
- CSimpleStringA strReserved(true);
- const ErrorCodeEnum rc = GetInstallBeginTimeStamp(strReserved);
- if (!strReserved.IsNullOrEmpty()) {
- return;
- }
- }
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- if (strTimeStamp.IsNullOrEmpty()) {
- pConfig->WriteConfigValue("TerminalDeploy", "StartTimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- } else {
- pConfig->WriteConfigValue("TerminalDeploy", "StartTimeStamp", strTimeStamp);
- }
- }
- ErrorCodeEnum CHealthManagerEntity::GetInstallBeginTimeStamp(CSimpleString& strTimeStamp)
- {
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- CSimpleStringA strValue(true);
- pConfig->ReadConfigValue("TerminalDeploy", "StartTimeStamp", strValue);
- if (strValue.IsNullOrEmpty()) {
- return Error_DataCheck;
- }
- strTimeStamp = strValue;
- return Error_Succeed;
- }
- ErrorCodeEnum CHealthManagerEntity::GetGuidePageUrlWithStep(int whichStep, CSimpleStringA& strUrl)
- {
- strUrl.Clear();
- CSimpleStringA pagePath;
- ErrorCodeEnum ec = GetFunction()->GetPath("Base", pagePath);
- pagePath.Append(SPLIT_SLASH_STR "res" SPLIT_SLASH_STR "ManagerDesktop" SPLIT_SLASH_STR "guide.html");
- if (whichStep > 0) {
- CSimpleStringA terminalNo;
- CSimpleStringA vendorType;
- CSimpleStringA serverIP;
- do {
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- const ErrorCodeEnum ec0 = pConfig->ReadConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
- const ErrorCodeEnum ec1 = pConfig->ReadConfigValue("TerminalDeploy", "Manufacturer", vendorType);
- const ErrorCodeEnum ec2 = pConfig->ReadConfigValue("TerminalDeploy", "ServerIP", serverIP);
- Dbg("read step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
- } while (false);
- pagePath = CSimpleStringA::Format("%s?page=%d", pagePath.GetData(), whichStep);
- bool prefix(true);
- if (!terminalNo.IsNullOrEmpty() || !vendorType.IsNullOrEmpty() || !serverIP.IsNullOrEmpty()) {
- CSimpleStringA strSearch(true);
- if (!terminalNo.IsNullOrEmpty()) {
- if (prefix) strSearch += "&";
- strSearch += CSimpleStringA("terminalno=") + terminalNo;
- prefix = true;
- }
- if (!vendorType.IsNullOrEmpty()) {
- if (prefix) strSearch += "&";
- strSearch += CSimpleStringA("vendor=") + vendorType;
- prefix = true;
- }
- if (!serverIP.IsNullOrEmpty()) {
- if (prefix) strSearch += "&";
- strSearch += CSimpleStringA("ip=") + serverIP;
- prefix = true;
- }
- pagePath += strSearch;
- }
- }
- strUrl = CSimpleStringA("file:///") + pagePath + CSimpleStringA("");
- return ec;
- }
- namespace
- {
- ErrorCodeEnum SplitAdapterFileName(CSimpleStringA strFileName, CAutoArray<CSimpleStringA>& values)
- {
- #ifdef RVC_OS_WIN
- CSimpleStringA strPrefix("");
- CSimpleStringA strSuffix(".dll");
- #else
- CSimpleStringA strPrefix("lib");
- CSimpleStringA strSuffix(".so");
- #endif //RVC_OS_WIN
- if (strFileName.GetLength() < strPrefix.GetLength() + strSuffix.GetLength()) {
- return Error_Param;
- }
- CSimpleStringA pureAdapterName = strFileName.SubString(
- strPrefix.GetLength(), strFileName.GetLength() - strPrefix.GetLength() - strSuffix.GetLength());
- values = pureAdapterName.Split('.');
- if (values.GetCount() != 4) {
- return Error_DataCheck;
- }
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CHealthManagerEntity::TellChromiumOpenGuidePage(const CSimpleStringA& pageUrl)
- {
- ErrorCodeEnum result(Error_Succeed);
- auto pClient = new ChromiumSrv_ClientBase(this);
- result = pClient->Connect();
- if (result == Error_Succeed) {
- ChromiumSrv_OpenBrowser_Req req;
- ChromiumSrv_OpenBrowser_Ans ans;
- req.mainUrl = pageUrl;
- req.viceUrl = "";
- req.type = "OutsideRequest";
- req.name = "GuidePage";
- req.exclusiveMode = true;
- req.top = -1;
- result = (*pClient)(EntityResource::getLink().upgradeLink())->OpenBrowser(req, ans, 10000);
- if (result == Error_Succeed) {
- Dbg("Request Chromium::OpenBrowser succ!");
- }
- else {
- Dbg("Request Chromium::OpenBrowser failed: %s", SpStrError(result));
- }
- pClient->GetFunction()->CloseSession();
- }
- else {
- pClient->SafeDelete();
- Dbg("Connect to Chromium entity failed: %s", SpStrError(result));
- }
- return result;
- }
- ErrorCodeEnum CHealthManagerEntity::DealSpecifiedEntity(DealType type, LPCTSTR lpcszEntityName, LPCTSTR lpcszCmdline, bool bForce, CSimpleStringA& strErrMsg)
- {
- ErrorCodeEnum result(Error_Succeed);
- strErrMsg.Clear();
- switch (type) {
- case Deal_Start:
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- CSimpleStringA strEntityName(lpcszEntityName);
- CEntityRunInfo info = {};
- result = GetFunction()->GetEntityRunInfo(strEntityName, info);
- bool toStart(true);
- Dbg("entity: %s, %s,%s", strEntityName.GetData(), SpStrError(result), SpStrEntityState(info.eState));
- if ((info.eState != EntityState_NoStart && info.eState == EntityState_Lost
- && info.eState == EntityState_Close && info.eState == EntityState_UnLoading)
- && (bForce)) {
- }
- if (info.eState != EntityState_NoStart && bForce) {
- Dbg("to terminal entity..");
- CSmartPointer<IAsynWaitSp> spWait;
- result = pFuncPrivilege->StopEntity(strEntityName, spWait);
- Dbg("stop entity return %s", SpStrError(result));
- if (result == Error_Succeed && spWait != NULL) {
- Dbg("to wait after stop...");
- result = spWait->WaitAnswer(60 * 1000);
- Dbg("wait result: %s", SpStrError(result));
- if (result != Error_Succeed) {
- CSmartPointer<IAsynWaitSp> spWait2;
- result = pFuncPrivilege->TerminateEntity(strEntityName, spWait2);
- Dbg("terminal entity return %s", SpStrError(result));
- if (result == Error_Succeed && spWait2 != NULL) {
- Dbg("to wait after terminal...");
- result = spWait2->WaitAnswer(60 * 1000);
- Dbg("wait result: %s", SpStrError(result));
- }
- }
- }
- if (result != Error_Succeed) {
- strErrMsg = CSimpleStringA::Format("重启前停止实体失败 %s, %s", SpStrEntityState(info.eState), SpStrError(result));
- toStart = false;
- }
- }
- else if (info.eState != EntityState_NoStart) {
- result = Error_InvalidState;
- strErrMsg = CSimpleStringA::Format("实体[%s]当前状态(%s)不支持该操作", strEntityName.GetData(), SpStrEntityState(info.eState));
- toStart = false;
- }
- if (toStart) {
- Dbg("to start entity..");
- CSmartPointer<IAsynWaitSp> spWait;
- result = pFuncPrivilege->StartEntity(strEntityName, lpcszCmdline, spWait);
- Dbg("start entity return %s", SpStrError(result));
- if (result == Error_Succeed && spWait != NULL) {
- Dbg("to wait...");
- result = spWait->WaitAnswer(60 * 1000);
- Dbg("wait result: %s", SpStrError(result));
- }
- if (result != Error_Succeed) {
- strErrMsg = CSimpleStringA::Format("启动实体失败 %s", SpStrError(result));
- }
- }
- }
- break;
- case Deal_Close:
- result = Error_NotImpl;
- break;
- case Deal_Pause:
- result = Error_NotImpl;
- break;
- case Deal_Continue:
- result = Error_NotImpl;
- break;
- case Deal_Kill:
- result = Error_NotImpl;
- break;
- case Deal_Test:
- result = Error_NotImpl;
- break;
- case Deal_Restart:
- result = Error_NotImpl;
- break;
- default:
- result = Error_NotSupport;
- break;
- }
- return result;
- }
- void CHealthManagerEntity::DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
- {
- #if defined(RVC_OS_LINUX)
- LOG_FUNCTION();
- ErrorCodeEnum result(Error_Succeed);
- int tmpResult = 0;
- CSimpleStringA tmpMsg(true);
- Dbg("Cmd: %d", ctx->Req.currStep);
- switch (ctx->Req.currStep) {
- case DeployStep_Begin:
- {
- if (ctx->Req.options == 1) { //重置配置
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- int lastStep(0), stepStatus(0);
- pConfig->ReadConfigValueInt("TerminalDeploy", "CurrStep", lastStep);
- pConfig->ReadConfigValueInt("TerminalDeploy", "CurrState", stepStatus);
- if (lastStep > 0 && (stepStatus == DEPLOYSTATE_NOTINIT)) {
- lastStep--;
- Dbg("draw back to %d", lastStep);
- }
- else if (lastStep != 0) {
- Dbg("current step: %d", lastStep);
- }
- else if (!m_fConfigMode) {
- lastStep = DeployStep_Finished;
- Dbg("reset to finished step");
- }
- for (int cur = lastStep; cur > 0; --cur) {
- switch (cur) {
- case DeployStep_GetTerminalInfo:
- {
- Dbg("clear terminalno etc at cache file...");
- pConfig->WriteConfigValue("TerminalDeploy", "TerminalNo", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "Manufacturer", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "LastInfo", NULL);
- }
- break;
- case DeployStep_FetchCenterSettings:
- {
- //清理集中配置文件
- Dbg("clear centersetting files...");
- CSimpleStringA strEntityCfgPath;
- tmpResult = GetFunction()->GetPath("Cfg", strEntityCfgPath);
- array_header_t* subs = fileutil_get_sub_files_a(strEntityCfgPath);
- if (subs) {
- regex_t reg;
- CSimpleStringA pattern = "CenterSetting\.[a-zA-Z0-9_\\(\\)\\-]*\.ini";
- int ret = regcomp(®, pattern, REG_EXTENDED | REG_NOSUB);
- if (ret) {
- char ebuff[256];
- regerror(ret, ®, ebuff, 256);
- Dbg("regex failed: %s", ebuff);
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
- toolkit_array_free2(subs);
- break;
- }
- Dbg("pattern: %s", pattern.GetData());
- for (int i = 0; i < subs->nelts; ++i) {
- char* filenamePath = ARRAY_IDX(subs, i, char*);
- char* filename = &filenamePath[strEntityCfgPath.GetLength() + 1];
- ret = regexec(®, filename, 0, NULL, 0);
- if (0 == ret) {
- Dbg("filename %s matched and remove it.", filename);
- fileutil_delete_file(filenamePath);
- }
- }
- toolkit_array_free2(subs);
- }
- }
- break;
- case DeployStep_AccessAuthorize:
- break;
- case DeployStep_MediaConfig:
- break;
- default:
- break;
- }
- }
- /*读取第一启动的时间戳,有用*/
- CSimpleStringA strBeginTimeReserved(true);
- GetInstallBeginTimeStamp(strBeginTimeReserved);
- CSimpleStringA strCachePath;
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRunInfoDirPath;
- CSimpleStringA strRunCfgDirPath;
- ///**TODO(Gifur@4/21/2022): 既然删除了,前面就没必要清空字段内容了 */
- GetFunction()->GetPath("RunInfo", strRunInfoDirPath);
- strCachePath = strRunInfoDirPath + SPLIT_SLASH_STR + "Global.ini";
- if (ExistsFileA(strCachePath)) {
- Dbg("delete cache file");
- fileutil_delete_file(strCachePath);
- }
- GetFunction()->GetPath("RunCfg", strRunCfgDirPath);
- if (strRunCfgDirPath.IsNullOrEmpty()) {
- strRunCfgDirPath = strRunInfoDirPath + SPLIT_SLASH_STR + "runcfg";
- }
- else {
- Dbg("Get RunCfg from GetPath directly:%s", strRunCfgDirPath.GetData());
- }
- if (ExistsDirA(strRunCfgDirPath)) {
- Dbg("remove runinfo dir");
- RemoveDirRecursiveA(strRunCfgDirPath);
- }
- CSimpleStringA strBackupFile;
- GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strBackupFile);
- if (ExistsFileA(strRootIniFullPath)) {
- Dbg("delete root.ini");
- fileutil_copy_file(strBackupFile, strRootIniFullPath);
- fileutil_delete_file(strRootIniFullPath);
- }
- LogWarn(Severity_High, Error_Debug, LOG_WARN_HEALTH_INSTALL_RESET, "user requires installation reset!");
- /** 将首次安装的时间写进去*/
- if (!strBeginTimeReserved.IsNullOrEmpty()) {
- RecordInstallBeginTimeStamp(strBeginTimeReserved);
- }
- }
- else {
- result = Error_NotImpl;
- }
- }
- break;
- case DeployStep_GetTerminalInfo:
- {
- if (ctx->Req.options == 0) {
- CAutoArray<CSimpleStringA> arrs = ctx->Req.param4.Split('|');
- const CSimpleStringA& terminalNo = arrs[0];
- //终端类型(行内定义)
- const CSimpleStringA& strTerminalType = arrs[1];
- const CSimpleStringA& serverIP = ctx->Req.param3;
- Dbg("server ip: %s, terminal no: %s, type: %s", serverIP.GetData(), (LPCTSTR)terminalNo, (LPCTSTR)strTerminalType);
- CSimpleStringA strVendorName(true);
- CSimpleStringA strZhCNVendorName(true);
- CSimpleStringA strDeviceModel(true);
- CSimpleStringA strDeviceSN(true);
- if (ctx->Req.array2.GetCount() > 0) {
- //硬件厂商
- strVendorName = ctx->Req.array2[0];
- //硬件设备型号(厂商)
- strDeviceModel = ctx->Req.array2[1];
- //设备序列号
- strDeviceSN = ctx->Req.array2[2];
- Dbg("vendor: %s, model:%s, sn: %s", strVendorName.GetData(), strDeviceModel.GetData(), strDeviceSN.GetData());
- }
- bool toRecord(false);
- CSimpleStringA matchInfo(true);
- //走总行服务
- HttpClientRequestConfig config(serverIP.GetData(), &SpGetToken);
- HttpClientResponseResult result;
- config.SetChildUri(URLPATH_REGISTER_FULL_LIST);
- config.AppendQuery("terminalNo", terminalNo.GetData());
- RestfulClient client = RestfulClient::getInstance();
- config.PreDo();
- client.Do(&config, &result);
- if (result.ResponseOK()) {
- struct CommResponseJson : public MicroServices::API::CommResponse
- {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(success, errorCode, returnCode, errorMsg, message)
- };
- CommResponseJson reponseStatus;
- struct RegistInfoJson : public MicroServices::API::Manage::RegistDetailInfo
- {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, deviceNo, initIP, machineNo, machineType, machineVersion, sites, terminalNo, manufactureID, manufacturerName, deviceTye)
- } terminalRegistInfo;
- Json::Value rawRoot;
- bool testSucc(false);
- do {
- if (!GetJsonRootObject(rawRoot, result.content)) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!Json2Object(reponseStatus, rawRoot)) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!reponseStatus.IsOperatedOK()) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!(rawRoot["data"].size() > 0)) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!Json2Object(terminalRegistInfo, rawRoot["data"][0])) {
- Dbg("%d", __LINE__);
- break;
- }
- testSucc = true;
- } while (false);
- if (testSucc) {
- auto printFunc = [&terminalRegistInfo]() {
- Dbg("TerminalNo: %s", terminalRegistInfo.terminalNo.c_str());
- Dbg("BranchNo: %s", terminalRegistInfo.branchNo.c_str());
- Dbg("DeviceNo: %s", terminalRegistInfo.deviceNo.c_str());
- Dbg("IP: %s", terminalRegistInfo.initIP.c_str());
- Dbg("MachineNo: %s", terminalRegistInfo.machineNo.c_str());
- Dbg("MachineType: %s", terminalRegistInfo.machineType.c_str());
- Dbg("MachineVersion: %s", terminalRegistInfo.machineVersion.c_str());
- Dbg("Sites: %s", terminalRegistInfo.sites.c_str());
- Dbg("manufactureID: %s", terminalRegistInfo.manufactureID.c_str());
- Dbg("manufacturerName: %s", terminalRegistInfo.manufacturerName.c_str());
- /** Agent: 终端设备型号*/
- Dbg("deviceTye: %s", terminalRegistInfo.deviceTye.c_str());
- };
- printFunc();
- if (!terminalRegistInfo.manufactureID.empty() && terminalRegistInfo.manufacturerName.empty()) {
- CommResponseJson reponseStatus2;
- HttpClientResponseResult result2;
- Json::Value rawRoot2;
- config.SetChildUri(URLPATH_MANUFACTURE_GET_ALL);
- config.ResetQuery();
- config.PreDo();
- client.Do(&config, &result2);
- bool fetchManufactureDone(false);
- if (result2.ResponseOK() && GetJsonRootObject(rawRoot2, result2.content)
- && Json2Object(reponseStatus2, rawRoot2) && reponseStatus2.IsOperatedOK()) {
- struct ManufactureInfoJson : public MicroServices::API::Manufacture::ManufactureInfo
- {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(manufacturerId, manufacturerName)
- };
- struct ManufactureList
- {
- std::vector<ManufactureInfoJson> data;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(data)
- } manufactureList;
- if (Json2Object(manufactureList, rawRoot2)) {
- for (auto it = manufactureList.data.begin(); it != manufactureList.data.end(); ++it) {
- if (it->manufacturerId.compare(terminalRegistInfo.manufactureID) == 0) {
- terminalRegistInfo.manufacturerName = it->manufacturerName;
- Dbg("get manufacturer name: %s", terminalRegistInfo.manufacturerName.c_str());
- fetchManufactureDone = true;
- break;
- }
- }
- }
- }
- if (!fetchManufactureDone) {
- if (reponseStatus2.IsNotEmpty() && !reponseStatus2.IsOperatedOK()) {
- Dbg("请求失败:%s", reponseStatus2.WhatError().c_str());
- } else {
- Dbg("解析返回内容失败:%s", result2.content.c_str());
- }
- }
- }
- printFunc();
- if (terminalRegistInfo.terminalNo.empty()) {
- tmpResult = Error_NotExist;
- tmpMsg = "查询终端信息不存在,请检测输入的终端号是否正确";
- } else if (terminalRegistInfo.terminalNo != terminalNo.GetData()) {
- tmpResult = Error_MisMatched;
- tmpMsg = CSimpleStringA::Format("查询返回的终端信息不匹配,输入:%s,返回:%s" , terminalNo.GetData(), terminalRegistInfo.terminalNo.c_str());
- } else {
- bool bMatched(true);
- /** 考虑到测试环境数据不准确,这里加一个开关跳过 [Gifur@2023421]*/
- bool criticialCheck(true);
- #ifndef DEVOPS_ON_PRD
- CSmartPointer<IConfigInfo> spConfigShell;
- GetFunction()->OpenConfig(Config_Shell, spConfigShell);
- int nValue(0);
- spConfigShell->ReadConfigValueInt("InstallProc", "SkipTerminalInfoCheck", nValue);
- if (!!nValue) {
- criticialCheck = false;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Skip terminal info check task!!");
- }
- #endif // !DEVOPS_ON_PRD
- if (criticialCheck) {
- if (strTerminalType.Compare(terminalRegistInfo.machineType.c_str()) != 0) {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- matchInfo += CSimpleStringA::Format("终端类型不匹配:[%s]vs[%s]", strTerminalType.GetData(), terminalRegistInfo.machineType.c_str());
- bMatched = false;
- }
- //terminalRegistInfo.manufacturerName = "中钞科堡现金处理";
- if (strVendorName.Compare(terminalRegistInfo.manufacturerName.c_str(), true) != 0) {
- do {
- CSmartPointer<IConfigInfo> spCfgConfig;
- GetFunction()->OpenConfig(Config_Software, spCfgConfig);
- spCfgConfig->ReadConfigValue("VendorZhCN", strVendorName, strZhCNVendorName);
- } while (false);
- if (!strZhCNVendorName.IsNullOrEmpty()
- && terminalRegistInfo.manufacturerName.find(strZhCNVendorName.GetData()) != std::string::npos) {
- //let it empty.
- } else {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- if (strZhCNVendorName.IsNullOrEmpty()) {
- matchInfo += CSimpleStringA::Format("设备厂商不匹配:[%s]vs[%s]", strVendorName.GetData(), terminalRegistInfo.manufacturerName.c_str());
- } else {
- matchInfo += CSimpleStringA::Format("设备厂商不匹配:[%s]vs[%s]", strZhCNVendorName.GetData(), terminalRegistInfo.manufacturerName.c_str());
- }
- bMatched = false;
- }
- }
- if (strDeviceModel.Compare(terminalRegistInfo.deviceTye.c_str()) != 0) {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- matchInfo += CSimpleStringA::Format("设备型号不匹配:[%s]vs[%s]", strDeviceModel.GetData(), terminalRegistInfo.deviceTye.c_str());
- bMatched = false;
- }
- /** Agent: 设备编号*/
- if (strDeviceSN.Compare(terminalRegistInfo.machineNo.c_str()) != 0) {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- matchInfo += CSimpleStringA::Format("设备序列号(编号)不匹配:[%s]vs[%s]", strDeviceSN.GetData(), terminalRegistInfo.machineNo.c_str());
- bMatched = false;
- }
- /** 其他信息的校验和应用 [Gifur@2022123]*/
- }
- if (!bMatched) {
- tmpResult = Error_DataCheck;
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += "。请核验录入信息是否准确!"; }
- tmpMsg = matchInfo;
- } else {
- toRecord = true;
- }
- }
- } else {
- if (reponseStatus.IsNotEmpty() && !reponseStatus.IsOperatedOK()) {
- tmpResult = Error_DataCheck;
- tmpMsg = CSimpleStringA::Format("请求失败:%s", reponseStatus.WhatError().c_str());
- Dbg(tmpMsg);
- } else {
- tmpResult = Error_DataCheck;
- tmpMsg = CSimpleStringA::Format("解析返回内容失败:%s", result.content.c_str());
- Dbg(tmpMsg);
- Dbg("rawRoot[data].size(): %d", rawRoot["data"].size());
- }
- }
- } else {
- tmpResult = Error_ServerNotAvailable;
- if (!result.content.empty()) {
- tmpMsg = CSimpleStringA::Format("访问 %s 失败:%d,%s", config.GetRequestUri().c_str(), result.statusCode, result.content.c_str());
- } else {
- tmpMsg = CSimpleStringA::Format("访问 %s 失败:%d", config.GetRequestUri().c_str(), result.statusCode);
- }
- }
- if (toRecord) {
- ErrorCodeEnum ec(Error_Succeed);
- do {
- Dbg("record to cache...");
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- const ErrorCodeEnum ec0 = pConfig->WriteConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
- const ErrorCodeEnum ec1 = pConfig->WriteConfigValue("TerminalDeploy", "Manufacturer", strVendorName);
- const ErrorCodeEnum ec2 = pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", serverIP);
- const ErrorCodeEnum ec3 = pConfig->WriteConfigValue("TerminalDeploy", "MachineType", strTerminalType);
- if (!matchInfo.IsNullOrEmpty()) {
- pConfig->WriteConfigValue("TerminalDeploy", "LastInfo", matchInfo);
- }
- Dbg("record step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2), SpStrError(ec3));
- } while (false);
- do {
- CSimpleStringA strRootCfgPath;
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRootChosenFile(true);
- CSimpleStringA strNousedPath;
- ec = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- ///**TODO(Gifur@10/16/2021): ASSERT 在这个步骤root.ini 文件不应该出现的,可能是字段的缺失才识别为未配置模式 */
- if (ExistsFileA(strRootIniFullPath)) {
- fileutil_copy_file(strNousedPath, strRootIniFullPath);
- fileutil_delete_file(strRootIniFullPath);
- Dbg("root.ini exists!");
- }
- const CSimpleStringA machineType(strTerminalType);
- const CSimpleStringA rootPattern("root");
- const CSimpleStringA pattern = rootPattern + "\\-" + machineType + "\\-" + strVendorName + "\\-[a-zA-Z0-9_\\(\\)\\-]*" + ".ini";
- ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath);
- array_header_t* subs = fileutil_get_sub_files_a(strRootCfgPath);
- if (subs) {
- regex_t reg;
- int ret = regcomp(®, pattern, REG_EXTENDED | REG_NOSUB);
- if (ret) {
- char ebuff[256];
- regerror(ret, ®, ebuff, 256);
- Dbg("regex failed: %s", ebuff);
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
- toolkit_array_free2(subs);
- break;
- }
- Dbg("pattern: %s", pattern.GetData());
- for (int i = 0; i < subs->nelts; ++i) {
- char* filenamePath = ARRAY_IDX(subs, i, char*);
- char* filename = &filenamePath[strRootCfgPath.GetLength() + 1];
- Dbg("filename: %s", filename);
- ret = regexec(®, filename, 0, NULL, 0);
- if (0 == ret) {
- Dbg("matched!");
- strRootChosenFile = filenamePath;
- break;
- }
- Dbg("not matched.");
- }
- toolkit_array_free2(subs);
- }
- if (!strRootChosenFile.IsNullOrEmpty()) {
- ///**TODO(Gifur@1/23/2022): 根据服务器返回的信息填充其他字段内容 */
- fileutil_copy_file(strRootTmpFile, strRootChosenFile);
- inifile_write_str(strRootTmpFile, "Terminal", "TerminalNo", terminalNo);
- //inifile_write_str(strRootTmpFile, "Terminal", "Manufacturer", vendorType);
- if (!strDeviceSN.IsNullOrEmpty()) {
- inifile_write_str(strRootTmpFile, "Terminal", "SN", strDeviceSN);
- }
- }
- else {
- CSimpleStringA::Format("%s", pattern.GetData());
- tmpMsg = "harewarecfg下匹配不到相应的配置文件,请确认选择的机型和设备厂商是否正确";
- tmpResult = Error_InvalidState;
- }
- } while (false);
- ctx->Ans.param2 = serverIP;
- }
- }
- else if (ctx->Req.options == 1) {
- //从缓存文件中获取,避免出现依赖
- CSimpleStringA terminalNo;
- CSimpleStringA vendorType;
- CSimpleStringA serverIP;
- CSimpleStringA terminalType;
- do {
- Dbg("read from cache...");
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- int nTemp(0);
- const ErrorCodeEnum ec0 = pConfig->ReadConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
- const ErrorCodeEnum ec1 = pConfig->ReadConfigValue("TerminalDeploy", "Manufacturer", vendorType);
- const ErrorCodeEnum ec2 = pConfig->ReadConfigValue("TerminalDeploy", "ServerIP", serverIP);
- const ErrorCodeEnum ec3 = pConfig->ReadConfigValue("TerminalDeploy", "MachineType", terminalType);
- Dbg("read step: %s, %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2), SpStrError(ec3));
- } while (false);
- int checkFlag = 0;
- if (terminalNo.IsNullOrEmpty()) checkFlag |= 1;
- if (vendorType.IsNullOrEmpty()) checkFlag |= 2;
- if (serverIP.IsNullOrEmpty()) checkFlag |= 4;
- if (terminalType.IsNullOrEmpty()) checkFlag |= 8;
- if (checkFlag != 0) {
- tmpResult = Error_Null;
- tmpMsg = CSimpleStringA::Format("获取终端缓存信息失败 Mask=0x%X", checkFlag);
- }
- else {
- ctx->Ans.array1.Init(3);
- ctx->Ans.array1[0] = ctx->Ans.array1[1] = ctx->Ans.array1[2] = 0;
- ctx->Ans.array1[0] = 1;
- ctx->Ans.array2.Init(4);
- ctx->Ans.array2[0] = terminalNo;
- ctx->Ans.array2[1] = vendorType;
- ctx->Ans.array2[2] = serverIP;
- ctx->Ans.array2[3] = terminalType;
- }
- }
- else {
- tmpResult = Error_NotSupport;
- }
- }
- break;
- case DeployStep_FetchCenterSettings:
- {
- const CSimpleStringA& serverIP = ctx->Req.param3;
- if (serverIP.IsNullOrEmpty()) {
- result = Error_Param;
- break;
- }
- ErrorCodeEnum ec(Error_Succeed);
- Dbg("to connect centersetting...%s", serverIP.GetData());
- auto pCenterSettingClient = new CenterSettingService_ClientBase(this);
- ec = pCenterSettingClient->Connect();
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("连接集中配置模块失败: %s", SpStrError(ec));
- pCenterSettingClient->SafeDelete();
- Dbg("connect to centersetting failed: %s", SpStrError(ec));
- } else {
- CenterSettingService_Downloadv2_Req req = {};
- req.reqCenterConfigUrl = serverIP;
- CenterSettingService_Downloadv2_Ans ans = {};
- /**TODO(Gifur@10/14/2021): 未知行内还是行外的情况 */
- Dbg("to download...");
- ec = (*pCenterSettingClient)(EntityResource::getLink().upgradeLink())->Downloadv2(req, ans, 60000);
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("下载集中配置文件请求失败: %s", SpStrError(ec));
- Dbg("to download failed: %s", SpStrError(ec));
- }
- pCenterSettingClient->GetFunction()->CloseSession();
- }
- tmpResult = ec;
- ctx->Ans.param2 = serverIP;
- }
- break;
- case DeployStep_AccessAuthorize:
- {
- const CSimpleStringA& serverIP = ctx->Req.param3;
- const int nPort = ctx->Req.param1;
- CSimpleStringA strUsername("admin");
- CSimpleStringA strPassword("88888888");
- if (ctx->Req.array2.GetCount() == 2) {
- strUsername = ctx->Req.array2[0];
- strPassword = ctx->Req.array2[1];
- }
- if (serverIP.IsNullOrEmpty()) {
- result = Error_Param;
- break;
- }
- ErrorCodeEnum ec(Error_Succeed);
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- Dbg("to connect initializer...%s::%d", serverIP.GetData(), nPort);
- auto pClient = new AccessAuthService_ClientBase(this);
- ec = pClient->Connect();
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("连接准入模块失败: %s", SpStrError(ec));
- pClient->SafeDelete();
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("connect to accessauth module failed: %s", SpStrError(ec));
- tmpResult = ec;
- }
- else {
- AccessAuthService_InitializeNew_Req req = {};
- req.strAuthServer = serverIP;
- req.strUserID = strUsername;
- req.strPassword = strPassword;
- AccessAuthService_InitializeNew_Ans ans = {};
- Dbg("to initializer new...");
- ec = (*pClient)(EntityResource::getLink().upgradeLink())->InitializeNew(req, ans, 60000);
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("初始化请求失败: %s", SpStrError(ec));
- tmpResult = ec;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("to initializenew failed: %s", SpStrError(ec));
- }
- else {
- const int errUserCode = (int)(ans.Errcode);
- if (errUserCode != 0) {
- if (ans.ErrMsg.IsNullOrEmpty()) {
- tmpMsg = CSimpleStringA::Format("%d", errUserCode);
- }
- else {
- tmpMsg = CSimpleStringA::Format("%s", ans.ErrMsg.GetData());
- }
- tmpResult = errUserCode;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("initialize failed: %s", (LPCTSTR)tmpMsg);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("initialize succ.");
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- ctx->Ans.param2 = serverIP;
- }
- break;
- case DeployStep_MediaConfig:
- {
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strNousedPath;
- tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- CSimpleStringA strRecordFilePath = (ctx->Req.options == 1) ? strRootIniFullPath : strRootTmpFile;
- if (!ExistsFileA(strRecordFilePath)) {
- Dbg("%s not exists!", strRecordFilePath.GetData());
- tmpMsg = CSimpleStringA::Format("%文件不存在,请重置后重新进行配置!", strRecordFilePath.GetData());
- tmpResult = Error_NotExist;
- }
- else {
- for (int i = 0; i < ctx->Req.array1.GetCount() && tmpResult == Error_Succeed; ++i) {
- CSimpleStringA key(true), value(ctx->Req.array2[i]);
- const int type = ctx->Req.array1[i];
- Dbg("%d: %s - %d", i, value.GetData(), type);
- switch (type) {
- case MediaDev_OutSpeaker:
- key = "handfree_out_dev";
- break;
- case MediaDev_InSpeaker:
- key = "pickup_out_dev";
- break;
- case MediaDev_OutMicrophone:
- key = "handfree_in_dev";
- break;
- case MediaDev_InMicrophone:
- key = "pickup_in_dev";
- break;
- default:
- tmpResult = Error_Param;
- break;
- }
- if (!key.IsNullOrEmpty()) {
- tmpResult = inifile_write_str(strRecordFilePath, "Audio", key, value);
- Dbg("write %s=%s into root.ini tmp file: %s", key.GetData(), value.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
- }
- else {
- Dbg("unrecognize: %d, %s", type, value.GetData());
- tmpResult = Error_Unexpect;
- }
- }
- }
- }
- break;
- case DeployStep_AdapterConfig:
- {
- if ((ctx->Req.options & 0x2) || (ctx->Req.options & 0x1)) {
- CSimpleStringA& strAdapterFileName = ctx->Req.param3;
- CAutoArray<CSimpleStringA> adapterInfo;
- tmpResult = SplitAdapterFileName(strAdapterFileName, adapterInfo);
- Dbg("%s, %s", strAdapterFileName.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
- if (tmpResult == 0) {
- CSimpleStringA strDevice(adapterInfo[0]);
- CSimpleStringA strDeviceSection("Device.");
- strDeviceSection += strDevice;
- CSimpleStringA strVendor(adapterInfo[1]);
- CSimpleStringA strVersion(adapterInfo[2]);
- CSimpleStringA strBatch(adapterInfo[3]);
- const int port = ctx->Req.param1;
- const int baudrate = ctx->Req.param2;
- if ((ctx->Req.options & 0x1)) { //更新到缓存
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strNousedPath;
- tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- if (!ExistsFileA(strRootTmpFile)) {
- Dbg("%s not exists!", strRootTmpFile.GetData());
- tmpMsg = "临时配置文件不存在,请重置后重新进行配置!";
- tmpResult = Error_NotExist;
- }
- else {
- tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Vendor", strVendor);
- tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Version", strVersion);
- tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Batch", strBatch);
- tmpResult = inifile_write_int(strRootTmpFile, strDeviceSection, "Port", port);
- tmpResult = inifile_write_int(strRootTmpFile, strDeviceSection, "Baudrate", baudrate);
- }
- }
- else { //更新到root.ini
- CSmartPointer<IConfigInfo> pRootConfig;
- GetFunction()->OpenConfig(Config_Root, pRootConfig);
- tmpResult = pRootConfig->WriteConfigValue(strDeviceSection, "Vendor", strVendor);
- Dbg("%s,%s,%s,%s,%s", strDeviceSection.GetData(), strVendor.GetData(), strVersion.GetData(), strBatch.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
- if (tmpResult == 0) {
- pRootConfig->WriteConfigValue(strDeviceSection, "Version", strVersion);
- pRootConfig->WriteConfigValue(strDeviceSection, "Batch", strBatch);
- pRootConfig->WriteConfigValueInt(strDeviceSection, "Port", port);
- pRootConfig->WriteConfigValueInt(strDeviceSection, "Baudrate", baudrate);
- }
- else {
- tmpMsg = CSimpleStringA::Format("写入ROOT配置文件失败:%s", SpStrError((ErrorCodeEnum)tmpResult));
- }
- }
- }
- else {
- tmpMsg = CSimpleStringA::Format("适配器文件名称不符合规范:%s", strAdapterFileName.GetData());
- }
- }
- else if ((ctx->Req.options & 0x4)) { //启动实体
- CSimpleStringA& strEntityName = ctx->Req.param3;
- tmpResult = DealSpecifiedEntity((DealType)ctx->Req.param1, strEntityName, ctx->Req.param4, (ctx->Req.param2 != 0), tmpMsg);
- }
- }
- break;
- case DeployStep_3rdParty_SogouInstall:
- {
- if ((ctx->Req.options == 1)) { //检测输入法的安装状态
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- Dbg(tmpMsg);
- }
- else {
- ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
- ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
- req.mode = 1;
- Dbg("to invoke...");
- tmpResult = (*pClient)(EntityResource::getLink().upgradeLink())->GetThirdPartyInstallState(req, ans, 30000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("获取安装状态请求失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- }
- else {
- ctx->Ans.param1 = 0;
- if (ans.status == 1) {
- ctx->Ans.param1 = 1;
- ctx->Ans.array1.Init(3);
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = ans.version;
- ctx->Ans.array2[1] = ans.path;
- ctx->Ans.array2[2] = ans.reserverd1; //安装时间
- ctx->Ans.array1[0] = ctx->Ans.array1[1] = ctx->Ans.array1[2] = 0;
- /** 传递是否已经是新版输入法 [Gifur@2023822]*/
- ctx->Ans.array1[0] = ans.reserverd3;
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- }
- else if (ctx->Req.options == 2) { //安装搜狗输入法
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)(tmpMsg);
- }
- else {
- ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
- ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
- req.type = 1;
- req.reserved1 = req.reserved2 = 0;
- /** 健康实体过来的调用,1表示不直接重启机器 [Gifur@202275]*/
- req.reserved1 = 1;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to install...");
- tmpResult = (*pClient)(EntityResource::getLink().upgradeLink())->InstallThirdPartyProgram(req, ans, 120000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("调用安装请求返回错误:%s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- } else {
- tmpResult = ans.result;
- tmpMsg = ans.msg;
- if (tmpResult == 0) {
- ctx->Ans.array1.Init(3);
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = ans.reserverd1; //版本号
- ctx->Ans.array2[1] = ans.path;
- ctx->Ans.array2[2] = ans.reserverd2; //安装时间
- ctx->Ans.array1[0] = ctx->Ans.array1[1] = ctx->Ans.array1[2] = 0;
- if(!ans.reserverd1.IsNullOrEmpty())
- { /** 缺少字段,只能再查一次输入法状态,以获取新旧版输入法信息 [Gifur@2023825]*/
- ResourceWatcherService_GetThirdPartyInstallState_Req req1 = {};
- ResourceWatcherService_GetThirdPartyInstallState_Ans ans1 = {};
- req1.mode = 1;
- ErrorCodeEnum tmp1 = (*pClient)(EntityResource::getLink().upgradeLink())->GetThirdPartyInstallState(req1, ans1, 30000);
- if (tmp1 == Error_Succeed && ans1.status == 1) {
- ctx->Ans.array1[0] = ans1.reserverd3;
- }
- }
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- }
- else {
- result = Error_NotSupport;
- }
- }
- break;
- case DeployStep_3rdParty_FontInstall:
- {
- if ((ctx->Req.options == 1)) { //检测字体的安装状态
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)(tmpMsg);
- }
- else {
- ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
- ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
- req.mode = 2;
- Dbg("to invoke...");
- tmpResult = (*pClient)(EntityResource::getLink().upgradeLink())->GetThirdPartyInstallState(req, ans, 30000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("获取安装状态请求失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)(tmpMsg);
- }
- else {
- ctx->Ans.param1 = 0;
- if (ans.status == 1) {
- ctx->Ans.param1 = 1;
- ctx->Ans.array1.Init(3);
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = ans.version;
- ctx->Ans.array2[1] = ans.path;
- ctx->Ans.array2[2] = ans.reserverd1; //安装时间
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- }
- else if ((ctx->Req.options == 2)) { //字体的安装
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)(tmpMsg);
- }
- else {
- ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
- ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
- req.type = 2; //
- req.reserved1 = req.reserved2 = 0;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to install font....");
- tmpResult = (*pClient)(EntityResource::getLink().upgradeLink())->InstallThirdPartyProgram(req, ans, 60000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("调用安装请求返回错误:%s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- }
- else {
- tmpResult = ans.result;
- tmpMsg = ans.msg;
- }
- pClient->GetFunction()->CloseSession();
- }
- }
- else {
- result = Error_NotSupport;
- }
- }
- break;
- case DeployStep_Finished:
- {
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRootChosenFile(true);
- CSimpleStringA strNousedPath;
- GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- strRootChosenFile = strRootIniFullPath + ".bak";
- if (ExistsFileA(strRootChosenFile)) {
- fileutil_delete_file(strRootChosenFile);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to clear root.ini backup file.");
- }
- CSystemStaticInfo info;
- GetFunction()->GetSystemStaticInfo(info);
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", info.InstallVersion.ToString());
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("received finish install cmd!");
- LogWarn(Severity_High, Error_Debug, LOG_WARN_HEALTH_INSTALL_FINISHED, "install finished");
- result = Error_Succeed;
- }
- break;
- default:
- result = Error_MisMatched;
- break;
- }
- //////////////////////////////////////////////////////////////////////////
- bool restartApp(false), restartPC(false);
- if (result == Error_Succeed) {
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- if (tmpResult == 0) {
- if ((ctx->Req.additional & 0x1)) //重命名 root.ini
- {
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strNousedPath;
- tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- if (!ExistsFileA(strRootTmpFile)) {
- tmpMsg = "临时配置文件不存在,无法加载配置文件,请重置后重新进行配置";
- tmpResult = Error_NotExist;
- }
- else {
- Dbg("rename tmp file to root.ini..");
- fileutil_copy_file(strRootIniFullPath, strRootTmpFile);
- fileutil_delete_file(strRootTmpFile);
- if (!ExistsFileA(strRootIniFullPath)) {
- tmpResult = Error_IO;
- }
- else {
- Dbg("root.ini has been renamed!");
- }
- }
- }
- pConfig->WriteConfigValueInt("TerminalDeploy", "CurrStep", ctx->Req.nextStep);
- pConfig->WriteConfigValueInt("TerminalDeploy", "CurrState", DEPLOYSTATE_NOTINIT);
- pConfig->WriteConfigValue("TerminalDeploy", "TimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- restartApp = ctx->Req.restartApp;
- restartPC = ctx->Req.restartPC;
- }
- else {
- pConfig->WriteConfigValueInt("TerminalDeploy", "CurrStep", ctx->Req.currStep);
- pConfig->WriteConfigValueInt("TerminalDeploy", "CurrState", DEPLOYSTATE_FAILED);
- pConfig->WriteConfigValue("TerminalDeploy", "TimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- }
- }
- if (restartPC || restartApp) {
- /** 无奈,有时处理太快,导致界面上看不到提示,所以只能选择战略性延迟,剩下的靠前端自己了 [Gifur@20211022]*/
- Dbg("sleep suitable second for providing time for fontside to tell user to wait while restarting pc or app");
- Sleep(3000);
- }
- if (restartPC) {
- tmpResult = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_OS);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("重启设备失败(%s),请手动重启", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- }
- }
- else if (restartApp) {
- tmpResult = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_Framework);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("重启应用失败(%s),请手动重启", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- }
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.additionalMsg = tmpMsg;
- ctx->Ans.nextStep = ctx->Req.nextStep;
- ctx->Answer(result);
- #endif
- }
- bool CHealthManagerEntity::IsTestMode()
- {
- static int flag = -1;
- if (flag == -1) {
- CSystemRunInfo runInfo;
- bool result = (GetFunction()->GetSystemRunInfo(runInfo) == Error_Succeed
- && !!(runInfo.dwBootOption & SystemBootOptionEnum::BootOption_Test));
- flag = result ? 1 : 0;
- }
- return !!flag;
- }
- bool CHealthManagerEntity::IsLackOfConfig(int& stepMode)
- {
- stepMode = 0;
- int lastRecordTime = 0;
- CSystemRunInfo runInfo;
- ErrorCodeEnum ec = GetFunction()->GetSystemRunInfo(runInfo);
- if (ec != Error_Succeed) {
- stepMode = ec;
- Dbg("get framework info failed: %s", SpStrError(ec));
- return false;
- }
- if (runInfo.eState == FrameworkState_NotConfig) {
- Dbg("not config from framework");
- stepMode = -1;
- return true;
- }
- else {
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- int stepStatus(0);
- pConfig->ReadConfigValueInt("TerminalDeploy", "CurrStep", stepMode);
- pConfig->ReadConfigValueInt("TerminalDeploy", "CurrState", stepStatus);
- pConfig->ReadConfigValueInt("TerminalDeploy", "TimeStamp", lastRecordTime);
- if (stepMode != DeployStep_Begin && DeployStep_Finished != stepMode) {
- Dbg("not config from cache: step=%d, status=%d", stepMode, stepStatus);
- return true;
- }
- }
- return false;
- }
- void CHealthManagerEntity::OnEntityStateHook(const char* pszEntityName, const char* pszTriggerEntity, EntityStateEnum eState, EntityStateEnum eLastState)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s trigger by %s: from %s to %s", pszEntityName, pszTriggerEntity, SpStrEntityState(eLastState), SpStrEntityState(eState));
- 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:
- {
- CSimpleStringA tmpWarnMsg = CSimpleStringA::Format("%s lost. trig entity:%s,lastState:%d", pszEntityName, pszTriggerEntity, 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);
- //'0':0x30 'A':0x41
- if (iByteLow > 0 && iByteLow < 10)
- csResultCode.Format("RTA51%c%c", iByteHigh + 0x30, iByteLow + 0x30);
- else
- csResultCode.Format("RTA51%c%c", iByteHigh + 0x30, iByteLow -10 + 0x41);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setLogCode("QLR0402501Z001").setResultCode(csResultCode.GetData())(tmpWarnMsg.GetData());
- }
- break;
- default:
- break;
- }
- }
- }
- void CHealthManagerEntity::ToCalcRebootHourAndMinute(int restartBegin, int restartEnd)
- {
- 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);
- }
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(CHealthManagerEntity)
- SP_END_ENTITY_MAP()
|