123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477 |
- // mod_healthmanager.cpp : Defines the exported functions for the DLL application.
- #include "stdafx.h"
- #if defined(RVC_OS_WIN)
- #include <TlHelp32.h>
- #include <iphlpapi.h>
- #include <ws2tcpip.h>
- #include <Winsock2.h>
- #include <Windows.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>
- #endif //RVC_OS_WIN
- #include <vector>
- #include <iostream>
- #include <fstream>
- #include <regex.h>
- #include "toolkit.h"
- #include "array.h"
- #include "fileutil.h"
- #include "iniutil.h"
- #include "osutil.h"
- #include "EntityBootStruct.h"
- #include "RestfulFunc.h"
- #include "api_manage_regist.h"
- #include "JsonConvertHelper.hpp"
- using namespace std;
- #include "mod_healthmanager.h"
- #include "CommEntityUtil.hpp"
- #include "CommEntitySettings.hpp"
- #include "GetDevInfoHelper.h"
- #include "TerminalInfoQueryConn.h"
- #if defined(RVC_OS_WIN)
- #pragma comment( lib, "advapi32.lib" )
- //the following 20151009
- #pragma comment(lib, "IPHLPAPI.lib")
- #endif //RVC_OS_WIN
- const DWORD HEALTHMANAGER_TIMER_ID = 1;
- const DWORD HEALTHMANAGER_WD_TIMER_ID = 2;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL = 60000;
- const DWORD HEALTHMANAGER_WD_TIMER_INTERVAL = 50000;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL_MINUTE = (HEALTHMANAGER_TIMER_INTERVAL/60000)*3;
- #define WORKING_BUFFER_SIZE 15000
- #define MAX_TRIES 3
- #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
- #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
- #include "CenterSetting_client_g.h"
- using namespace CenterSetting;
- #include "Initializer_client_g.h"
- using namespace Initializer;
- //for defines in header file
- #include "CameraConfigManage_def_g.h"
- using namespace CameraConfigManage;
- #include "Chromium_client_g.h"
- using namespace Chromium;
- #include "ResourceWatcher_client_g.h"
- using namespace ResourceWatcher;
- 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();
- m_pEntity->EnterState(ctx);
- }
- void HealthManagerSession::Handle_ExitState(SpReqAnsContext<HealthManagerService_ExitState_Req, HealthManagerService_ExitState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ExitState(ctx);
- }
- void HealthManagerSession::Handle_DoEvent(SpReqAnsContext<HealthManagerService_DoEvent_Req, HealthManagerService_DoEvent_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->DoEvent(ctx);
- }
- void HealthManagerSession::Handle_GetEntityCfgInfo(SpReqAnsContext<HealthManagerService_GetEntityCfgInfo_Req, HealthManagerService_GetEntityCfgInfo_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetEntityCfgInfo(ctx);
- }
- void HealthManagerSession::Handle_GetNetworkState(SpReqAnsContext<HealthManagerService_GetNetworkState_Req, HealthManagerService_GetNetworkState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetNetworkState(ctx);
- }
- void HealthManagerSession::Handle_QueryHardwareInfo(SpReqAnsContext<HealthManagerService_QueryHardwareInfo_Req, HealthManagerService_QueryHardwareInfo_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->QueryHardwareInfo(ctx);
- }
- void HealthManagerSession::Handle_ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- }
- void HealthManagerSession::Handle_ControlTerminalLife(
- SpReqAnsContext<HealthManagerService_ControlTerminalLife_Req, HealthManagerService_ControlTerminalLife_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ControlTerminalLife(ctx);
- }
- void HealthManagerSession::Handle_DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->DeployTerminal(ctx);
- }
- void HealthManagerSession::Handle_ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ControlEntityLife(ctx);
- }
- void HealthManagerSession::Handle_Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
- {
- LOG_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:
- */
- void CHealthManagerEntity::OnStarted()
- {
- ErrorCodeEnum result(Error_NotInit);
- int curStep(0);
- m_fConfigMode = IsNotConfigMode(curStep);
- if (m_fConfigMode) {
- //kill guardin process if exists
- char* relates[] = { "guardian" };
- alive_process_info processes[1];
- memset(processes, 0, sizeof(processes));
- int count = 1;
- osutil_detect_unique_app(relates, array_size(relates), &count, processes);
- if (count > 0) {
- Dbg("to kill guardian process which is seem alive.");
- osutil_terminate_related_process(relates, array_size(relates));
- }
- if (curStep >= 0) {
- Dbg("Change Framework status to NotConfig");
- this->GetFunction()->GetPrivilegeFunction()->RefreshFrameworkState(FrameworkState_NotConfig);
- }
- //挑一个状态判断为配置模式,以此操作其他实体的逻辑,比如:
- //集中配置实体不因无集中配置文件进行弹窗报错
- //初始化实体不会自行进行准入验证
- CSimpleStringA strSysValue = CSimpleStringA::Format("Z=%d", curStep);
- result = GetFunction()->SetSysVar("TerminalStage", strSysValue);
- Dbg("update TerminalStage=%s return %s", strSysValue.GetData(), SpStrError(result));
-
- CSimpleStringA machineType = SP::Module::Comm::GetCurrMachineType(this);
- CSimpleStringA configPath = SP::Module::Comm::GetCurrEntityConfigPath(this);
- const int stepCount = GetDeployStepFromStatus(curStep);
- for (int i = stepCount, j=0; i >= 0; --i, j++) {
- switch (j) {
- case 0:
- {
- Dbg("Initial Boot Step.");
- std::shared_ptr<TerminalDeployStep> step = std::make_shared<TerminalDeployStep>("");
- step->LoadConfig(configPath);
- result = step->StartStartupEntities(this);
- if (result != Error_Succeed) {
- LogError(Severity_Middle, result, 0, CSimpleStringA::Format("Initial Boot Step failed: %s", SpStrError(result)));
- return;
- }
- }
- break;
- case 1:
- {
- Dbg("Second Boot Step.");
- LOG_ASSERT(!machineType.IsNullOrEmpty());
- std::shared_ptr<TerminalDeploySecondStep> step(nullptr);
- step = std::make_shared<TerminalDeploySecondStep>(machineType);
- step->LoadConfig(configPath);
- result = step->StartStartupEntities(this);
- if (result != Error_Succeed) {
- LogError(Severity_Middle, result, 0, CSimpleStringA::Format("Second Boot Step failed: %s", SpStrError(result)));
- return;
- }
- }
- break;
- case 2:
- {
- Dbg("Third Boot Step.");
- LOG_ASSERT(!machineType.IsNullOrEmpty());
- std::shared_ptr<TerminalDeployThirdStep> step(nullptr);
- step = std::make_shared<TerminalDeployThirdStep>(machineType);
- step->LoadConfig(configPath);
- result = step->StartStartupEntities(this);
- if (result != Error_Succeed) {
- LogError(Severity_Middle, result, 0, CSimpleStringA::Format("Third Boot Step failed: %s", SpStrError(result)));
- return;
- }
- }
- break;
- default:
- break;
- }
- }
- CSimpleStringA strUrl;
- result = GetGuidePageUrlWithStep(curStep, strUrl);
- Dbg("Url:{%s}", (LPCTSTR)strUrl);
- result = TellChromiumOpenGuidePage(strUrl);
- }
- }
- bool CHealthManagerEntity::DoWatchDog(WatchDogOp eOp)
- {
- switch(eOp)
- {
- case WD_OP_START:
- {
- if (m_pWatchDogClient == NULL)
- {
- m_pWatchDogClient = new WatchDogService_ClientBase(this);
- ErrorCodeEnum eErrConn = m_pWatchDogClient->Connect();
- if (eErrConn != Error_Succeed) {
- Dbg("WatchDog connected failed.");
- m_pWatchDogClient->SafeDelete();
- m_pWatchDogClient = NULL;
- break;
- }
- else
- Dbg("WatchDog connected.");
- }
- WatchDogService_StartWatch_Req req;
- req.Delay = 120;//oiltmp
- req.Timeout = 60;
- WatchDogService_StartWatch_Ans ans;
- ErrorCodeEnum eErrStart = m_pWatchDogClient->StartWatch(req,ans,10000);
- if (eErrStart == Error_Succeed)
- m_bWatchDog = true;
- Dbg("start watch %d.",eErrStart);
- }
- break;
- case WD_OP_STOP:
- {
- if (!m_bWatchDog)
- break;
- WatchDogService_StopWatch_Req req;
- WatchDogService_StopWatch_Ans ans;
- ErrorCodeEnum eErrStop = m_pWatchDogClient->StopWatch(req,ans,10000);
- if (eErrStop == Error_Succeed)
- m_bWatchDog = false;
- Dbg("stop watchd %d.",eErrStop);
- }
- break;
- case WD_OP_REFRESH:
- {
- if (!m_bWatchDog)
- break;
- WatchDogService_Refresh_Req req;
- WatchDogService_Refresh_Ans ans;
- ErrorCodeEnum eErrRefresh = m_pWatchDogClient->Refresh(req,ans,10000);
- Dbg("refresh watchdog %d.",eErrRefresh);
- }
- break;
- default:
- break;
- }
- return true;
- }
- void CHealthManagerEntity::OnWatchDogTimeout()
- {
- xxx++;
- if (m_bWatchDog && xxx == 5)
- {
- DoWatchDog(WD_OP_STOP);
- //oiltmp
- Sleep(180000);
- Dbg("have sleep 18000,wake up.");
- //DoWatchDog(WD_OP_START);
- }
- else if (m_bWatchDog && xxx<5)
- {
- DoWatchDog(WD_OP_REFRESH);
- GetFunction()->ResetTimer(HEALTHMANAGER_WD_TIMER_ID, HEALTHMANAGER_WD_TIMER_INTERVAL);
- }
- }
- int CHealthManagerEntity::SystemRestart(bool bPeriod, bool bImmediately,bool bNow)
- {
- if (bPeriod)
- {
- Dbg("restart periodly.");
- m_restartTimes = 0;
- }
- if (bNow)
- {
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
- int x = SystemShutdown(TRUE);
- Dbg("From ie to shutdown %d",x);
- return 0;
- }
- SYSTEMTIME localTime;
- GetLocalTimeRVC(localTime);
-
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (err != Error_Succeed) {
- LOG_TRACE("open cfg file failed!");
- return -1;
- }
- //
- //ups restart
- if (m_pUpsClient != NULL)
- {
- if (!m_bToRestart)
- {
- m_restartTimes++;
- if (m_restartTimes > m_maxRestartTimes)
- {
- Dbg("restart too many times(%d,%d),give up.",m_restartTimes,m_maxRestartTimes);
- m_restartTimes--;
- return -1;
- }
- Dbg("the %d restart.",m_restartTimes);
- spConfigRun->WriteConfigValueInt("Run","RestartTimes",m_restartTimes);
- if (m_lastHour != localTime.wHour)
- {
- m_lastHour = localTime.wHour;
- Dbg("set last hour to %d", m_lastHour);
- spConfigRun->WriteConfigValueInt("Run", "LastHour", m_lastHour);
- }
- }
- else
- return 0;
- UpsService_Shutdown_Req req;
- UpsService_Shutdown_Ans ans;
- if (bImmediately)
- {
- req.ShutdownTime = 1;
- req.UpTime = 1;
- }
- else
- {
- req.ShutdownTime = 1;//oiltmp
- req.UpTime = 3; //oiltmp
- }
- ErrorCodeEnum eErrShutdown = m_pUpsClient->Shutdown(req,ans,10000);
- if (eErrShutdown == Error_Succeed)
- {
- //m_lastHour = localTime.wHour;
- Dbg("to shutdown");
- m_bToRestart = true;
- Sleep(20000);
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger,m_eRebootWay);
- int ret;
- if (m_bGetUpsStateFlag)
- ret = SystemShutdown();
- else
- ret = SystemShutdown(TRUE);
- Dbg("after ups,SystemShutdown result %d",ret);
- }
- else
- Dbg("shutdown failed(%d)",eErrShutdown);
- }
- else
- {
- Dbg("no ups,so to restart directly.");
- if (!m_bToRestart)
- {
- m_restartTimes++;
- if (m_restartTimes > m_maxRestartTimes)
- {
- Dbg("restart too many times(%d,%d),give up.",m_restartTimes,m_maxRestartTimes);
- m_restartTimes--;
- return -1;
- }
- Dbg("the %d restart.",m_restartTimes);
- spConfigRun->WriteConfigValueInt("Run","RestartTimes",m_restartTimes);
- if (m_lastHour != localTime.wHour)
- {
- m_lastHour = localTime.wHour;
- Dbg("set last hour to %d", m_lastHour);
- spConfigRun->WriteConfigValueInt("Run", "LastHour", m_lastHour);
- }
- //oilyang 20140606
- //framework to reboot os
- //int ret = SystemShutdown(TRUE);
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger,RebootWay_OS);
- //Dbg("no ups,SystemShutdown result %d",ret);
- }
- }
- return 0;
- }
- /** 这里建议改用调用框架提供的接口,关机、重启均支持 [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
- }
- ErrorCodeEnum CHealthManagerEntity::SystemShutdownThroughUPS(DWORD msPreShutdown, DWORD msPreRestart)
- {
- bool upsIsNull = true;
- ErrorCodeEnum result = Error_Unexpect;
- if (m_pUpsClient) {
- m_pUpsClient->GetFunction()->CloseSession();
- m_pUpsClient = NULL;
- upsIsNull = false;
- }
- m_pUpsClient = new UpsService_ClientBase(this);
- ErrorCodeEnum eErrConn = m_pUpsClient->Connect();
- if (eErrConn != Error_Succeed) {
- Dbg("Ups connected failed: %s", SpStrError(eErrConn));
- m_pUpsClient->SafeDelete();
- m_pUpsClient = NULL;
- return eErrConn;
- }
- do
- {
- UpsService_GetStatus_Req req;
- UpsService_GetStatus_Ans ans;
- ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req, ans, 3000);
- Dbg("current state %d", ans.Status);
- } while (false);
- do
- {
- UpsService_Shutdown_Req req;
- UpsService_Shutdown_Ans ans;
- req.ShutdownTime = msPreShutdown; //刚好可以等到框架退出
- req.UpTime = msPreRestart; //要求5分钟内拔掉电源来实现真正断电关机
- ErrorCodeEnum eErrShutdown = m_pUpsClient->Shutdown(req, ans, 10000);
- if (eErrShutdown == Error_Succeed) {
- Dbg("Invoke UPS::Shutdown successfully.");
- result = Error_Succeed;
- } else {
- CSimpleStringA tmp = CSimpleStringA::Format("通过UPS关机失败:%s", SpStrError(eErrShutdown));
- this->GetFunction()->ShowFatalError(tmp);
- result = eErrShutdown;
- }
- } while (false);
- if (upsIsNull && m_pUpsClient) {
- m_pUpsClient->GetFunction()->CloseSession();
- m_pUpsClient = NULL;
- }
- return result;
- }
- int CHealthManagerEntity::FrameworkShutdown(bool bRestart)
- {
- #ifdef RVC_OS_WIN
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
- ZeroMemory( &si, sizeof(si) );
- si.cb = sizeof(si);
- ZeroMemory( &pi, sizeof(pi) );
- GetFunction()->FlushLogFile();
- // LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\\Program Files\\MyApp\" -L -S"));
- //CreateProcess(NULL, szCmdline, /*...*/);
- // Start the child process.
- CSimpleStringA csRestart,csVerPath,csAll,csSep("\""),csBlank(" "),csScript("wscript.exe"),csReFlag("r");
- csRestart = "sprestart.exe ";
- ErrorCodeEnum Error = GetFunction()->GetPath("RootVer", csVerPath);
- //csVerPath +="\\spexplorerfast.vbs";
- 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;
- Dbg("allpath[%s]",(LPCTSTR)csAll);
- LPTSTR szCmdline = _strdup(csAll);
- if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
- {
- Dbg("CreateProcess failed (%d).\n", GetLastError());
- return -1;
- }
- m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
- //MessageBoxA(0,0,0,0);
- DWORD dwErr = GetLastError();
- // Wait until child process exits.
- WaitForSingleObject( pi.hProcess, INFINITE );
-
-
- // Close process and thread handles.
- CloseHandle( pi.hProcess );
- CloseHandle( pi.hThread );
- return 0;
- #else
- Dbg("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)
- {
- Dbg("restart mc NoPrivilege");
- return Error_NoPrivilege;
- }
- map<CSimpleStringA,ModuleRunInfo>::iterator it;
- it = m_modRunInfo.find(pEntityName);
- if (it == m_modRunInfo.end())
- {
- Dbg("add %s to modfuninfo(%d).",pEntityName,m_modRunInfo.size());
- m_modRunInfo[pEntityName].count = 1;
- m_modRunInfo[pEntityName].dwStart = GetTickCountRVC();
- }
- else
- {
- Dbg("modruninfo size %d",m_modRunInfo.size());
- Dbg("%d",m_modRunInfo[pEntityName].count);
- (m_modRunInfo[pEntityName].count)++;
- Dbg("%d",m_modRunInfo[pEntityName].count);
- }
- CSmartPointer<IAsynWaitSp> spWait;
- ErrorCodeEnum eErrCode = Error_Succeed;
- eErrCode = pFuncPrivilege->TerminateEntity(pEntityName,spWait);
- if (spWait != NULL)
- eErrCode = spWait->WaitAnswer(10000);
- if (eErrCode != Error_Succeed)
- {
- Dbg("kill %s %d",pEntityName,eErrCode);
- return eErrCode;
- }
- Sleep(3000);
- eErrCode = pFuncPrivilege->StartEntity(pEntityName,NULL,spWait);
- if (spWait != NULL)
- eErrCode = spWait->WaitAnswer(10000);
- if (eErrCode != Error_Succeed)
- {
- Dbg("start %s %d",pEntityName,eErrCode);
- return eErrCode;
- }
- //m_modRestartCount++;
- //if (m_modRestartCount == 1)
- // m_MCStart = GetTickCount();
- DWORD dwMaxTimes,dwInternal;
- if (m_modCfgInfo.find(pEntityName) == m_modCfgInfo.end())
- {
- dwMaxTimes = m_restartMode[RESTART_MODE_DEFAULT].dwTimes;
- dwInternal = m_restartMode[RESTART_MODE_DEFAULT].dwInternal;
- }
- else
- {
- dwMaxTimes = m_restartMode[m_modCfgInfo[pEntityName]].dwTimes;
- dwInternal = m_restartMode[m_modCfgInfo[pEntityName]].dwInternal;
- }
- Dbg("%d,%d,%s restart %d times",dwMaxTimes,dwInternal,pEntityName,m_modRunInfo[pEntityName].count);
- if (m_modRunInfo[pEntityName].count > dwMaxTimes)
- {
- m_MCEnd = GetTickCountRVC();
- if (m_MCEnd-m_modRunInfo[pEntityName].dwStart < dwInternal)
- {
- Dbg("wait chance to restart pc.");
- //if (_strnicmp(pEntityName, "FaceTracking", strlen("FaceTracking")) != 0)
- // m_bWaitRestartPC = true;
- }
- else
- {
- m_modRunInfo[pEntityName].dwStart = m_MCEnd;
- m_modRunInfo[pEntityName].count = 0;
- LogWarn(Severity_Low,Error_Unexpect,LOG_WARN_HEALTH_MODULE_RESTART_TIMES
- ,"restart x times in more than 10mins");
- }
- }
- return eErrCode;
- }
- void CHealthManagerEntity::AfterWaitRestartPC()
- {
- ReadMachineDataBySyncSerivce();
- Dbg("menu:[%s]",(LPCTSTR)m_menuChoice);
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- Dbg("restart pc NoPrivilege");
- return;
- }
- ErrorCodeEnum eErr;
- CSimpleStringA csCustomerHandle("");
- eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle);
- Dbg("cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle);
- if (eErr != Error_Succeed)
- {
- Dbg("get CustomerHandle failed (%d).",eErr);
- }
- else if (csCustomerHandle[0] == 'N')
- {
- m_bWaitRestartPC = false;
- pFuncPrivilege->DisplayBlueScreen("暂停服务test");
- Dbg("time comes,restart machine");
- m_eRebootTrigger = RebootTrigger_RunExcepition;
- m_eRebootWay = RebootWay_Power;
- SystemRestart(false, true);
- }
- }
- void CHealthManagerEntity::UpsSupplyLockScreen()
- {
- ErrorCodeEnum eErr;
- CSimpleStringA csCustomerHandle("");
- eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle);
- Dbg("upslockscreen cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle);
- if (eErr != Error_Succeed)
- {
- Dbg("get CustomerHandle failed (%d).",eErr);
- }
- else// if (csCustomerHandle[0] == 'N')
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- if (pFuncPrivilege == NULL)
- {
- Dbg("display screen NoPrivilege");
- return;
- }
- pFuncPrivilege->DisplayBlueScreen("暂停服务");
- LogEvent(Severity_High,LOG_EVT_HEALTH_UPS_NO_ELECTOR,"ups no elector,to shutdown machine");
- Dbg("ups no elector,display screen.");
- //oiltmp eject card and sth else
- Sleep(30000);
- if (m_bUpsWaitLock)
- {
- m_bUpsWaitLock = false;
- m_bScreenLock = true;
- int ret = SystemShutdown();
- Dbg("SystemShutdown result %d",ret);
- }
- else
- {
- pFuncPrivilege->UndisplayBlueScreen();
- m_bUpsWaitLock = false;
- m_bScreenLock = false;
- }
- }
- }
- void CHealthManagerEntity::OnCheckTimeTimeout()
- {
- if (m_bNeedToRestartIE)
- {
- //oilyang 20160704
- //to judge in main page & the phone is offline
- CSimpleStringA csCustHandle("");
- ErrorCodeEnum eErr = Error_Unexpect;
- eErr = GetFunction()->GetSysVar("CustomerHandle", csCustHandle);
- if (eErr == Error_Succeed)
- {
- if (csCustHandle.Compare("C") != 0 && csCustHandle.Compare("T") != 0 && csCustHandle.Compare("G") != 0)
- {
- if (m_bInMainPage)
- {
- Dbg("to restart iebrowser.");
- RestartIE();
- }
- }
- }
-
- }
- SYSTEMTIME localTime;
- GetLocalTimeRVC(localTime);
- //99 is initial value of m_preDay
- if (m_preDay != 99 && m_preDay != localTime.wDayOfWeek && m_bNeedToRestartPAD == false)
- m_bNeedToRestartPAD = true;
- m_preDay = localTime.wDayOfWeek;
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr != Error_Succeed)
- Dbg("timer open cfg file failed!");
- else
- {
- if (localTime.wHour != m_lastHour)
- {
- Dbg("hour changed,to set restart times to 0");
- spConfigRun->WriteConfigValueInt("Run", "RestartTimes", 0);
- }
- }
- GetNetDeviceState();
- if (_strnicmp(m_sysStaticInfo.strMachineType.GetData(), "RVC.PAD", strlen("RVC.PAD")) == 0)
- {
- if (m_bNeedToRestartPAD)
- {
- ULONGLONG ull = 0;
- ull = GetTickCountRVC();
- int osRunHours = 0, osRunDays = 0;
- osRunHours = (ull / (1000 * 60 * 60));
- osRunDays = osRunHours / 24;
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (m_maxRunDays <= 0)
- m_maxRunDays = 7;
- if (osRunDays >= m_maxRunDays)
- {
- Dbg("os has run %d hour,to restart os.", osRunHours);
- spConfigRun->WriteConfigValueInt("Restart", "DayNum", 0);
- m_eRebootTrigger = RebootTrigger_Period;
- m_eRebootWay = RebootWay_Power;
- SystemRestart(true,true);
- }
- else if (osRunDays >= 1)
- {
- if (osRunDays > m_dayNum)
- {
- Dbg("os has run %d hour,to restart framework.", osRunHours);
- spConfigRun->WriteConfigValueInt("Restart", "DayNum", osRunDays);
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Period, RebootWay_Framework);
- }
- }
- }
- }
- else //not RVC.PAD
- {
- if (m_wDayOfWeek != localTime.wDayOfWeek)
- {
- if (localTime.wHour == m_restartHour && localTime.wMinute >= m_restartMinute
- && localTime.wMinute <= (m_restartMinute + HEALTHMANAGER_TIMER_INTERVAL_MINUTE))
- {
- m_wDayOfWeek = localTime.wDayOfWeek;
- m_eRebootTrigger = RebootTrigger_Period;
- m_eRebootWay = RebootWay_Power;
- BOOL bRet = SystemRestart(true,true);
- Dbg("restart machine[%d][%d] bRet=%d, LastError=%d", localTime.wHour, localTime.wMinute, bRet, GetLastError());
- Dbg("not rvc.pad %s,%s", m_sysStaticInfo.strMachineType.GetData(), (const char*)m_sysStaticInfo.strMachineType);
- }
- }
- }
- if (m_pUpsClient == NULL)
- {
- CSimpleStringA csRunState("B");
- GetFunction()->GetSysVar("RunState",csRunState);
- if (csRunState[0] != 'B' || csRunState[0] != 'I')
- {
- if (_strnicmp(m_sysStaticInfo.strMachineType.GetData(), "RVC.Stand2S", strlen("RVC.Stand2S") == 0))
- {
- int ret = ConnectUps();
- Dbg("connect ups %d.", ret);
- }
- }
- }
- else
- {
- UpsService_GetStatus_Req req;
- UpsService_GetStatus_Ans ans;
- ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req,ans,3000);
- if (eErrState == Error_Succeed)
- {
- m_bGetUpsStateFlag = true;
- switch(ans.Status)
- {
- case UPS_STATUS_NORMAL:
- m_bUpsWaitLock = false;
- m_upsNoElectorCount = 0;
- break;
- case UPS_STATUS_ERROR_TO_GET_STATUS:
- m_upsStateCount++;
- if (m_upsStateCount > 3)
- {
- //logwarn oiltmp
- }
- break;
- case UPS_STATUS_NO_ELECTOR:
- m_bUpsWaitLock = true;
- m_upsNoElectorCount++;
- if (m_upsNoElectorCount > 2)
- {
- //logwarn oiltmp
- //notify front end
- //shutdown pc or not?
- }
- break;
- default:
- break;
- }
- //Dbg("current state %d",ans.Status);
- }
- else
- {
- Dbg("get ups state failed(%d).",eErrState);
- m_bGetUpsStateFlag = false;
- if (eErrState == Error_NetBroken)
- {
- m_pUpsClient->GetFunction()->CloseSession();
- m_pUpsClient = NULL;
- }
- }
- }
- ReadMachineDataBySyncSerivce();
- //Dbg("fsm:%d,menu:%s", m_fsm.GetFSMState(),(const char*)m_menuChoice);
- 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情况
- {
- //oilyang@20210923 N for "Normal",changed for liuwentao
- GetFunction()->SetSysVar("RunState", "N");
- iCheckGuardian = CheckGuardianIsRun(true);
- if (!m_bSayIdle)
- {
- m_bSayIdle = true;
- if (iCheckGuardian > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- int ret = m_pfUpgradeRestart(3, 0);
- Dbg("healthmanager say idle,so tell the guardian.%d", ret);
- }
- }
- CSimpleStringA csRunInfo,csStartTime;
- if ((GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
- {
- Dbg("get runinfo path failed(%d)");
- }
- else
- {
- csStartTime = csRunInfo + "/runcfg/starttime.dat";
- int ret = remove(csStartTime);
- if (ret == 0)
- Dbg("delete time file error.[%d]",GetLastError());
- }
- }
- if (iCheckGuardian > 0)
- {
- if (m_pfShake != NULL)
- {
- WorkStateEnum eShake;
- Dbg("to shake...");
- int ret = m_pfShake(eShake);
- //if (eErrShake != Error_Succeed)
- Dbg("shake hand result:%d,work state %d", ret, eShake);
- }
- if (!m_bHealthInit)
- {
- bool bStop = StopGuardian();
- if (bStop)
- {
- m_bHealthInit = true;
- bool bGuardian = StartGuardian();
- Dbg("restart guardian %d", bGuardian);
- }
- }
- }
- else if (iCheckGuardian == -1)
- {
- Dbg("to start guardian");
- bool bGuardian = StartGuardian();
- Dbg("start guardian %d",bGuardian);
- }
- }
- else
- {
- //oilyang@20190905 add if auth suc,tell guardian,for upgrade
- if (m_fsm.GetAccessAuthFlag())
- {
- if (CheckGuardianIsRun(true) > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- int ret = m_pfUpgradeRestart(5, 0);
- Dbg("auth suc,so tell the guardian.%d", ret);
- }
- }
- }
- }
- }
- 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;
- int ret = m_pfShake(eShake);
- Dbg("accessauth told me not to restart framework,so that it can have time to retry.%d", ret);
- }
- }
- }
- if (m_fsm.GetFSMState() == HM_FSM_STATE_CMS)
- {
- GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL);
- return;
- }
- if (m_bWaitRestartPC)
- {
- Dbg("finally we the restart time come,no wait.");
- //m_bWaitRestartPC = false;
- AfterWaitRestartPC();
- }
- if (m_bUpsWaitLock)
- {
- UpsSupplyLockScreen();
- }
- else
- {
- //no need to un-display blue screen? oiltest 20140320
- //if (m_bScreenLock)
- //{
- // CSmartPointer<IEntityFunction> pFunc = GetFunction();
- // CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- // if (pFuncPrivilege == NULL)
- // {
- // Dbg("unlock screen NoPrivilege");
- // return;
- // }
- // pFuncPrivilege->UndisplayBlueScreen();
- // m_bScreenLock = false;
- //}
- }
- 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);
- Dbg("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
- Dbg("to stop guardian");
- HANDLE hSnapshot;
- int rc = TRUE;
- int result;
- HANDLE hProcess;
- //find and kill guardian.exe
- hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- if (hSnapshot)
- {
- PROCESSENTRY32 pe;
- pe.dwSize = sizeof(pe);
- if (Process32First(hSnapshot, &pe))
- {
- do {
- if (_stricmp(&pe.szExeFile[0], "guardian.exe") == 0)
- {
- hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID );
- if( hProcess == NULL )
- {
- Dbg("Fail to open process(%d)!",GetLastError());
- return false;
- }
- else
- {
- result = TerminateProcess(hProcess,-1);
- if (result)
- {
- Dbg("Terminate guardian suc.");
- return true;
- }
- else
- {
- Dbg("Terminate guardian failed(%d).",GetLastError());
- return false;
- }
- CloseHandle( hProcess );
- }
- Sleep(3000);
- WaitForSingleObject(&pe.th32ProcessID, INFINITE );
- break;
- }
- } while (Process32Next(hSnapshot, &pe));
- }
- CloseHandle(hSnapshot);
- }
- Sleep(3000);
- return false;
- #else
- 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();
- if (m_sysStaticInfo.strMachineType.Compare("RVC.IL") == 0)
- {
- Dbg("machine type is RVC.IL,no need to start guardian.exe");
- return false;
- }
- Dbg("to start guardian");
- // Start the child process.
- CSimpleStringA csBinPath;
- ErrorCodeEnum Error = GetFunction()->GetPath("Bin", csBinPath);
- #ifdef RVC_OS_WIN
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
- ZeroMemory( &si, sizeof(si) );
- si.cb = sizeof(si);
- ZeroMemory( &pi, sizeof(pi) );
- GetFunction()->FlushLogFile();
- // Start the child process.
- CSimpleStringA csAll,csSep("\"");
- csBinPath +="\\guardian.exe";
- csAll = csSep + csBinPath + csSep;
- Dbg("guardian path[%s]",(LPCTSTR)csAll);
- LPTSTR szCmdline = _strdup(csAll);
- if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
- {
- Dbg("CreateProcess failed (%d).\n", GetLastError());
- return false;
- }
- DWORD dwErr = GetLastError();
- return true;
- #else
- 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_Software, spConfig);
- if (err != Error_Succeed) {
- LOG_TRACE("open cfg file failed!");
- return false;
- }
- m_restartHour = m_restartMinute = 1;
- m_maxRestartTimes = 3;
- int defaultTimesMax,defaultInternal,lowTimesMax,lowInternal;
- defaultTimesMax = 10;
- defaultInternal = 600000;
- lowTimesMax = 5;
- lowInternal = 600000;
- spConfig->ReadConfigValueInt("init","RestartHour",m_restartHour);
- spConfig->ReadConfigValueInt("init","RestartMinute",m_restartMinute);
- int testflag;
- spConfig->ReadConfigValueInt("init","TestFlag",testflag);
- m_testFlag = testflag;
- spConfig->ReadConfigValueInt("Run","MaxRestartTimes",m_maxRestartTimes);
- Dbg("m_maxRestartTimes(%d)",m_maxRestartTimes);
- spConfig->ReadConfigValueInt("ModRestartSettings","DefaultTimesMax",defaultTimesMax);
- spConfig->ReadConfigValueInt("ModRestartSettings","DefaultInternal",defaultInternal);
- spConfig->ReadConfigValueInt("ModRestartSettings","LowTimesMax",lowTimesMax);
- spConfig->ReadConfigValueInt("ModRestartSettings","LowInternal",lowInternal);
- m_restartMode[RESTART_MODE_DEFAULT].dwTimes = defaultTimesMax;
- m_restartMode[RESTART_MODE_DEFAULT].dwInternal = defaultInternal;
- m_restartMode[RESTART_MODE_LOW].dwTimes = lowTimesMax;
- m_restartMode[RESTART_MODE_LOW].dwInternal = lowInternal;
- CSimpleStringA csDefaultModule,csLowModule;
- spConfig->ReadConfigValue("ModRestartSettings","DefaultModule",csDefaultModule);
- spConfig->ReadConfigValue("ModRestartSettings","LowModule",csLowModule);
- SplitModuleNames(csDefaultModule,RESTART_MODE_DEFAULT);
- SplitModuleNames(csLowModule,RESTART_MODE_LOW);
- Dbg("%d:%d",m_restartHour,m_restartMinute);
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->ReadConfigValueInt("Run", "LastHour", m_lastHour);
- m_dayNum = 1;
- spConfigRun->ReadConfigValueInt("Restart", "DayNum", m_dayNum);
- if (m_dayNum == 0)
- {
- spConfigRun->WriteConfigValueInt("Restart", "DayNum", 0);
- }
- spConfigRun->ReadConfigValueInt("Run", "RestartTimes", m_restartTimes);
- CSmartPointer<IConfigInfo> spCerConfig;
- eErr = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
- spCerConfig->ReadConfigValueInt(GetEntityName(), "MaxRunDays", m_maxRunDays);
- int xNdGuardian = 0;
- spCerConfig->ReadConfigValueInt("NonExclusive", "NonGuardian", xNdGuardian);
- if (xNdGuardian == 1)
- m_bNeedGuardian = false;
- Dbg("central setting:m_maxRunDays:%d,DayNum:%d,xNdGuardian:%d", m_maxRunDays,m_dayNum, xNdGuardian);
- SYSTEMTIME localTime;
- GetLocalTimeRVC(localTime);
- if (m_bInit) {
- m_bInit = false;
- m_wDayOfWeek = localTime.wDayOfWeek;
- }
- eErr = GetFunction()->GetSystemStaticInfo(m_sysStaticInfo);
- if (eErr != Error_Succeed)
- {
- Dbg("Get system static info failed(%s).", SpStrError(eErr));
- m_sysStaticInfo.strMachineType = "";
- m_sysStaticInfo.strSite = "";
- m_sysStaticInfo.InstallVersion = CVersion();
- }
- ReadMachineDataBySyncSerivce();
- ITimerListener *pListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnCheckTimeTimeout);
- Dbg("set timer");
- GetFunction()->SetTimer(HEALTHMANAGER_TIMER_ID, pListener, HEALTHMANAGER_TIMER_INTERVAL);
- //oiltmp 20131204 commented,the following upline(...)add it
- //DoWatchDog(WD_OP_START);
- //ITimerListener *pWDListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnWatchDogTimeout);
- //GetFunction()->SetTimer(HEALTHMANAGER_WD_TIMER_ID, pWDListener, HEALTHMANAGER_WD_TIMER_INTERVAL);
- CSimpleStringA deamonBasePath = "";
- err = GetFunction()->GetPath("bin",deamonBasePath);
- if (err != Error_Succeed) {
- Dbg("for wait deamon get bin path failed(%d).",err);
- return false;
- }
- #if defined(RVC_OS_LINUX)
- deamonBasePath += "/libGuardianBase.so";
- Dbg("gd path [%s]", (LPCTSTR)deamonBasePath);
- void* handle = dlopen(deamonBasePath, RTLD_LAZY);
- if (handle == NULL)
- {
- Dbg("load libGuardianBase.so failed(%d)", errno);
- return false;
- }
- m_pfShake = (pfShakeHands)dlsym(handle, "ShakeHands");
- if (m_pfShake == NULL)
- {
- Dbg("get ShakeHands failed(%d)", GetLastError());
- return false;
- }
- m_pfUpgradeRestart = (pfUpgradeRestart)dlsym(handle, "UpgradeRestart");
- if (m_pfUpgradeRestart == NULL)
- {
- Dbg("get UpgradeRestart failed(%d)", GetLastError());
- return false;
- }
- #else
- deamonBasePath += "\\GuardianBase.dll";
- HMODULE hDll = LoadLibraryA(deamonBasePath);
- Dbg("gd path [%s]", (LPCTSTR)deamonBasePath);
- if (hDll == NULL)
- {
- Dbg("load guardianbase.dll failed(%d)", GetLastError());
- return false;
- }
- m_pfShake = (pfShakeHands)GetProcAddress(hDll,"ShakeHands");
- if (m_pfShake == NULL)
- {
- Dbg("get shakehands failed(%d)",GetLastError());
- return false;
- }
- m_pfUpgradeRestart = (pfUpgradeRestart)GetProcAddress(hDll,"UpgradeRestart");
- if (m_pfUpgradeRestart == NULL)
- {
- Dbg("get UpgradeRestart failed(%d)",GetLastError());
- return false;
- }
- #endif //RVC_OS_LINUX
- Dbg("have load guardian.");
- if (CheckGuardianIsRun(true) > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- Sleep(500);
- Dbg("to tell guardian framework is starting.");
- int ret = m_pfUpgradeRestart(4, 0);//tell guardian framework is starting...oilyang 20150514
- Dbg("feedback of framework is starting.%d", ret);
- }
- }
- m_currentVer = "";
- UpdateSiteToRuncfg();
- return true;
- }
- void CHealthManagerEntity::SplitModuleNames(CSimpleStringA csLine, ModuleReMode eMode)
- {
- string str((const char*)csLine);
- size_t pos = 0,nameEnd = 0;
- size_t len = str.length();
- while(1)
- {
- nameEnd = str.find(',',pos);
- if (nameEnd != string::npos)
- {
- m_modCfgInfo[str.substr(pos,nameEnd-pos).c_str()] = eMode;
- pos = nameEnd + 1;
- }
- else
- {
- if (pos < len)
- m_modCfgInfo[str.substr(pos,nameEnd-pos).c_str()] = eMode;
- break;
- }
- }
- }
- int CHealthManagerEntity::ConnectUps()
- {
- if (m_pUpsClient == NULL)
- {
- m_pUpsClient = new UpsService_ClientBase(this);
- ErrorCodeEnum eErrConn = m_pUpsClient->Connect();
- if (eErrConn != Error_Succeed) {
- Dbg("Ups connected failed(%d).",eErrConn);
- m_pUpsClient->SafeDelete();
- m_pUpsClient = NULL;
- }
- else
- {
- Dbg("ups entity connected.");
- UpsService_GetStatus_Req req;
- UpsService_GetStatus_Ans ans;
- ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req,ans,3000);
- if (eErrState == Error_Succeed)
- {
- m_bGetUpsStateFlag = true;
- Dbg("current state %d",ans.Status);
- return 0;
- }
- else
- Dbg("connect get ups state failed(%d).",eErrState);
- }
- }
- return -1;
- }
- bool CHealthManagerEntity::SaveCurrentVersion()
- {
- CSimpleStringA csRootVer,csRunInfo,csBakFile,csVerFile;
- ErrorCodeEnum eErr;
- if ((eErr = GetFunction()->GetPath("RootVer",csRootVer)) != Error_Succeed)
- {
- LOG_TRACE("Get version path failed(%d).",eErr);
- return false;
- }
- if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
- {
- Dbg("get runinfo path failed(%d)",eErr);
- return false;
- }
- //csVerFile = csRootVer + "\\active.txt";
- csBakFile = csRunInfo + "/runcfg/version.dat";
- //ifstream infile(csVerFile,std::ifstream::binary);
- ofstream outfile (csBakFile,std::ofstream::binary);
- //infile.seekg (0,infile.end);
- //long size = infile.tellg();
- //infile.seekg (0,infile.beg);
- CSimpleStringA csCurrVer = m_sysStaticInfo.InstallVersion.ToString();
- Dbg("get current version [%s]",(LPCTSTR)csCurrVer);
- int size = csCurrVer.GetLength();
- char* buffer = new char[size];
- ZeroMemory(buffer,size);
- //infile.read (buffer,size);
- memcpy(buffer,csCurrVer,size);
- outfile.write (buffer,size);
- delete[] buffer;
- outfile.close();
- //infile.close();
- return true;
- }
- bool CHealthManagerEntity::SaveFrameStartTimeForUpgrade()
- {
- CSimpleStringA csRunInfo,csBakFile;
- ErrorCodeEnum eErr;
- if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
- {
- Dbg("get runinfo path failed(%d)",eErr);
- return false;
- }
- //csVerFile = csRootVer + "\\active.txt";
- csBakFile = csRunInfo + "/runcfg/starttime.dat";
- //ifstream infile(csVerFile,std::ifstream::binary);
- ofstream outfile (csBakFile,std::ofstream::binary);
- CSystemRunInfo sysRunInfo;
- GetFunction()->GetSystemRunInfo(sysRunInfo);
- if (eErr != Error_Succeed)
- {
- Dbg("Get system run info failed(%d).",eErr);
- return false;
- }
- CSimpleStringA csStartTime = sysRunInfo.tmStart.ToTimeString();
- Dbg("get current time start [%s]",(LPCTSTR)csStartTime);
- int size = csStartTime.GetLength();
- char* buffer = new char[size];
- ZeroMemory(buffer,size);
- //infile.read (buffer,size);
- memcpy(buffer,csStartTime,size);
- outfile.write (buffer,size);
- delete[] buffer;
- outfile.close();
- //infile.close();
- return true;
- }
- bool CHealthManagerEntity::VersionRollBack(const char *pVerion)
- {
- CSimpleStringA csCurrVer = m_sysStaticInfo.InstallVersion.ToString();
- if (_stricmp(csCurrVer,pVerion) == 0)
- {
- Dbg("destination version identified the current version.");
- return false;
- }
- m_pUpgMgr = new UpgradeMgrService_ClientBase(this);
- if (m_pUpgMgr == NULL)
- {
- Dbg("create UpgradeMgr client failed.");
- return false;
- }
- CSmartPointer<IAsynWaitSp> pAsyncWait;
- ErrorCodeEnum eErr = m_pUpgMgr->Connect(pAsyncWait);
- if (eErr != Error_Succeed)
- {
- Dbg("connect to UpgradeMgr failed(%d)",eErr);
- return false;
- }
- else
- eErr = pAsyncWait->WaitAnswer(10000);
- UpgradeMgrService_RollbackUpdate_Req req;
- req.strVersion = pVerion;
- UpgradeMgrService_RollbackUpdate_Ans ans;
- eErr = m_pUpgMgr->RollbackUpdate(req,ans,10000);
- if (eErr == Error_Succeed)
- {
- Dbg("version rollback doing.");
- m_bVerRollback = true;
- return true;
- }
- else
- {
- Dbg("UpgradeMgr rollback failed(%d)",eErr);
- return false;
- }
- }
- void CHealthManagerEntity::ReadMachineDataBySyncSerivce()
- {
- ErrorCodeEnum eSync;
- if (m_pSync == NULL)
- {
- m_pSync = new SyncService_ClientBase(this);
- if (m_pSync != NULL)
- {
- ErrorCodeEnum eSync = m_pSync->Connect();
- if (eSync != Error_Succeed)
- {
- Dbg("connect to SyncService failed %d.",eSync);
- m_pSync->SafeDelete();
- m_pSync = NULL;
- }
- }
- }
- else
- {
- SyncService_GetMachineData_Req req;
- SyncService_GetMachineData_Ans ans;
- req.key = "MenuChoice";
- eSync = m_pSync->GetMachineData(req,ans,10000);
- if (eSync == Error_Succeed)
- {
- m_menuChoice = ans.value;
- if (m_menuPre.Compare(m_menuChoice) != 0)
- {
- m_menuPre = m_menuChoice;
- Dbg("menu:[%s]", (LPCTSTR)m_menuChoice);
- if (m_menuChoice.Compare("Main") == 0)
- {
- //according to yangzixiong,comment it. by oilyang 20160615
- //LogEvent(Severity_Middle, LOG_EVT_USB_CONTROL_OFF, "usb off");//just for Stand2S
- }
- }
- }
- else
- {
- m_menuChoice = "";
- }
- }
- }
- int CHealthManagerEntity::GetNetDeviceState()
- {
- return 0;
- }
- int CHealthManagerEntity::UpdateSiteChangeFlag()
- {
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
- if (eErr != Error_Succeed) {
- Dbg("UpdateSiteChangeFlag open run cfg file failed!");
- return -1;
- }
- eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 1);
- Dbg("Write SiteChanged 1.err[%d]",eErr);
- return 0;
- }
- int CHealthManagerEntity::UpdateSiteToRuncfg(bool bWriteSite,bool bClearSiteFlag)
- {
- Dbg("bClearSiteFlag[%d]",bClearSiteFlag);
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
- if (eErr != Error_Succeed) {
- Dbg("UpdateSiteToRuncfg open run cfg file failed!");
- return -1;
- }
- if (!bClearSiteFlag)
- {
- int siteChangedFlag = 0;
- eErr = spConfig->ReadConfigValueInt("AboutSite", "SiteChanged", siteChangedFlag);
- if (eErr == Error_Succeed)
- {
- if (siteChangedFlag != 0)
- {
- bWriteSite = false;
- }
- }
- }
- else
- {
- eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 0);
- Dbg("UpdateSiteToRuncfg.Write Site (%d).", eErr);
- }
- if (bWriteSite)
- {
- spConfig->WriteConfigValue("AboutSite", "Site", m_sysStaticInfo.strSite);
- }
- return 0;
- }
- int CHealthManagerEntity::WriteSiteToRootIni()
- {
- LOG_FUNCTION();
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
- if (eErr != Error_Succeed) {
- Dbg("UpdateSiteToRuncfg open run cfg file failed!");
- return -1;
- }
- CSimpleStringA csSite("");
- eErr = spConfig->ReadConfigValue("AboutSite", "Site", csSite);
- if (eErr == Error_Succeed)
- {
- CSimpleStringA path("");
- GetFunction()->GetPath("HardwareCfg", path);
- path.Append("\\");
- path.Append("root.ini");
- Dbg("WriteSiteToRootIni[%s]",(LPCTSTR)path);
- //oiltestlinux comment the following 2 lines
- //BOOL bRet = ::WritePrivateProfileStringA("Terminal", "Site", csSite, path);
- //Dbg("WriteSiteToRootIni:write site bRet = %d", bRet);
- }
- return 0;
- }
- int CHealthManagerEntity::RestartIE()
- {
- CSimpleStringA csBrowserName = "IEBrowser";
- m_bNeedToRestartIE = false;
- CSmartPointer<IAsynWaitSp> spWait;
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = GetFunction().ConvertCase<IEntityFunctionPrivilege>();
- if (m_fsm.IsCutIEBrowser())
- csBrowserName = "Chromium";
- ErrorCodeEnum eErr = pFuncPrivilege->TerminateEntity(csBrowserName.GetData(), spWait);
- if (eErr == Error_Succeed)
- {
- if (spWait != NULL)
- spWait->WaitAnswer(10000);
- }
- else
- Dbg("TerminateEntity browser failed.%d", eErr);
- eErr = pFuncPrivilege->StartEntity(csBrowserName.GetData(), "", spWait);
- if (eErr == Error_Succeed)
- {
- if (spWait != NULL)
- eErr = spWait->WaitAnswer(15000);
- }
- else
- {
- Dbg("Start browser failed(%d).", eErr);
- }
- return 0;
- }
- void CHealthManagerEntity::QueryHardwareInfo(SpReqAnsContext<HealthManagerService_QueryHardwareInfo_Req, HealthManagerService_QueryHardwareInfo_Ans>::Pointer ctx)
- {
- CSystemStaticInfo info;
- GetFunction()->GetSystemStaticInfo(info);
- NetworkAddressesList macAddrs;
- NetworkAddressesList ipAddrs;
- SP::Module::Net::GetINETMacAddresses(macAddrs, ipAddrs);
- ctx->Ans.ip = ipAddrs;
- ctx->Ans.mac = macAddrs;
- ctx->Ans.machineType = info.strMachineType;
- ctx->Ans.site = info.strSite;
- ctx->Ans.terminalNo = info.strTerminalID;
- ctx->Ans.termLimit = __ReadCenterConfigStr("TermLimitSwitch", "IEBrowser");
- ctx->Ans.termVersion = info.InstallVersion.ToString();
- ctx->Answer(Error_Succeed);
- }
- void CHealthManagerEntity::ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
- {
- 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; 6:poweroff with ups-- >
- 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;
- case 6:
- if(ctx->Req.reserved1 > 0 && ctx->Req.reserved2 > 0)
- result = SystemShutdownThroughUPS(ctx->Req.reserved1, ctx->Req.reserved2);
- else
- result = SystemShutdownThroughUPS();
- if (result == Error_Succeed) {
- Sleep(300);
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_OS);
- }
- 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::GetINETMacAddresses(NetworkAddressesList &macList, NetworkAddressesList &ipList)
- {
- #ifdef RVC_OS_WIN
- PIP_ADAPTER_ADDRESSES pAddresses = NULL;
- ULONG family = AF_INET;
- ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
- ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
- Dbg("GetINETMacAddresses");
- // Make an initial call to GetAdaptersAddresses to get the
- // size needed into the outBufLen variable
- if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW)
- {
- pAddresses = static_cast<PIP_ADAPTER_ADDRESSES>(HeapAlloc(GetProcessHeap(), 0, outBufLen));
- }
- Dbg("GetAdaptersAddresses 1");
- if (NULL == pAddresses)
- {
- Dbg("pAddresses = NULL");
- return;
- }
- // _ASSERT( pAddresses );
- // Make a second call to GetAdapters Addresses to get the
- // actual data we want
- DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
- Dbg("GetAdaptersAddresses 2");
- /* MACAddresses vAddress;*/
- if (dwRetVal != ERROR_SUCCESS)
- {
- Dbg("dwRetVal = %d", dwRetVal);
- return;
- }
- PIP_ADAPTER_ADDRESSES pFirst = pAddresses;
- while (pAddresses)
- {
- if (pAddresses->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET &&
- pAddresses->OperStatus == IfOperStatusUp &&
- pAddresses->IfType != IF_TYPE_SOFTWARE_LOOPBACK)
- {
- Dbg("in while if 1");
- BYTE* pa = pAddresses->PhysicalAddress;
- if (!pa)
- {
- pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
- continue;
- }
- Dbg("in while if 2");
- char bAddressBytes[MACSESION];
- int bAddressInt[MACSESION];
- memset(bAddressBytes, 0, MACSESION);
- size_t nAddressSize = pAddresses->PhysicalAddressLength;
- memcpy(bAddressBytes, pa, (nAddressSize < MACSESION ? nAddressSize : MACSESION));
- char CommarSeperatedAddress[MACSESION * 3] = { 0 };
- for (int i = 0; i < MACSESION; ++i)
- {
- bAddressInt[i] = bAddressBytes[i];
- bAddressInt[i] &= 0x000000ff; // avoid "ff" leading bytes when "char" is lager then 0x7f
- }
- Dbg("in while if 3");
- sprintf(CommarSeperatedAddress, "%02x:%02x:%02x:%02x:%02x:%02x",
- bAddressInt[0],
- bAddressInt[1],
- bAddressInt[2],
- bAddressInt[3],
- bAddressInt[4],
- bAddressInt[5]); // Should use scl::FormatString inside
- CSimpleStringA tmpmac = CSimpleStringA(CommarSeperatedAddress);
- Dbg("in while if 4");
- macList.Append(&tmpmac, 0, 1);
- // macList.push_back( std::string( CommarSeperatedAddress ) );
- Dbg("Description : %s", pAddresses->Description);
- Dbg("OperStatus : %d, IfType = %d, mac = %s", pAddresses->OperStatus, pAddresses->IfType, CommarSeperatedAddress);
- sockaddr_in *sa_in = (sockaddr_in *)pAddresses->FirstUnicastAddress->Address.lpSockaddr;
- char buf_addr[100] = { 0 };
- CSimpleStringA tmpip = CSimpleStringA(inet_ntop(AF_INET, &(sa_in->sin_addr), buf_addr, 100));
- ipList.Append(&tmpip, 0, 1);
- }
- pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
- }
- HeapFree(GetProcessHeap(), 0, pFirst);
- return;
- #else
- return;//oiltestlinux
- #endif //RVC_OS_WIN
- }
- void CHealthManagerEntity::OnLog(const CAutoArray<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)
- {
- // MessageBoxA(0,0,0,0);
- //if (dwUserCode != LOG_EVT_HEARTBEAT_UN_CONNECTED)
- // Dbg("user code:%x,from entity:%s",dwUserCode,pszEntityName);
- switch (dwUserCode) {
- case EVENT_RESTART_SHELL:
- case Event_Req_Framework_Restart: //case framework restart after upgrade
- case EVENT_CONSOLE_REQ_RESTART_SHELL:
- case Event_Req_Framework_Rollback://case after rollback
- //according to zl commented the following line 20150828
- //case EVENT_UKEY_CUSTOMER_MANANAGER_SYS_EXIT:
- case LOG_EVT_IEBROWSER_RESET_SITE_RESTART: //重设root.ini的site,重启框架
- case LOG_EVT_HEARTBEAT_UN_CONNECTED: //重设site后框架分行服务连接不上,再次重启回退到前一版本
- {
- Dbg("user code:%x,from entity:%s", dwUserCode, pszEntityName);
- int iCheckGuardian = CheckGuardianIsRun();
- if (iCheckGuardian < 0)
- {
- bool bStartGuardian = StartGuardian();
- if (!bStartGuardian)
- {
- Dbg("Before restart frame,start guardian failed.");
- break;
- }
- Dbg("Before restart frame,start guardian suc.");
- Sleep(2000);
- }
- if (dwUserCode == Event_Req_Framework_Restart)
- {
- SaveCurrentVersion();
- SaveFrameStartTimeForUpgrade();
- if (CheckGuardianIsRun(true) > 0)
- {
- if (m_pfUpgradeRestart != NULL)
- {
- ErrorCodeEnum eErr = Error_Unexpect;
- int ret = m_pfUpgradeRestart(1, 0);
- Dbg("to tell guardian framework is restarting.%d", ret);
- }
- }
- m_eRebootTrigger = RebootTrigger_FrameUpgrade;
- }
- else if (dwUserCode == Event_Req_Framework_Rollback)
- {
- Dbg("version rollback succeed.to restart framework");
- m_bVerRollback = false;
- m_eRebootTrigger = RebootTrigger_RollBack;
- }
- else if (dwUserCode == LOG_EVT_IEBROWSER_RESET_SITE_RESTART)
- {
- //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 == LOG_EVT_HEARTBEAT_UN_CONNECTED)
- {
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
- int tmpFlag = 99;
- spConfig->ReadConfigValueInt("AboutSite", "SiteChanged", tmpFlag);
- if (tmpFlag != 1)
- {
- //Dbg("heartbeat can't connect(normal).no need to rollback.");
- break;
- }
- WriteSiteToRootIni();
- UpdateSiteToRuncfg(false, true);
- }
- m_eRebootWay = RebootWay_Framework;
- BOOL bRet = FrameworkShutdown();
- Dbg("framework shutdown [%d]", bRet);
- }
- break;
- case EVENT_CONSOLE_REQ_SHUTDOWN_SHELL:
- {
- BOOL bRet = FrameworkShutdown(false);
- Dbg("framework shutdown 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:
- {
- if (dwUserCode == Event_Req_OS_Restart)
- m_eRebootTrigger = RebootTrigger_OSUpgrade;
- else
- m_eRebootTrigger = RebootTrigger_Unknown;
- m_eRebootWay = RebootWay_Power;
- BOOL bRet = SystemRestart(false,true);
- Dbg("os restart [%d]", bRet);
- }
- break;
- case LOG_EVT_IEBROWSER_RESTART_MACHINE:
- {
- m_eRebootTrigger = RebootTrigger_Unknown;
- m_eRebootWay = RebootWay_Power;
- BOOL bRet = SystemRestart(false, true,true);
- Dbg("machine restart now [%d]", bRet);
- break;
- }
- case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE:
- {
- Dbg("User descktop said to shutdown machine now.");
- SystemShutdown();
- break;
- }
- case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE_THROUGH_UPS:
- {
- Dbg("User descktop said to shutdown machine now through UPS");
- if (Error_Succeed == SystemShutdownThroughUPS()) {
- ///**TODO(Gifur@7/16/2021): 主动跟监护进程做一次握手,避免在关机过程中提前重启了框架 */
- Sleep(300);
- m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_Framework);
- }
- break;
- }
- case LOG_EVT_SELFCHECK_OS_RESTART:
- Dbg("selfcheck to wait chance to restart(os) pc.");
- m_eRebootTrigger = RebootTrigger_RunExcepition;
- m_eRebootWay = RebootWay_Power;
- m_bWaitRestartPC = true;
- break;
- case LOG_EVT_SELFCHECK_POWER_RESTART:
- Dbg("selfcheck to wait chance to restart(power) pc.");
- m_eRebootTrigger = RebootTrigger_RunExcepition;
- m_eRebootWay = RebootWay_Power;
- m_bWaitRestartPC = true;
- break;
- //commented the following 4 event oilyang 20140616
- //case ERROR_MOD_MEDIACONTROLLER_ENVCAMERA_BUG://environment camera error
- //case EVENT_MOD_FACE_ENVCAM_ERROR:
- // Dbg("Environment camera restart");
- // RestartModule("MediaController");
- // break;
- //case ERROR_MOD_MEDIACONTROLLER_OPECAMERA_BUG://operation camera error
- //case EVENT_MOD_FACE_OPECAM_ERROR:
- // Dbg("Operation camera restart");
- // RestartModule("MediaController");
- // break;
- case EVENT_ACCESSAUTH_SUCCEED:
- Dbg("access auth succeed.");
- m_fsm.SetAccessAuth();
- m_bAccessSuc = true;
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = true;
- 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) {
- Dbg("no retry,no restart.");
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = false;
- }else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_NORESTART) {
- Dbg("retry,no restart.");
- m_bNeedAuthRetry = true;
- m_bNeedGuardianRestart = false;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_RESTART) {
- Dbg("retry,restart.");
- m_bNeedAuthRetry = true;
- m_bNeedGuardianRestart = true;
- }
- else if (dwUserCode == CONTROL_ACCESSAUTH_UNKNOWN) {
- Dbg("unkown access failed.no retry,restart.");
- m_bNeedAuthRetry = false;
- m_bNeedGuardianRestart = true;
- }
- m_fsm.SetAccessFailedFlag();
- //oilyang@20210929
- GetFunction()->SetSysVar("TerminalStage", "C");
- Dbg("access auth failed %d.", dwUserCode);
- m_bAccessSuc = false;
- if (m_bNeedAuthRetry)
- {
- Dbg("retry AccessAuth");
- m_fsm.ToReAccessAuth();
- }
- }
- break;
- case EVENT_MOD_INITIALIZER_MK_LOADED:
- Dbg("init succeed.");
- m_fsm.SetInitSucFlag();
- break;
- case EVENT_MOD_INITIALIZER_MK_FAILED:
- Dbg("init failed.");
- m_fsm.SetInitFailFlag();
- break;
- case EVENT_MOD_FACE_OPENCV_ERROR:
- RestartModule("FaceTracking");
- break;
- case LOG_EVT_INC_VERSION_ROLLBACK:
- Dbg("version to be rollback to %s", pszMessage);
- if (!m_bVerRollback)
- {
- Dbg("rollbacking");
- VersionRollBack(pszMessage);
- }
- break;
- case LOG_EVT_SELFCHECK_TOKEN_KEEPER_LOST:
- {
- ErrorCodeEnum eErr = RestartModule("TokenKeeper");
- Dbg("to re accessauth");
- m_fsm.ToReAccessAuth();
- }
- break;
- case EVENT_UKEY_CUSTOMER_MANANAGER_SYS_ENTER:
- {
- Dbg("to enter customer manager system.");
- m_fsm.SetCustomerMngerState(CM_ENTER);//set enter state
- FSMEvent *pEvt = new FSMEvent(USER_EVT_ENTER_CUSTOMER_MANAGER);
- m_fsm.PostEventFIFO(pEvt);
- }
- break;
- case LOG_EVT_HEARTBEAT_CONNECTED:
- UpdateSiteToRuncfg(true, true);
- break;
- case EVENT_MOD_CENTERSETTING_RVCWEBVER_CHANGE:
- m_bNeedToRestartIE = true;
- break;
- //case EVENT_UKEY_NOT_ENTER_CUSTOMER_MANANAGER:
- // {
- // Dbg("NOT to enter customer manager system.");
- // m_fsm.SetCustomerMngerState(CM_NOT_ENTER);//set enter state
- // }
- // break;
- case EVENT_MOD_RELEASESIP_TIMEOUT:
- Dbg("RELEASESIP_TIMEOUT.");
- RestartModule("SIPPhone");
- break;
- case LOG_EVT_SELFCHECK_IEBROWSER_IDLE:
- //IE重启之后,重置是否进入主页变量
- Dbg("Browser(IE/Chromuim) to idle.");
- LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_Receive_Browser_Idle
- , "Browser(IE/Chromuim) to idle.");
- m_bBrowserIdleFirst = true;
- break;
- case LOG_EVT_INC_TRADE_MANAGER_NORMAL:
- case LOG_EVT_INC_TRADE_MANAGER_ON:
- case LOG_EVT_INC_TRADE_MANAGER_OFF:
- {
- TradeManage tm;
- if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_NORMAL)
- tm.op = 0;
- else if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_ON)
- tm.op = 1;
- else if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_OFF)
- tm.op = 2;
- tm.time = pszMessage;
- Dbg("trademanager:%d,%s",tm.op,(const char*)tm.time);
- SpSendBroadcast(GetFunction(), SP_MSG_OF(TradeManage), SP_MSG_SIG_OF(TradeManage), tm);
- }
- case LOG_EVT_INC_DEVICE_LOCK_ON:
- case LOG_EVT_INC_DEVICE_UNLOCK:
- case LOG_EVT_INC_DEVICE_KICK_OFF:
- {
- TerminalManager tm;
- if (dwUserCode == LOG_EVT_INC_DEVICE_LOCK_ON)
- tm.op = 0;
- else if (dwUserCode == LOG_EVT_INC_DEVICE_UNLOCK)
- {
- if (m_bAccessSuc)
- tm.op = 1;
- else
- tm.op = 99;//oilyang@20170818 according to xingzichen
- }
- else if (dwUserCode == LOG_EVT_INC_DEVICE_KICK_OFF)
- tm.op = 2;
- Dbg("terminal manager:%d", tm.op);
- SpSendBroadcast(GetFunction(), SP_MSG_OF(TerminalManager), SP_MSG_SIG_OF(TerminalManager), tm);
- }
- break;
- case LOG_EVT_SYSTMECUSTOM_START_ACCESSAUTH:
- Dbg("receive md5 ok event.");
- m_fsm.SetMD5OK(1);
- break;
- case LOG_EVT_PINPAD_OPEN_SUC:
- //oilyang@20210421 if have called AccessAuth before,we need to recall AccessAuth
- m_fsm.JudgeIfNeedInitFWB();
- if (m_fsm.QueryHaveAuthEver())
- {
- Dbg("receive pinpad open success event.");
- m_fsm.DeviceReConnect();
- }
- case LOG_EVT_CARDSWIPER_DISCONNECTED:
- //oilyang@20210425 if device disconnected,we need to recall AccessAuth
- //RestartModule("CardSwiper");
- //RestartModule("PinPad");
- if (m_fsm.QueryHaveAuthEver())
- {
- Dbg("receive device disconnected event.");
- m_fsm.DeviceReConnect();
- }
- 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)
- {
- m_bHaveThrowMainPage = true;
- Dbg("the first enter main page from HealthManger started.");
- LogEvent(Severity_Middle, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START
- , "first enter main page from HealthManager started.");
- LogWarn(Severity_Middle, Error_Unexpect,LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START
- , m_sysStaticInfo.InstallVersion.ToString());
- }
- if (m_bBrowserIdleFirst)
- {
- Dbg("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");
- LogWarn(Severity_Middle, Error_Unexpect, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE, m_sysStaticInfo.InstallVersion.ToString());
- spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartTimes", 0);
- Dbg("As have been in main page,reset UpgradeRestartTimes.");
- }
- }
- else
- m_bInMainPage = false;
- }
- }
- void CHealthManagerEntity::OnBroadcastEvent(CUUID SubID, const char *pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer)
- {
- #if defined(RVC_OS_WIN)
- if (_strnicmp(pszEntityName, "CardSwiper", strlen("CardSwiper")) == 0) {
- if (dwMessageSignature == eMsgSig_ConnectStatus) {
- CSimpleStringA tmpDevSN("");
- GetFunction()->GetSysVar("FWBDevSN", tmpDevSN);
- if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2) {
- Dbg("This is fwb device.no need to reconnect here.");
- return;
- }
- CardSwiper::ConnectStatus cs;
- SpBuffer2Object(Buffer, cs);
- if (cs.status == 0) {
- if (m_connectStatus == 1) {
- m_connectStatus = 0;
- }
- } else if (cs.status == 1) {
- if (m_connectStatus == 0) {
- m_connectStatus = 1;
- m_fsm.DeviceReConnect();
- }
- }
- }
- }
- #endif //RVC_OS_WIN
- }
- 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 {
-
- if (m_fConfigMode) {
- result = Error_InvalidState;
- } else {
- CSimpleStringA shellScriptPath;
- GetFunction()->GetPath("Base", shellScriptPath);
- shellScriptPath += SPLIT_SLASH_STR;
- shellScriptPath += "res" SPLIT_SLASH_STR "RunScript" SPLIT_SLASH_STR "startSettings.sh";
- if (!ExistsFileA(shellScriptPath)) {
- tmpResult = Error_NotExist;
- tmpMsg = CSimpleStringA::Format("%s 文件不存在", shellScriptPath.GetData());
- } else {
- char app[MAX_PATH] = { '\0' };
- tk_process_t* process = NULL;
- tk_process_option_t option;
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- sprintf(app, "bash %s", shellScriptPath.GetData());
- option.params = app;
- const int res = process_spawn(&option, &process);
- if (0 == res) {
- FREE(process);
- Dbg("execute {%s} suc", shellScriptPath.GetData());
- tmpMsg = shellScriptPath;
- } else {
- tmpResult = (ErrorCodeEnum)res;
- tmpMsg = CSimpleStringA::Format("执行文件 %s 失败", shellScriptPath.GetData());
- }
- }
- }
- LogWarn(Severity_Middle, Error_Debug, LOG_WARN_HEALTH_GATEWAY_CMD, tmpMsg);
- }
- 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;
- }
- 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.exclusiveMode = true;
- req.type = 0;
- result = pClient->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)
- {
- 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", "HeadOfficeMode", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", 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 strCachePath;
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRunInfoDirPath;
- CSimpleStringA strRunCfgDirPath;
- 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);
- strRunCfgDirPath = strRunInfoDirPath + SPLIT_SLASH_STR + "runcfg";
- 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, "install reset");
- } 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 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);
- bool fHeadOfficeMode(false);
- if (ctx->Req.param1 == 0) { //走分行服务
- CTerminalInfoQuery* pCnn = new CTerminalInfoQuery(this);
- /** 1050 是固定的服务端实体端口 [Gifur@20211013]*/
- const bool ret = pCnn->ConnectServer(serverIP.GetData(), 1050);
- Dbg("Connect finished: %d", ret);
- if (pCnn->IsConnectionOK()) {
- Dbg("Connect OK!");
- TerminalRegistRet info;
- result = pCnn->GetTerminalInfo(terminalNo.GetData(), &info);
- pCnn->Close();
- PrintTerminalRegistInfo(&info);
- if (strlen(info.TerminalNo) == 0) {
- tmpResult = Error_NotExist;
- tmpMsg = "查询终端信息不存在,请检测输入的终端号是否正确";
- } else if (terminalNo.Compare(info.TerminalNo) != 0) {
- tmpResult = Error_MisMatched;
- tmpMsg = CSimpleStringA::Format("查询返回的终端信息不匹配,输入:%s,返回:%s", terminalNo.GetData(), info.TerminalNo);
- } else {
- toRecord = true;
- }
- } else {
- Dbg("Connect Failed!");
- result = Error_ConnectFailed;
- }
- pCnn->DecRefCount();
- pCnn = NULL;
- } else if (ctx->Req.param1 == 1) { //走总行服务
- fHeadOfficeMode = true;
- HttpClientRequestConfig config(serverIP.GetData());
- HttpClientResponseResult result;
- config.SetChildUri(CSimpleStringA(URLPATH_TERMINAL_REGISTER_INFO).Append(terminalNo).GetData());
- RestfulClient client = RestfulClient::getInstance();
- client.Do(config, result);
- if (result.statusCode == HttpStatusCode::OK) {
- struct CommResponseJson : public MicroServices::API::CommResponse {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(success, errorCode, returnCode, errorMsg, message)
- };
- CommResponseJson reponseStatus;
- struct RegistInfoJson : public MicroServices::API::Manage::RegistInfo {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, deviceNo, initIP, machineNo, machineType, machineVersion, sites, terminalNo)
- } terminalRegistInfo;
- Json::Value rawRoot;
- if (GetJsonRootObject(rawRoot, result.content)
- && Json2Object(reponseStatus, rawRoot) && reponseStatus.IsReqBusinessSucc()
- && Json2Object(terminalRegistInfo, rawRoot["data"])) {
- 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());
- };
- 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);
- if (strTerminalType.Compare(terminalRegistInfo.machineType.c_str()) != 0) {
- Dbg("终端类型不匹配!输入为:%s,查询为:%s", strTerminalType.GetData(), terminalRegistInfo.machineType.c_str());
- bMatched = false;
- }
- if (strDeviceSN.Compare(terminalRegistInfo.machineNo.c_str()) != 0) {
- Dbg("设备序列号不匹配!输入为:%s,查询为:%s", strDeviceSN.GetData(), terminalRegistInfo.machineNo.c_str());
- bMatched = false;
- }
- /** 其他信息的校验和应用 [Gifur@2022123]*/
- toRecord = true;
- }
- } else {
- if (reponseStatus.IsPadded() && !reponseStatus.IsReqBusinessSucc()) {
- tmpResult = Error_DataCheck;
- tmpMsg = CSimpleStringA::Format("请求失败:%s", reponseStatus.WhatError().c_str());
- } else {
- tmpResult = Error_DataCheck;
- tmpMsg = CSimpleStringA::Format("解析返回内容失败:%s", result.content.c_str());
- }
- }
- } else {
- tmpResult = Error_ServerNotAvailable;
- if (result.content.length() > 0) {
- 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->WriteConfigValueInt("TerminalDeploy", "HeadOfficeMode", fHeadOfficeMode ? 1 : 0);
- 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!");
- }
- ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath);
- array_header_t* subs = fileutil_get_sub_files_a(strRootCfgPath);
- if (subs) {
- regex_t reg;
- CSimpleStringA machineType(strTerminalType);
- CSimpleStringA rootPattern("root");
- CSimpleStringA pattern = rootPattern + "\\-" + machineType + "\\-" + strVendorName + "\\-[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[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 {
- tmpMsg = "找不到对应的备选配置,请确认选择的机型和设备厂商是否正确";
- tmpResult = Error_InvalidState;
- }
- } while (false);
- ctx->Ans.param2 = serverIP;
-
- }
- } else if(ctx->Req.options == 1){
- //从缓存文件中获取,避免出现依赖
- CSimpleStringA terminalNo;
- CSimpleStringA vendorType;
- CSimpleStringA serverIP;
- bool fHeadOfficeMode(false);
- 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->ReadConfigValueInt("TerminalDeploy", "HeadOfficeMode", nTemp);
- fHeadOfficeMode = (nTemp > 0);
- Dbg("read step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
- } while (false);
- int checkFlag = 0;
- if (terminalNo.IsNullOrEmpty()) checkFlag |= 1;
- if (vendorType.IsNullOrEmpty()) checkFlag |= 2;
- if (serverIP.IsNullOrEmpty()) checkFlag |= 4;
- 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] = fHeadOfficeMode ? 1 : 0;
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = terminalNo;
- ctx->Ans.array2[1] = vendorType;
- ctx->Ans.array2[2] = serverIP;
- }
- } else {
- tmpResult = Error_NotSupport;
- }
- }
- break;
- case DeployStep_FetchCenterSettings:
- {
- const CSimpleStringA& serverIP = ctx->Req.param3;
- const int nPort = ctx->Req.param1;
- const bool headOfficeMode = (ctx->Req.param2 == 1);
- if (serverIP.IsNullOrEmpty() || (!headOfficeMode && nPort <= 0)) {
- result = Error_Param;
- break;
- }
- ErrorCodeEnum ec(Error_Succeed);
- Dbg("to connect centersetting...%s::%d", serverIP.GetData(), nPort);
- 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_Download_Req req = {};
- req.strAddr = serverIP;
- req.nPort = nPort;
- CenterSettingService_Download_Ans ans = {};
- /**TODO(Gifur@10/14/2021): 未知行内还是行外的情况 */
- Dbg("to download...");
- ec = pCenterSettingClient->Download(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() || nPort <= 0) {
- 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 InitializerService_ClientBase(this);
- ec = pClient->Connect();
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("连接初始化模块失败: %s", SpStrError(ec));
- pClient->SafeDelete();
- Dbg("connect to initializer module failed: %s", SpStrError(ec));
- tmpResult = ec;
- } else {
- InitializerService_InitializeNew_Req req = {};
- req.strAuthServer = serverIP;
- req.nAuthPort = nPort;
- req.strUserID = strUsername;
- req.strPassword = strPassword;
- InitializerService_InitializeNew_Ans ans = {};
- Dbg("to initializer...");
- ec = pClient->InitializeNew(req, ans, 60000);
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("初始化请求失败: %s", SpStrError(ec));
- tmpResult = ec;
- Dbg("to initialize 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;
- Dbg("initialize failed: %s", (LPCTSTR)tmpMsg);
- } else {
- Dbg("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->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; //安装时间
- }
- }
- 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();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
- ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
- req.type = 1;
- Dbg("to install...");
- tmpResult = pClient->InstallThirdPartyProgram(req, ans, 60000);
- 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; //安装时间
- }
- }
- 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();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
- ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
- req.mode = 2;
- Dbg("to invoke...");
- tmpResult = pClient->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; //安装时间
- }
- }
- 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();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
- ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
- req.type = 2; //
- Dbg("to install font....");
- tmpResult = pClient->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);
- Dbg("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());
- //int nTemp(0);
- //CSmartPointer<IConfigInfo> pConfig;
- //GetFunction()->OpenConfig(Config_Cache, pConfig);
- //pConfig->ReadConfigValueInt("TerminalDeploy", "HeadOfficeMode", nTemp);
- //SP::Module::Comm::Settings::StoreHeadBranchServicesMode(this, (nTemp > 0));
- Dbg("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);
- }
- 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::IsNotConfigMode(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 != 0 && DeployStep_Finished != stepMode) {
- Dbg("not config from cache: step=%d, status=%d", stepMode, stepStatus);
- return true;
- }
- }
- return false;
- }
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(CHealthManagerEntity)
- SP_END_ENTITY_MAP()
|