1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355 |
- // 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"
- using namespace std;
- #include "mod_healthmanager.h"
- #include "CommEntityUtil.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());
- } else {
- tmpResult = (ErrorCodeEnum)res;
- tmpMsg = CSimpleStringA::Format("执行文件 %s 失败", shellScriptPath.GetData());
- }
- }
- }
- }
- 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);
- }
- 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) {
- CTerminalInfoQuery* pCnn = new CTerminalInfoQuery(this);
- CAutoArray<CSimpleStringA> arrs = ctx->Req.param4.Split('|');
- const CSimpleStringA& terminalNo = arrs[0];
- const CSimpleStringA& vendorType = arrs[1];
- const CSimpleStringA& serverIP = ctx->Req.param3;
- Dbg("server ip: %s, terminal no: %s, vendor: %s", serverIP.GetData(), (LPCTSTR)terminalNo, (LPCTSTR)vendorType);
- 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());
- }
- /** 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 {
- 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", vendorType);
- const ErrorCodeEnum ec2 = pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", serverIP);
- Dbg("record step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
- } 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("Stand2S");
- CSimpleStringA rootPattern("root");
- CSimpleStringA pattern = rootPattern + "\\-" + machineType + "\\-" + vendorType + "\\-[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()) {
- 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 {
- Dbg("Connect Failed!");
- result = Error_ConnectFailed;
- }
- pCnn->DecRefCount();
- pCnn = NULL;
- } else if(ctx->Req.options == 1){
- //从缓存文件中获取,避免出现依赖
- CSimpleStringA terminalNo;
- CSimpleStringA vendorType;
- CSimpleStringA serverIP;
- do {
- Dbg("read from cache...");
- 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);
- 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.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;
- if (serverIP.IsNullOrEmpty() || 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, 10000);
- 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, 10000);
- 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, 10000);
- 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, 10000);
- 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, 10000);
- 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.");
- }
- 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()
|