12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650 |
- // mod_healthmanager.cpp : Defines the exported functions for the DLL application.
- #include "stdafx.h"
- #if defined(RVC_OS_WIN)
- #include <TlHelp32.h>
- #include <iphlpapi.h>
- #include <ws2tcpip.h>
- #include <Winsock2.h>
- #include <Windows.h>
- #else
- #include <sys/wait.h>
- #include <unistd.h>
- #include <time.h>
- #include <signal.h>
- #include <dlfcn.h>
- #include <fcntl.h>
- #include <sys/reboot.h>
- #endif //RVC_OS_WIN
- #include <vector>
- #include <iostream>
- #include <fstream>
- #include <regex.h>
- #include "toolkit.h"
- #include "array.h"
- #include "fileutil.h"
- #include "iniutil.h"
- #include "osutil.h"
- #include "EntityBootStruct.h"
- #include "RestfulFunc.h"
- #include "api_manage_list.h"
- #include "api_manufacture_controller.h"
- #include "JsonConvertHelper.hpp"
- using namespace std;
- #include "mod_healthmanager.h"
- #include "CommEntityUtil.hpp"
- #include "CommEntitySettings.hpp"
- #include "GetDevInfoHelper.h"
- #include "TerminalInfoQueryConn.h"
- #if defined(RVC_OS_WIN)
- #pragma comment( lib, "advapi32.lib" )
- //the following 20151009
- #pragma comment(lib, "IPHLPAPI.lib")
- #endif //RVC_OS_WIN
- const DWORD HEALTHMANAGER_TIMER_ID = 1;
- const DWORD HEALTHMANAGER_WD_TIMER_ID = 2;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL = 60000;
- const DWORD HEALTHMANAGER_WD_TIMER_INTERVAL = 50000;
- const DWORD HEALTHMANAGER_TIMER_INTERVAL_MINUTE = (HEALTHMANAGER_TIMER_INTERVAL/60000)*3;
- #define WORKING_BUFFER_SIZE 15000
- #define MAX_TRIES 3
- #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
- #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
- #include "CenterSetting_client_g.h"
- using namespace CenterSetting;
- #include "Initializer_client_g.h"
- using namespace Initializer;
- //for defines in header file
- #include "CameraConfigManage_def_g.h"
- using namespace CameraConfigManage;
- #include "Chromium_client_g.h"
- using namespace Chromium;
- #include "ResourceWatcher_client_g.h"
- using namespace ResourceWatcher;
- template<class T>
- class TimerOutHelper : public ITimerListener
- {
- public:
- typedef void (T::*FuncTimer)();
- TimerOutHelper(T *p, FuncTimer pTimerFunc, bool bDeleteSelf = false)
- : m_pObject(p), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf) {}
- virtual void OnTimeout(DWORD dwTimerID)
- {
- (m_pObject->*m_pTimer)();
- if (m_bDeleteSelf)
- delete this;
- }
- private:
- T *m_pObject;
- FuncTimer m_pTimer;
- bool m_bDeleteSelf;
- };
- static void PrintTerminalRegistInfo(const TerminalRegistRet* info)
- {
- Dbg("TerminalNo: %s", info->TerminalNo);
- Dbg("DeviceNo: %s", info->DeviceNo);
- Dbg("OutletNo: %s", info->OutletNo);
- Dbg("Initializer: %s", info->Initializer);
- Dbg("PadDeviceID: %s", info->PadDeviceID);
- Dbg("MachineType: %s", info->MachineType);
- Dbg("MachineVersion: %s", info->MachineVersion);
- Dbg("Sites: %s", info->Sites);
- Dbg("EnrolAddr: %s", info->EnrolAddr);
- Dbg("Editor: %s", info->Editor);
- Dbg("State: %c", info->State);
- Dbg("PublicKey: %s", info->PublicKey);
- Dbg("FingerPrint: %s", info->FingerPrint);
- }
- void HealthManagerSession::Handle_EnterState(SpReqAnsContext<HealthManagerService_EnterState_Req, HealthManagerService_EnterState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->EnterState(ctx);
- }
- void HealthManagerSession::Handle_ExitState(SpReqAnsContext<HealthManagerService_ExitState_Req, HealthManagerService_ExitState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ExitState(ctx);
- }
- void HealthManagerSession::Handle_DoEvent(SpReqAnsContext<HealthManagerService_DoEvent_Req, HealthManagerService_DoEvent_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->DoEvent(ctx);
- }
- void HealthManagerSession::Handle_GetEntityCfgInfo(SpReqAnsContext<HealthManagerService_GetEntityCfgInfo_Req, HealthManagerService_GetEntityCfgInfo_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetEntityCfgInfo(ctx);
- }
- void HealthManagerSession::Handle_GetNetworkState(SpReqAnsContext<HealthManagerService_GetNetworkState_Req, HealthManagerService_GetNetworkState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetNetworkState(ctx);
- }
- void HealthManagerSession::Handle_QueryHardwareInfo(SpReqAnsContext<HealthManagerService_QueryHardwareInfo_Req, HealthManagerService_QueryHardwareInfo_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->QueryHardwareInfo(ctx);
- }
- void HealthManagerSession::Handle_ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- }
- void HealthManagerSession::Handle_ControlTerminalLife(
- SpReqAnsContext<HealthManagerService_ControlTerminalLife_Req, HealthManagerService_ControlTerminalLife_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ControlTerminalLife(ctx);
- }
- void HealthManagerSession::Handle_DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->DeployTerminal(ctx);
- }
- void HealthManagerSession::Handle_ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ControlEntityLife(ctx);
- }
- void HealthManagerSession::Handle_Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->Gateway(ctx);
- }
- //通过当前实施步骤判断当前为第几次的临时重启
- static inline int GetDeployStepFromStatus(int status)
- {
- int result(-1);
- switch (status) {
- case DeployStep_Begin:
- case DeployStep_3rdParty_FontInstall:
- case DeployStep_3rdParty_SogouInstall:
- case DeployStep_GetTerminalInfo:
- result = 0;
- break;
- case DeployStep_AdapterConfig:
- result = 1;
- break;
- case DeployStep_MediaConfig:
- case DeployStep_FetchCenterSettings:
- case DeployStep_AccessAuthorize:
- result = 2;
- break;
- default:
- result = 0;
- break;
- }
- return result;
- }
- /**
- TerminalStage
- A: 准入通过?
- C: 准入不通过?
- D:设备故障
- B:
- N:
- U:
- */
- void CHealthManagerEntity::OnStarted()
- {
- ErrorCodeEnum result(Error_NotInit);
- int curStep(0);
- m_fConfigMode = IsNotConfigMode(curStep);
- if (m_fConfigMode) {
- //kill guardin process if exists
- char* relates[] = { "guardian" };
- alive_process_info processes[1];
- memset(processes, 0, sizeof(processes));
- int count = 1;
- osutil_detect_unique_app(relates, array_size(relates), &count, processes);
- if (count > 0) {
- Dbg("to kill guardian process which is seem alive.");
- osutil_terminate_related_process(relates, array_size(relates));
- }
- if (curStep >= 0) {
- Dbg("Change Framework status to NotConfig");
- this->GetFunction()->GetPrivilegeFunction()->RefreshFrameworkState(FrameworkState_NotConfig);
- }
- //挑一个状态判断为配置模式,以此操作其他实体的逻辑,比如:
- //集中配置实体不因无集中配置文件进行弹窗报错
- //初始化实体不会自行进行准入验证
- CSimpleStringA strSysValue = CSimpleStringA::Format("Z=%d", curStep);
- result = GetFunction()->SetSysVar("TerminalStage", strSysValue);
- Dbg("update TerminalStage=%s return %s", strSysValue.GetData(), SpStrError(result));
- /** 安装的时候是否需要延迟,毕竟涉及到重启 [Gifur@202231]*/
- m_fsm.WaitALittleIfNecessary();
-
- 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);
- }
- }
- 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();
- 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::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, const linkContext& pLinkInfo)
- {
- // 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后框架分行服务连接不上,再次重启回退到前一版本
- case Event_Req_Framework_No_Upgrade_Restart://升级请求重启框架(体系外升级等等)
- {
- 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);
- }
- else if (dwUserCode == Event_Req_Framework_No_Upgrade_Restart)
- {
- Dbg("Event_Req_Framework_No_Upgrade_Restart.");
- }
- 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_Resource;
- m_eRebootWay = RebootWay_Power;
- BOOL bRet = SystemRestart(false,true);
- Dbg("os restart [%d]", bRet);
- }
- break;
- case LOG_EVT_IEBROWSER_RESTART_MACHINE:
- {
- m_eRebootTrigger = RebootTrigger_Resource;
- 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;
- 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_Low, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START
- , "first enter main page from HealthManager started.");
- CSmartPointer<IConfigInfo> spConfigShell;
- GetFunction()->OpenConfig(Config_Shell, spConfigShell);
- CSimpleStringA shellVersion(true);
- spConfigShell->ReadConfigValue("Main", "SoftwareVersion", shellVersion);
- LogWarn(Severity_Low, Error_Unexpect,LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START
- , CSimpleStringA::Format("First enter main page from HealthManger started: %s, test: %s",
- m_sysStaticInfo.InstallVersion.ToString().GetData(), shellVersion.GetData()));
- }
- if (m_bBrowserIdleFirst)
- {
- Dbg("the first enter main page from browser started.");
- m_bBrowserIdleFirst = false;
- m_bEnterMainPageEver = true;
- LogEvent(Severity_Low, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE, "enter main page");
- LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE,
- CSimpleStringA::Format("first enter main page from browser started: %s", m_sysStaticInfo.InstallVersion.ToString().GetData()));
- spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartTimes", 0);
- Dbg("As have been in main page,reset UpgradeRestartTimes.");
- }
- }
- else
- m_bInMainPage = false;
- }
- }
- void CHealthManagerEntity::OnBroadcastEvent(CUUID SubID, const char *pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer)
- {
- #if defined(RVC_OS_WIN)
- if (_strnicmp(pszEntityName, "CardSwiper", strlen("CardSwiper")) == 0) {
- if (dwMessageSignature == eMsgSig_ConnectStatus) {
- CSimpleStringA tmpDevSN("");
- GetFunction()->GetSysVar("FWBDevSN", tmpDevSN);
- if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2) {
- Dbg("This is fwb device.no need to reconnect here.");
- return;
- }
- CardSwiper::ConnectStatus cs;
- SpBuffer2Object(Buffer, cs);
- if (cs.status == 0) {
- if (m_connectStatus == 1) {
- m_connectStatus = 0;
- }
- } else if (cs.status == 1) {
- if (m_connectStatus == 0) {
- m_connectStatus = 1;
- m_fsm.DeviceReConnect();
- }
- }
- }
- }
- #endif //RVC_OS_WIN
- }
- void CHealthManagerEntity::ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.devId == 0 && ctx->Req.entityName.IsNullOrEmpty()) {
- result = Error_Param;
- } else {
- if (ctx->Req.entityName.IsNullOrEmpty()) {
- ///**TODO(Gifur@10/22/2021): */
- result = Error_NotImpl;
- } else {
- tmpResult = DealSpecifiedEntity((DealType)ctx->Req.option, ctx->Req.entityName, ctx->Req.param, ctx->Req.force, tmpMsg);
- }
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- }
- void CHealthManagerEntity::Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.type != 1) {
- result = Error_NotSupport;
- } else {
-
- if (m_fConfigMode) {
- result = Error_InvalidState;
- } else {
- CSimpleStringA shellScriptPath;
- GetFunction()->GetPath("Base", shellScriptPath);
- shellScriptPath += SPLIT_SLASH_STR;
- shellScriptPath += "res" SPLIT_SLASH_STR "RunScript" SPLIT_SLASH_STR "startSettings.sh";
- if (!ExistsFileA(shellScriptPath)) {
- tmpResult = Error_NotExist;
- tmpMsg = CSimpleStringA::Format("%s 文件不存在", shellScriptPath.GetData());
- } else {
- char app[MAX_PATH] = { '\0' };
- tk_process_t* process = NULL;
- tk_process_option_t option;
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- sprintf(app, "bash %s", shellScriptPath.GetData());
- option.params = app;
- const int res = process_spawn(&option, &process);
- if (0 == res) {
- FREE(process);
- Dbg("execute {%s} suc", shellScriptPath.GetData());
- tmpMsg = shellScriptPath;
- } else {
- tmpResult = (ErrorCodeEnum)res;
- tmpMsg = CSimpleStringA::Format("执行文件 %s 失败", shellScriptPath.GetData());
- }
- }
- }
- LogWarn(Severity_Middle, Error_Debug, LOG_WARN_HEALTH_GATEWAY_CMD,
- CSimpleStringA::Format("GateWay: %s", tmpMsg.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;
- }
- void CHealthManagerEntity::RecordInstallBeginTimeStamp(const CSimpleString& strTimeStamp, BOOL forceReset)
- {
- if (!forceReset) {
- CSimpleStringA strReserved(true);
- const ErrorCodeEnum rc = GetInstallBeginTimeStamp(strReserved);
- if (!strReserved.IsNullOrEmpty()) {
- return;
- }
- }
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- if (strTimeStamp.IsNullOrEmpty()) {
- pConfig->WriteConfigValue("TerminalDeploy", "StartTimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- } else {
- pConfig->WriteConfigValue("TerminalDeploy", "StartTimeStamp", strTimeStamp);
- }
- }
- ErrorCodeEnum CHealthManagerEntity::GetInstallBeginTimeStamp(CSimpleString& strTimeStamp)
- {
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- CSimpleStringA strValue(true);
- pConfig->ReadConfigValue("TerminalDeploy", "StartTimeStamp", strValue);
- if (strValue.IsNullOrEmpty()) {
- return Error_DataCheck;
- }
- strTimeStamp = strValue;
- return Error_Succeed;
- }
- ErrorCodeEnum CHealthManagerEntity::GetGuidePageUrlWithStep(int whichStep, CSimpleStringA& strUrl)
- {
- strUrl.Clear();
- CSimpleStringA pagePath;
- ErrorCodeEnum ec = GetFunction()->GetPath("Base", pagePath);
- pagePath.Append(SPLIT_SLASH_STR "res" SPLIT_SLASH_STR "ManagerDesktop" SPLIT_SLASH_STR "guide.html");
- if (whichStep > 0) {
- CSimpleStringA terminalNo;
- CSimpleStringA vendorType;
- CSimpleStringA serverIP;
- do {
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- const ErrorCodeEnum ec0 = pConfig->ReadConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
- const ErrorCodeEnum ec1 = pConfig->ReadConfigValue("TerminalDeploy", "Manufacturer", vendorType);
- const ErrorCodeEnum ec2 = pConfig->ReadConfigValue("TerminalDeploy", "ServerIP", serverIP);
- Dbg("read step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
- } while (false);
- pagePath = CSimpleStringA::Format("%s?page=%d", pagePath.GetData(), whichStep);
- bool prefix(true);
- if (!terminalNo.IsNullOrEmpty() || !vendorType.IsNullOrEmpty() || !serverIP.IsNullOrEmpty()) {
- CSimpleStringA strSearch(true);
- if (!terminalNo.IsNullOrEmpty()) {
- if (prefix) strSearch += "&";
- strSearch += CSimpleStringA("terminalno=") + terminalNo;
- prefix = true;
- }
- if (!vendorType.IsNullOrEmpty()) {
- if (prefix) strSearch += "&";
- strSearch += CSimpleStringA("vendor=") + vendorType;
- prefix = true;
- }
- if (!serverIP.IsNullOrEmpty()) {
- if (prefix) strSearch += "&";
- strSearch += CSimpleStringA("ip=") + serverIP;
- prefix = true;
- }
- pagePath += strSearch;
- }
- }
- strUrl = CSimpleStringA("file:///") + pagePath + CSimpleStringA("");
- return ec;
- }
- namespace
- {
- ErrorCodeEnum SplitAdapterFileName(CSimpleStringA strFileName, CAutoArray<CSimpleStringA>& values)
- {
- #ifdef RVC_OS_WIN
- CSimpleStringA strPrefix("");
- CSimpleStringA strSuffix(".dll");
- #else
- CSimpleStringA strPrefix("lib");
- CSimpleStringA strSuffix(".so");
- #endif //RVC_OS_WIN
- if (strFileName.GetLength() < strPrefix.GetLength() + strSuffix.GetLength()) {
- return Error_Param;
- }
- CSimpleStringA pureAdapterName = strFileName.SubString(
- strPrefix.GetLength(), strFileName.GetLength() - strPrefix.GetLength() - strSuffix.GetLength());
- values = pureAdapterName.Split('.');
- if (values.GetCount() != 4) {
- return Error_DataCheck;
- }
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CHealthManagerEntity::TellChromiumOpenGuidePage(const CSimpleStringA& pageUrl)
- {
- ErrorCodeEnum result(Error_Succeed);
- auto pClient = new ChromiumSrv_ClientBase(this);
- result = pClient->Connect();
- if (result == Error_Succeed) {
- ChromiumSrv_OpenBrowser_Req req;
- ChromiumSrv_OpenBrowser_Ans ans;
- req.mainUrl = pageUrl;
- req.viceUrl = "";
- req.exclusiveMode = true;
- req.type = 0;
- result = pClient->OpenBrowser(req, ans, 10000);
- if (result == Error_Succeed) {
- Dbg("Request Chromium::OpenBrowser succ!");
- } else {
- Dbg("Request Chromium::OpenBrowser failed: %s", SpStrError(result));
- }
- pClient->GetFunction()->CloseSession();
- } else {
- pClient->SafeDelete();
- Dbg("Connect to Chromium entity failed: %s", SpStrError(result));
- }
- return result;
- }
- ErrorCodeEnum CHealthManagerEntity::DealSpecifiedEntity(DealType type, LPCTSTR lpcszEntityName, LPCTSTR lpcszCmdline, bool bForce, CSimpleStringA& strErrMsg)
- {
- ErrorCodeEnum result(Error_Succeed);
- strErrMsg.Clear();
- switch (type) {
- case Deal_Start:
- {
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
- CSimpleStringA strEntityName(lpcszEntityName);
- CEntityRunInfo info = {};
- result = GetFunction()->GetEntityRunInfo(strEntityName, info);
- bool toStart(true);
- Dbg("entity: %s, %s,%s", strEntityName.GetData(), SpStrError(result), SpStrEntityState(info.eState));
- if ((info.eState != EntityState_NoStart && info.eState == EntityState_Lost
- && info.eState == EntityState_Close && info.eState == EntityState_UnLoading)
- && (bForce)) {
- }
- if (info.eState != EntityState_NoStart && bForce) {
- Dbg("to terminal entity..");
- CSmartPointer<IAsynWaitSp> spWait;
- result = pFuncPrivilege->StopEntity(strEntityName, spWait);
- Dbg("stop entity return %s", SpStrError(result));
- if (result == Error_Succeed && spWait != NULL) {
- Dbg("to wait after stop...");
- result = spWait->WaitAnswer(60 * 1000);
- Dbg("wait result: %s", SpStrError(result));
- if (result != Error_Succeed) {
- CSmartPointer<IAsynWaitSp> spWait2;
- result = pFuncPrivilege->TerminateEntity(strEntityName, spWait2);
- Dbg("terminal entity return %s", SpStrError(result));
- if (result == Error_Succeed && spWait2 != NULL) {
- Dbg("to wait after terminal...");
- result = spWait2->WaitAnswer(60 * 1000);
- Dbg("wait result: %s", SpStrError(result));
- }
- }
- }
- if (result != Error_Succeed) {
- strErrMsg = CSimpleStringA::Format("重启前停止实体失败 %s, %s", SpStrEntityState(info.eState), SpStrError(result));
- toStart = false;
- }
- } else if (info.eState != EntityState_NoStart) {
- result = Error_InvalidState;
- strErrMsg = CSimpleStringA::Format("实体[%s]当前状态(%s)不支持该操作", strEntityName.GetData(), SpStrEntityState(info.eState));
- toStart = false;
- }
- if (toStart) {
- Dbg("to start entity..");
- CSmartPointer<IAsynWaitSp> spWait;
- result = pFuncPrivilege->StartEntity(strEntityName, lpcszCmdline, spWait);
- Dbg("start entity return %s", SpStrError(result));
- if (result == Error_Succeed && spWait != NULL) {
- Dbg("to wait...");
- result = spWait->WaitAnswer(60 * 1000);
- Dbg("wait result: %s", SpStrError(result));
- }
- if (result != Error_Succeed) {
- strErrMsg = CSimpleStringA::Format("启动实体失败 %s", SpStrError(result));
- }
- }
- }
- break;
- case Deal_Close:
- result = Error_NotImpl;
- break;
- case Deal_Pause:
- result = Error_NotImpl;
- break;
- case Deal_Continue:
- result = Error_NotImpl;
- break;
- case Deal_Kill:
- result = Error_NotImpl;
- break;
- case Deal_Test:
- result = Error_NotImpl;
- break;
- case Deal_Restart:
- result = Error_NotImpl;
- break;
- default:
- result = Error_NotSupport;
- break;
- }
- return result;
- }
- void CHealthManagerEntity::DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- ErrorCodeEnum result(Error_Succeed);
- int tmpResult = 0;
- CSimpleStringA tmpMsg(true);
- Dbg("Cmd: %d", ctx->Req.currStep);
- switch (ctx->Req.currStep) {
- case DeployStep_Begin:
- {
- if (ctx->Req.options == 1) { //重置配置
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- int lastStep(0), stepStatus(0);
- pConfig->ReadConfigValueInt("TerminalDeploy", "CurrStep", lastStep);
- pConfig->ReadConfigValueInt("TerminalDeploy", "CurrState", stepStatus);
- if (lastStep > 0 && (stepStatus == DEPLOYSTATE_NOTINIT)) {
- lastStep--;
- Dbg("draw back to %d", lastStep);
- } else if(lastStep != 0) {
- Dbg("current step: %d", lastStep);
- } else if(!m_fConfigMode) {
- lastStep = DeployStep_Finished;
- Dbg("reset to finished step");
- }
- for (int cur = lastStep; cur > 0; --cur) {
- switch (cur) {
- case DeployStep_GetTerminalInfo:
- {
- Dbg("clear terminalno etc at cache file...");
- pConfig->WriteConfigValue("TerminalDeploy", "TerminalNo", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "Manufacturer", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "HeadOfficeMode", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", NULL);
- pConfig->WriteConfigValue("TerminalDeploy", "LastInfo", NULL);
- }
- break;
- case DeployStep_FetchCenterSettings:
- {
- //清理集中配置文件
- Dbg("clear centersetting files...");
- CSimpleStringA strEntityCfgPath;
- tmpResult = GetFunction()->GetPath("Cfg", strEntityCfgPath);
- array_header_t* subs = fileutil_get_sub_files_a(strEntityCfgPath);
- if (subs) {
- regex_t reg;
- CSimpleStringA pattern = "CenterSetting\.[a-zA-Z0-9_\\(\\)\\-]*\.ini";
- int ret = regcomp(®, pattern, REG_EXTENDED | REG_NOSUB);
- if (ret) {
- char ebuff[256];
- regerror(ret, ®, ebuff, 256);
- Dbg("regex failed: %s", ebuff);
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
- toolkit_array_free2(subs);
- break;
- }
- Dbg("pattern: %s", pattern.GetData());
- for (int i = 0; i < subs->nelts; ++i) {
- char* filenamePath = ARRAY_IDX(subs, i, char*);
- char* filename = &filenamePath[strEntityCfgPath.GetLength() + 1];
- ret = regexec(®, filename, 0, NULL, 0);
- if (0 == ret) {
- Dbg("filename %s matched and remove it.", filename);
- fileutil_delete_file(filenamePath);
- }
- }
- toolkit_array_free2(subs);
- }
- }
- break;
- case DeployStep_AccessAuthorize:
- break;
- case DeployStep_MediaConfig:
- break;
- default:
- break;
- }
- }
- /*读取第一启动的时间戳,有用*/
- CSimpleStringA strBeginTimeReserved(true);
- GetInstallBeginTimeStamp(strBeginTimeReserved);
- CSimpleStringA strCachePath;
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRunInfoDirPath;
- CSimpleStringA strRunCfgDirPath;
- ///**TODO(Gifur@4/21/2022): 既然删除了,前面就没必要清空字段内容了 */
- GetFunction()->GetPath("RunInfo", strRunInfoDirPath);
- strCachePath = strRunInfoDirPath + SPLIT_SLASH_STR + "Global.ini";
- if (ExistsFileA(strCachePath)) {
- Dbg("delete cache file");
- fileutil_delete_file(strCachePath);
- }
- GetFunction()->GetPath("RunCfg", strRunCfgDirPath);
- if (strRunCfgDirPath.IsNullOrEmpty()) {
- strRunCfgDirPath = strRunInfoDirPath + SPLIT_SLASH_STR + "runcfg";
- } else {
- Dbg("Get RunCfg from GetPath directly:%s", strRunCfgDirPath.GetData());
- }
- if (ExistsDirA(strRunCfgDirPath)) {
- Dbg("remove runinfo dir");
- RemoveDirRecursiveA(strRunCfgDirPath);
- }
- CSimpleStringA strBackupFile;
- GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strBackupFile);
- if (ExistsFileA(strRootIniFullPath)) {
- Dbg("delete root.ini");
- fileutil_copy_file(strBackupFile, strRootIniFullPath);
- fileutil_delete_file(strRootIniFullPath);
- }
- LogWarn(Severity_High, Error_Debug, LOG_WARN_HEALTH_INSTALL_RESET, "user requires installation reset!");
- /** 将首次安装的时间写进去*/
- if (!strBeginTimeReserved.IsNullOrEmpty()) {
- RecordInstallBeginTimeStamp(strBeginTimeReserved);
- }
- } else {
- result = Error_NotImpl;
- }
- }
- break;
- case DeployStep_GetTerminalInfo:
- {
- if (ctx->Req.options == 0) {
-
- CAutoArray<CSimpleStringA> arrs = ctx->Req.param4.Split('|');
- const CSimpleStringA& terminalNo = arrs[0];
- //终端类型(行内定义)
- const CSimpleStringA& strTerminalType = arrs[1];
- const CSimpleStringA& serverIP = ctx->Req.param3;
- Dbg("server ip: %s, terminal no: %s, type: %s", serverIP.GetData(), (LPCTSTR)terminalNo, (LPCTSTR)strTerminalType);
- CSimpleStringA strVendorName(true);
- CSimpleStringA strZhCNVendorName(true);
- CSimpleStringA strDeviceModel(true);
- CSimpleStringA strDeviceSN(true);
- if (ctx->Req.array2.GetCount() > 0) {
- //硬件厂商
- strVendorName = ctx->Req.array2[0];
- //硬件设备型号(厂商)
- strDeviceModel = ctx->Req.array2[1];
- //设备序列号
- strDeviceSN = ctx->Req.array2[2];
- Dbg("vendor: %s, model:%s, sn: %s", strVendorName.GetData(), strDeviceModel.GetData(), strDeviceSN.GetData());
- }
- bool toRecord(false);
- bool fHeadOfficeMode(false);
- CSimpleStringA matchInfo(true);
- ///**TODO(Gifur@4/21/2022): 走分行的逻辑后续要移除 */
- if (ctx->Req.param1 == 0) { //走分行服务
- CTerminalInfoQuery* pCnn = new CTerminalInfoQuery(this);
- /** 1050 是固定的服务端实体端口 [Gifur@20211013]*/
- const bool ret = pCnn->ConnectServer(serverIP.GetData(), 1050);
- Dbg("Connect finished: %d", ret);
- if (pCnn->IsConnectionOK()) {
- Dbg("Connect OK!");
- TerminalRegistRet info;
- result = pCnn->GetTerminalInfo(terminalNo.GetData(), &info);
- pCnn->Close();
- PrintTerminalRegistInfo(&info);
- if (strlen(info.TerminalNo) == 0) {
- tmpResult = Error_NotExist;
- tmpMsg = "查询终端信息不存在,请检测输入的终端号是否正确";
- } else if (terminalNo.Compare(info.TerminalNo) != 0) {
- tmpResult = Error_MisMatched;
- tmpMsg = CSimpleStringA::Format("查询返回的终端信息不匹配,输入:%s,返回:%s", terminalNo.GetData(), info.TerminalNo);
- } else {
- toRecord = true;
- }
- } else {
- Dbg("Connect Failed!");
- result = Error_ConnectFailed;
- }
- pCnn->DecRefCount();
- pCnn = NULL;
- } else if (ctx->Req.param1 == 1) { //走总行服务
- fHeadOfficeMode = true;
- HttpClientRequestConfig config(serverIP.GetData());
- HttpClientResponseResult result;
- config.SetChildUri(URLPATH_REGISTER_FULL_LIST);
- config.AppendQuery("terminalNo", terminalNo.GetData());
- RestfulClient client = RestfulClient::getInstance();
- config.PreDo();
- client.Do(&config, &result);
- if (result.ResponseOK()) {
- struct CommResponseJson : public MicroServices::API::CommResponse {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(success, errorCode, returnCode, errorMsg, message)
- };
- CommResponseJson reponseStatus;
- struct RegistInfoJson : public MicroServices::API::Manage::RegistDetailInfo {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, deviceNo, initIP, machineNo, machineType, machineVersion, sites, terminalNo, manufactureID, manufacturerName, deviceTye)
- } terminalRegistInfo;
- Json::Value rawRoot;
- bool testSucc(false);
- do
- {
- if (!GetJsonRootObject(rawRoot, result.content)) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!Json2Object(reponseStatus, rawRoot)) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!reponseStatus.IsOperatedOK()) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!(rawRoot["data"].size() > 0)) {
- Dbg("%d", __LINE__);
- break;
- }
- if (!Json2Object(terminalRegistInfo, rawRoot["data"][0])) {
- Dbg("%d", __LINE__);
- break;
- }
- testSucc = true;
- } while (false);
- if (testSucc) {
- auto printFunc = [&terminalRegistInfo]() {
- Dbg("TerminalNo: %s", terminalRegistInfo.terminalNo.c_str());
- Dbg("BranchNo: %s", terminalRegistInfo.branchNo.c_str());
- Dbg("DeviceNo: %s", terminalRegistInfo.deviceNo.c_str());
- Dbg("IP: %s", terminalRegistInfo.initIP.c_str());
- Dbg("MachineNo: %s", terminalRegistInfo.machineNo.c_str());
- Dbg("MachineType: %s", terminalRegistInfo.machineType.c_str());
- Dbg("MachineVersion: %s", terminalRegistInfo.machineVersion.c_str());
- Dbg("Sites: %s", terminalRegistInfo.sites.c_str());
- Dbg("manufactureID: %s", terminalRegistInfo.manufactureID.c_str());
- Dbg("manufacturerName: %s", terminalRegistInfo.manufacturerName.c_str());
- /** Agent: 终端设备型号*/
- Dbg("deviceTye: %s", terminalRegistInfo.deviceTye.c_str());
- };
-
- printFunc();
- if (!terminalRegistInfo.manufactureID.empty() && terminalRegistInfo.manufacturerName.empty()) {
- CommResponseJson reponseStatus2;
- HttpClientResponseResult result2;
- Json::Value rawRoot2;
- config.SetChildUri(URLPATH_MANUFACTURE_GET_ALL);
- config.ResetQuery();
- config.PreDo();
- client.Do(&config, &result2);
- bool fetchManufactureDone(false);
- if (result2.ResponseOK() && GetJsonRootObject(rawRoot2, result2.content)
- && Json2Object(reponseStatus2, rawRoot2) && reponseStatus2.IsOperatedOK()) {
- struct ManufactureInfoJson : public MicroServices::API::Manufacture::ManufactureInfo {
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(manufacturerId, manufacturerName)
- };
- struct ManufactureList {
- std::vector<ManufactureInfoJson> data;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(data)
- } manufactureList;
- if (Json2Object(manufactureList, rawRoot2)) {
- for (auto it = manufactureList.data.begin(); it != manufactureList.data.end(); ++it) {
- if (it->manufacturerId.compare(terminalRegistInfo.manufactureID) == 0) {
- terminalRegistInfo.manufacturerName = it->manufacturerName;
- Dbg("get manufacturer name: %s", terminalRegistInfo.manufacturerName.c_str());
- fetchManufactureDone = true;
- break;
- }
- }
- }
- }
- if (!fetchManufactureDone) {
- if (reponseStatus2.IsNotEmpty() && !reponseStatus2.IsOperatedOK()) {
- Dbg("请求失败:%s", reponseStatus2.WhatError().c_str());
- } else {
- Dbg("解析返回内容失败:%s", result2.content.c_str());
- }
- }
- }
- printFunc();
- if (terminalRegistInfo.terminalNo.empty()) {
- tmpResult = Error_NotExist;
- tmpMsg = "查询终端信息不存在,请检测输入的终端号是否正确";
- } else if (terminalRegistInfo.terminalNo != terminalNo.GetData()) {
- tmpResult = Error_MisMatched;
- tmpMsg = CSimpleStringA::Format("查询返回的终端信息不匹配,输入:%s,返回:%s"
- , terminalNo.GetData(), terminalRegistInfo.terminalNo.c_str());
- } else {
- bool bMatched(true);
- if (strTerminalType.Compare(terminalRegistInfo.machineType.c_str()) != 0) {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- matchInfo += CSimpleStringA::Format("终端类型不匹配:[%s]vs[%s]", strTerminalType.GetData(), terminalRegistInfo.machineType.c_str());
- bMatched = false;
- }
- //terminalRegistInfo.manufacturerName = "中钞科堡现金处理";
- if (strVendorName.Compare(terminalRegistInfo.manufacturerName.c_str(), true) != 0) {
- do {
- CSmartPointer<IConfigInfo> spCfgConfig;
- GetFunction()->OpenConfig(Config_Software, spCfgConfig);
- spCfgConfig->ReadConfigValue("VendorZhCN", strVendorName, strZhCNVendorName);
- } while (false);
- if (!strZhCNVendorName.IsNullOrEmpty()
- && terminalRegistInfo.manufacturerName.find(strZhCNVendorName.GetData()) != std::string::npos) {
- //let it empty.
- } else {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- if (strZhCNVendorName.IsNullOrEmpty()) {
- matchInfo += CSimpleStringA::Format("设备厂商不匹配:[%s]vs[%s]", strVendorName.GetData(), terminalRegistInfo.manufacturerName.c_str());
- } else {
- matchInfo += CSimpleStringA::Format("设备厂商不匹配:[%s]vs[%s]", strZhCNVendorName.GetData(), terminalRegistInfo.manufacturerName.c_str());
- }
- bMatched = false;
- }
- }
- if (strDeviceModel.Compare(terminalRegistInfo.deviceTye.c_str()) != 0) {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- matchInfo += CSimpleStringA::Format("设备型号不匹配:[%s]vs[%s]", strDeviceModel.GetData(), terminalRegistInfo.deviceTye.c_str());
- bMatched = false;
- }
- /** Agent: 设备编号*/
- if (strDeviceSN.Compare(terminalRegistInfo.machineNo.c_str()) != 0) {
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
- matchInfo += CSimpleStringA::Format("设备序列号(编号)不匹配:[%s]vs[%s]", strDeviceSN.GetData(), terminalRegistInfo.machineNo.c_str());
- bMatched = false;
- }
- /** 其他信息的校验和应用 [Gifur@2022123]*/
- if (!bMatched) {
- tmpResult = Error_DataCheck;
- if (!matchInfo.IsNullOrEmpty()) { matchInfo += "。请核验录入信息是否准确!"; }
- tmpMsg = matchInfo;
- } else {
- toRecord = true;
- }
- }
- } else {
- if (reponseStatus.IsNotEmpty() && !reponseStatus.IsOperatedOK()) {
- tmpResult = Error_DataCheck;
- tmpMsg = CSimpleStringA::Format("请求失败:%s", reponseStatus.WhatError().c_str());
- Dbg(tmpMsg);
- } else {
- tmpResult = Error_DataCheck;
- tmpMsg = CSimpleStringA::Format("解析返回内容失败:%s", result.content.c_str());
- Dbg(tmpMsg);
- Dbg("rawRoot[data].size(): %d", rawRoot["data"].size());
- }
- }
- } else {
- tmpResult = Error_ServerNotAvailable;
- if (!result.content.empty()) {
- tmpMsg = CSimpleStringA::Format("访问 %s 失败:%d,%s", config.GetRequestUri().c_str(), result.statusCode, result.content.c_str());
- } else {
- tmpMsg = CSimpleStringA::Format("访问 %s 失败:%d", config.GetRequestUri().c_str(), result.statusCode);
- }
- }
- }
- if (toRecord) {
- ErrorCodeEnum ec(Error_Succeed);
- do {
- Dbg("record to cache...");
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- const ErrorCodeEnum ec0 = pConfig->WriteConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
- const ErrorCodeEnum ec1 = pConfig->WriteConfigValue("TerminalDeploy", "Manufacturer", strVendorName);
- const ErrorCodeEnum ec2 = pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", serverIP);
- const ErrorCodeEnum ec3 = pConfig->WriteConfigValueInt("TerminalDeploy", "HeadOfficeMode", fHeadOfficeMode ? 1 : 0);
- if (!matchInfo.IsNullOrEmpty()) {
- pConfig->WriteConfigValue("TerminalDeploy", "LastInfo", matchInfo);
- }
- Dbg("record step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2), SpStrError(ec3));
- } while (false);
- do {
- CSimpleStringA strRootCfgPath;
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRootChosenFile(true);
- CSimpleStringA strNousedPath;
- ec = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- ///**TODO(Gifur@10/16/2021): ASSERT 在这个步骤root.ini 文件不应该出现的,可能是字段的缺失才识别为未配置模式 */
- if (ExistsFileA(strRootIniFullPath)) {
- fileutil_copy_file(strNousedPath, strRootIniFullPath);
- fileutil_delete_file(strRootIniFullPath);
- Dbg("root.ini exists!");
- }
- const CSimpleStringA machineType(strTerminalType);
- const CSimpleStringA rootPattern("root");
- const CSimpleStringA pattern = rootPattern + "\\-" + machineType + "\\-" + strVendorName + "\\-[a-zA-Z0-9_\\(\\)\\-]*" + ".ini";
- ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath);
- array_header_t* subs = fileutil_get_sub_files_a(strRootCfgPath);
- if (subs) {
- regex_t reg;
- int ret = regcomp(®, pattern, REG_EXTENDED | REG_NOSUB);
- if (ret) {
- char ebuff[256];
- regerror(ret, ®, ebuff, 256);
- Dbg("regex failed: %s", ebuff);
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
- toolkit_array_free2(subs);
- break;
- }
- Dbg("pattern: %s", pattern.GetData());
- for (int i = 0; i < subs->nelts; ++i) {
- char* filenamePath = ARRAY_IDX(subs, i, char*);
- char* filename = &filenamePath[strRootCfgPath.GetLength() + 1];
- Dbg("filename: %s", filename);
- ret = regexec(®, filename, 0, NULL, 0);
- if (0 == ret) {
- Dbg("matched!");
- strRootChosenFile = filenamePath;
- break;
- }
- Dbg("not matched.");
- }
- toolkit_array_free2(subs);
- }
- if (!strRootChosenFile.IsNullOrEmpty()) {
- ///**TODO(Gifur@1/23/2022): 根据服务器返回的信息填充其他字段内容 */
- fileutil_copy_file(strRootTmpFile, strRootChosenFile);
- inifile_write_str(strRootTmpFile, "Terminal", "TerminalNo", terminalNo);
- //inifile_write_str(strRootTmpFile, "Terminal", "Manufacturer", vendorType);
- if (!strDeviceSN.IsNullOrEmpty()) {
- inifile_write_str(strRootTmpFile, "Terminal", "SN", strDeviceSN);
- }
- } else {
- CSimpleStringA::Format("%s", pattern.GetData());
- tmpMsg = "harewarecfg下匹配不到相应的配置文件,请确认选择的机型和设备厂商是否正确";
- tmpResult = Error_InvalidState;
- }
- } while (false);
- ctx->Ans.param2 = serverIP;
-
- }
- } else if(ctx->Req.options == 1){
- //从缓存文件中获取,避免出现依赖
- CSimpleStringA terminalNo;
- CSimpleStringA vendorType;
- CSimpleStringA serverIP;
- bool fHeadOfficeMode(false);
- do {
- Dbg("read from cache...");
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- int nTemp(0);
- const ErrorCodeEnum ec0 = pConfig->ReadConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
- const ErrorCodeEnum ec1 = pConfig->ReadConfigValue("TerminalDeploy", "Manufacturer", vendorType);
- const ErrorCodeEnum ec2 = pConfig->ReadConfigValue("TerminalDeploy", "ServerIP", serverIP);
- const ErrorCodeEnum ec3 = pConfig->ReadConfigValueInt("TerminalDeploy", "HeadOfficeMode", nTemp);
- fHeadOfficeMode = (nTemp > 0);
- Dbg("read step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
- } while (false);
- int checkFlag = 0;
- if (terminalNo.IsNullOrEmpty()) checkFlag |= 1;
- if (vendorType.IsNullOrEmpty()) checkFlag |= 2;
- if (serverIP.IsNullOrEmpty()) checkFlag |= 4;
- if (checkFlag != 0) {
- tmpResult = Error_Null;
- tmpMsg = CSimpleStringA::Format("获取终端缓存信息失败 Mask=0x%X", checkFlag);
- } else {
- ctx->Ans.array1.Init(3);
- ctx->Ans.array1[0] = ctx->Ans.array1[1] = ctx->Ans.array1[2] = 0;
- ctx->Ans.array1[0] = fHeadOfficeMode ? 1 : 0;
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = terminalNo;
- ctx->Ans.array2[1] = vendorType;
- ctx->Ans.array2[2] = serverIP;
- }
- } else {
- tmpResult = Error_NotSupport;
- }
- }
- break;
- case DeployStep_FetchCenterSettings:
- {
- const CSimpleStringA& serverIP = ctx->Req.param3;
- const int nPort = ctx->Req.param1;
- const bool headOfficeMode = (ctx->Req.param2 == 1);
- if (serverIP.IsNullOrEmpty() || (!headOfficeMode && nPort <= 0)) {
- result = Error_Param;
- break;
- }
- ErrorCodeEnum ec(Error_Succeed);
- Dbg("to connect centersetting...%s::%d", serverIP.GetData(), nPort);
- auto pCenterSettingClient = new CenterSettingService_ClientBase(this);
- ec = pCenterSettingClient->Connect();
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("连接集中配置模块失败: %s", SpStrError(ec));
- pCenterSettingClient->SafeDelete();
- Dbg("connect to centersetting failed: %s", SpStrError(ec));
- } else {
- CenterSettingService_Download_Req req = {};
- req.strAddr = serverIP;
- req.nPort = nPort;
- CenterSettingService_Download_Ans ans = {};
- /**TODO(Gifur@10/14/2021): 未知行内还是行外的情况 */
- Dbg("to download...");
- ec = pCenterSettingClient->Download(req, ans, 60000);
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("下载集中配置文件请求失败: %s", SpStrError(ec));
- Dbg("to download failed: %s", SpStrError(ec));
- }
- pCenterSettingClient->GetFunction()->CloseSession();
- }
- tmpResult = ec;
- ctx->Ans.param2 = serverIP;
- }
- break;
- case DeployStep_AccessAuthorize:
- {
- const CSimpleStringA& serverIP = ctx->Req.param3;
- const int nPort = ctx->Req.param1;
- CSimpleStringA strUsername("admin");
- CSimpleStringA strPassword("88888888");
- if (ctx->Req.array2.GetCount() == 2) {
- strUsername = ctx->Req.array2[0];
- strPassword = ctx->Req.array2[1];
- }
- if (serverIP.IsNullOrEmpty() || nPort <= 0) {
- result = Error_Param;
- break;
- }
- ErrorCodeEnum ec(Error_Succeed);
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- Dbg("to connect initializer...%s::%d", serverIP.GetData(), nPort);
- auto pClient = new InitializerService_ClientBase(this);
- ec = pClient->Connect();
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("连接初始化模块失败: %s", SpStrError(ec));
- pClient->SafeDelete();
- Dbg("connect to initializer module failed: %s", SpStrError(ec));
- tmpResult = ec;
- } else {
- InitializerService_InitializeNew_Req req = {};
- req.strAuthServer = serverIP;
- req.nAuthPort = nPort;
- req.strUserID = strUsername;
- req.strPassword = strPassword;
- InitializerService_InitializeNew_Ans ans = {};
- Dbg("to initializer...");
- ec = pClient->InitializeNew(req, ans, 60000);
- if (ec != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("初始化请求失败: %s", SpStrError(ec));
- tmpResult = ec;
- Dbg("to initialize failed: %s", SpStrError(ec));
- } else {
- const int errUserCode = (int)(ans.Errcode);
- if (errUserCode != 0) {
- if (ans.ErrMsg.IsNullOrEmpty()) {
- tmpMsg = CSimpleStringA::Format("%d", errUserCode);
- } else {
- tmpMsg = CSimpleStringA::Format("%s", ans.ErrMsg.GetData());
- }
- tmpResult = errUserCode;
- Dbg("initialize failed: %s", (LPCTSTR)tmpMsg);
- } else {
- Dbg("initialize succ.");
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- ctx->Ans.param2 = serverIP;
- }
- break;
- case DeployStep_MediaConfig:
- {
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strNousedPath;
- tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- CSimpleStringA strRecordFilePath = (ctx->Req.options == 1) ? strRootIniFullPath : strRootTmpFile;
- if (!ExistsFileA(strRecordFilePath)) {
- Dbg("%s not exists!", strRecordFilePath.GetData());
- tmpMsg = CSimpleStringA::Format("%文件不存在,请重置后重新进行配置!", strRecordFilePath.GetData());
- tmpResult = Error_NotExist;
- } else {
- for (int i = 0; i < ctx->Req.array1.GetCount() && tmpResult == Error_Succeed; ++i) {
- CSimpleStringA key(true), value(ctx->Req.array2[i]);
- const int type = ctx->Req.array1[i];
- Dbg("%d: %s - %d", i, value.GetData(), type);
- switch (type) {
- case MediaDev_OutSpeaker:
- key = "handfree_out_dev";
- break;
- case MediaDev_InSpeaker:
- key = "pickup_out_dev";
- break;
- case MediaDev_OutMicrophone:
- key = "handfree_in_dev";
- break;
- case MediaDev_InMicrophone:
- key = "pickup_in_dev";
- break;
- default:
- tmpResult = Error_Param;
- break;
- }
- if (!key.IsNullOrEmpty()) {
- tmpResult = inifile_write_str(strRecordFilePath, "Audio", key, value);
- Dbg("write %s=%s into root.ini tmp file: %s", key.GetData(), value.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
- } else {
- Dbg("unrecognize: %d, %s", type, value.GetData());
- tmpResult = Error_Unexpect;
- }
- }
- }
- }
- break;
- case DeployStep_AdapterConfig:
- {
- if ((ctx->Req.options & 0x2) || (ctx->Req.options & 0x1)) {
- CSimpleStringA& strAdapterFileName = ctx->Req.param3;
- CAutoArray<CSimpleStringA> adapterInfo;
- tmpResult = SplitAdapterFileName(strAdapterFileName, adapterInfo);
- Dbg("%s, %s", strAdapterFileName.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
- if (tmpResult == 0) {
- CSimpleStringA strDevice(adapterInfo[0]);
- CSimpleStringA strDeviceSection("Device.");
- strDeviceSection += strDevice;
- CSimpleStringA strVendor(adapterInfo[1]);
- CSimpleStringA strVersion(adapterInfo[2]);
- CSimpleStringA strBatch(adapterInfo[3]);
- const int port = ctx->Req.param1;
- const int baudrate = ctx->Req.param2;
- if ((ctx->Req.options & 0x1)) { //更新到缓存
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strNousedPath;
- tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- if (!ExistsFileA(strRootTmpFile)) {
- Dbg("%s not exists!", strRootTmpFile.GetData());
- tmpMsg = "临时配置文件不存在,请重置后重新进行配置!";
- tmpResult = Error_NotExist;
- } else {
- tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Vendor", strVendor);
- tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Version", strVersion);
- tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Batch", strBatch);
- tmpResult = inifile_write_int(strRootTmpFile, strDeviceSection, "Port", port);
- tmpResult = inifile_write_int(strRootTmpFile, strDeviceSection, "Baudrate", baudrate);
- }
- } else { //更新到root.ini
- CSmartPointer<IConfigInfo> pRootConfig;
- GetFunction()->OpenConfig(Config_Root, pRootConfig);
- tmpResult = pRootConfig->WriteConfigValue(strDeviceSection, "Vendor", strVendor);
- Dbg("%s,%s,%s,%s,%s", strDeviceSection.GetData(), strVendor.GetData(), strVersion.GetData(), strBatch.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
- if (tmpResult == 0) {
- pRootConfig->WriteConfigValue(strDeviceSection, "Version", strVersion);
- pRootConfig->WriteConfigValue(strDeviceSection, "Batch", strBatch);
- pRootConfig->WriteConfigValueInt(strDeviceSection, "Port", port);
- pRootConfig->WriteConfigValueInt(strDeviceSection, "Baudrate", baudrate);
- } else {
- tmpMsg = CSimpleStringA::Format("写入ROOT配置文件失败:%s", SpStrError((ErrorCodeEnum)tmpResult));
- }
- }
- } else {
- tmpMsg = CSimpleStringA::Format("适配器文件名称不符合规范:%s", strAdapterFileName.GetData());
- }
- }
- else if ((ctx->Req.options & 0x4)) { //启动实体
- CSimpleStringA& strEntityName = ctx->Req.param3;
- tmpResult = DealSpecifiedEntity((DealType)ctx->Req.param1, strEntityName, ctx->Req.param4, (ctx->Req.param2 != 0), tmpMsg);
- }
- }
- break;
- case DeployStep_3rdParty_SogouInstall:
- {
- if ((ctx->Req.options == 1)) { //检测输入法的安装状态
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
- ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
- req.mode = 1;
- Dbg("to invoke...");
- tmpResult = pClient->GetThirdPartyInstallState(req, ans, 30000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("获取安装状态请求失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- } else {
- ctx->Ans.param1 = 0;
- if (ans.status == 1) {
- ctx->Ans.param1 = 1;
- ctx->Ans.array1.Init(3);
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = ans.version;
- ctx->Ans.array2[1] = ans.path;
- ctx->Ans.array2[2] = ans.reserverd1; //安装时间
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- } else if (ctx->Req.options == 2) { //安装搜狗输入法
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
- ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
- req.type = 1;
- req.reserved1 = req.reserved2 = 0;
- /** 健康实体过来的调用,1表示不直接重启机器 [Gifur@202275]*/
- req.reserved1 = 1;
- Dbg("to install...");
- tmpResult = pClient->InstallThirdPartyProgram(req, ans, 60000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("调用安装请求返回错误:%s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- } else {
- tmpResult = ans.result;
- tmpMsg = ans.msg;
- if (tmpResult == 0) {
- ctx->Ans.array1.Init(3);
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = ans.reserverd1;
- ctx->Ans.array2[1] = ans.path;
- ctx->Ans.array2[2] = ans.reserverd2; //安装时间
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- } else {
- result = Error_NotSupport;
- }
- }
- break;
- case DeployStep_3rdParty_FontInstall:
- {
- if ((ctx->Req.options == 1)) { //检测字体的安装状态
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
- ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
- req.mode = 2;
- Dbg("to invoke...");
- tmpResult = pClient->GetThirdPartyInstallState(req, ans, 30000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("获取安装状态请求失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- } else {
- ctx->Ans.param1 = 0;
- if (ans.status == 1) {
- ctx->Ans.param1 = 1;
- ctx->Ans.array1.Init(3);
- ctx->Ans.array2.Init(3);
- ctx->Ans.array2[0] = ans.version;
- ctx->Ans.array2[1] = ans.path;
- ctx->Ans.array2[2] = ans.reserverd1; //安装时间
- }
- }
- pClient->GetFunction()->CloseSession();
- }
- } else if ((ctx->Req.options == 2)) { //字体的安装
- auto pClient = new ResourceWatcherService_ClientBase(this);
- tmpResult = pClient->Connect();
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
- pClient->SafeDelete();
- Dbg(tmpMsg);
- } else {
- ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
- ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
- req.type = 2; //
- req.reserved1 = req.reserved2 = 0;
- Dbg("to install font....");
- tmpResult = pClient->InstallThirdPartyProgram(req, ans, 60000);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("调用安装请求返回错误:%s", SpStrError((ErrorCodeEnum)tmpResult));
- Dbg(tmpMsg);
- } else {
- tmpResult = ans.result;
- tmpMsg = ans.msg;
- }
- pClient->GetFunction()->CloseSession();
- }
- } else {
- result = Error_NotSupport;
- }
- }
- break;
- case DeployStep_Finished:
- {
- CSimpleStringA strRootTmpFile;
- CSimpleStringA strRootIniFullPath;
- CSimpleStringA strRootChosenFile(true);
- CSimpleStringA strNousedPath;
- GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
- strRootChosenFile = strRootIniFullPath + ".bak";
- if (ExistsFileA(strRootChosenFile)) {
- fileutil_delete_file(strRootChosenFile);
- Dbg("to clear root.ini backup file.");
- }
- CSystemStaticInfo info;
- GetFunction()->GetSystemStaticInfo(info);
- CSmartPointer<IConfigInfo> pConfig;
- GetFunction()->OpenConfig(Config_Cache, pConfig);
- pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", info.InstallVersion.ToString());
- 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()
|