mod_healthmanager.cpp 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650
  1. // mod_healthmanager.cpp : Defines the exported functions for the DLL application.
  2. #include "stdafx.h"
  3. #if defined(RVC_OS_WIN)
  4. #include <TlHelp32.h>
  5. #include <iphlpapi.h>
  6. #include <ws2tcpip.h>
  7. #include <Winsock2.h>
  8. #include <Windows.h>
  9. #else
  10. #include <sys/wait.h>
  11. #include <unistd.h>
  12. #include <time.h>
  13. #include <signal.h>
  14. #include <dlfcn.h>
  15. #include <fcntl.h>
  16. #include <sys/reboot.h>
  17. #endif //RVC_OS_WIN
  18. #include <vector>
  19. #include <iostream>
  20. #include <fstream>
  21. #include <regex.h>
  22. #include "toolkit.h"
  23. #include "array.h"
  24. #include "fileutil.h"
  25. #include "iniutil.h"
  26. #include "osutil.h"
  27. #include "EntityBootStruct.h"
  28. #include "RestfulFunc.h"
  29. #include "api_manage_list.h"
  30. #include "api_manufacture_controller.h"
  31. #include "JsonConvertHelper.hpp"
  32. using namespace std;
  33. #include "mod_healthmanager.h"
  34. #include "CommEntityUtil.hpp"
  35. #include "CommEntitySettings.hpp"
  36. #include "GetDevInfoHelper.h"
  37. #include "TerminalInfoQueryConn.h"
  38. #if defined(RVC_OS_WIN)
  39. #pragma comment( lib, "advapi32.lib" )
  40. //the following 20151009
  41. #pragma comment(lib, "IPHLPAPI.lib")
  42. #endif //RVC_OS_WIN
  43. const DWORD HEALTHMANAGER_TIMER_ID = 1;
  44. const DWORD HEALTHMANAGER_WD_TIMER_ID = 2;
  45. const DWORD HEALTHMANAGER_TIMER_INTERVAL = 60000;
  46. const DWORD HEALTHMANAGER_WD_TIMER_INTERVAL = 50000;
  47. const DWORD HEALTHMANAGER_TIMER_INTERVAL_MINUTE = (HEALTHMANAGER_TIMER_INTERVAL/60000)*3;
  48. #define WORKING_BUFFER_SIZE 15000
  49. #define MAX_TRIES 3
  50. #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
  51. #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
  52. #include "CenterSetting_client_g.h"
  53. using namespace CenterSetting;
  54. #include "Initializer_client_g.h"
  55. using namespace Initializer;
  56. //for defines in header file
  57. #include "CameraConfigManage_def_g.h"
  58. using namespace CameraConfigManage;
  59. #include "Chromium_client_g.h"
  60. using namespace Chromium;
  61. #include "ResourceWatcher_client_g.h"
  62. using namespace ResourceWatcher;
  63. template<class T>
  64. class TimerOutHelper : public ITimerListener
  65. {
  66. public:
  67. typedef void (T::*FuncTimer)();
  68. TimerOutHelper(T *p, FuncTimer pTimerFunc, bool bDeleteSelf = false)
  69. : m_pObject(p), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf) {}
  70. virtual void OnTimeout(DWORD dwTimerID)
  71. {
  72. (m_pObject->*m_pTimer)();
  73. if (m_bDeleteSelf)
  74. delete this;
  75. }
  76. private:
  77. T *m_pObject;
  78. FuncTimer m_pTimer;
  79. bool m_bDeleteSelf;
  80. };
  81. static void PrintTerminalRegistInfo(const TerminalRegistRet* info)
  82. {
  83. Dbg("TerminalNo: %s", info->TerminalNo);
  84. Dbg("DeviceNo: %s", info->DeviceNo);
  85. Dbg("OutletNo: %s", info->OutletNo);
  86. Dbg("Initializer: %s", info->Initializer);
  87. Dbg("PadDeviceID: %s", info->PadDeviceID);
  88. Dbg("MachineType: %s", info->MachineType);
  89. Dbg("MachineVersion: %s", info->MachineVersion);
  90. Dbg("Sites: %s", info->Sites);
  91. Dbg("EnrolAddr: %s", info->EnrolAddr);
  92. Dbg("Editor: %s", info->Editor);
  93. Dbg("State: %c", info->State);
  94. Dbg("PublicKey: %s", info->PublicKey);
  95. Dbg("FingerPrint: %s", info->FingerPrint);
  96. }
  97. void HealthManagerSession::Handle_EnterState(SpReqAnsContext<HealthManagerService_EnterState_Req, HealthManagerService_EnterState_Ans>::Pointer ctx)
  98. {
  99. LOG_FUNCTION();
  100. m_pEntity->EnterState(ctx);
  101. }
  102. void HealthManagerSession::Handle_ExitState(SpReqAnsContext<HealthManagerService_ExitState_Req, HealthManagerService_ExitState_Ans>::Pointer ctx)
  103. {
  104. LOG_FUNCTION();
  105. m_pEntity->ExitState(ctx);
  106. }
  107. void HealthManagerSession::Handle_DoEvent(SpReqAnsContext<HealthManagerService_DoEvent_Req, HealthManagerService_DoEvent_Ans>::Pointer ctx)
  108. {
  109. LOG_FUNCTION();
  110. m_pEntity->DoEvent(ctx);
  111. }
  112. void HealthManagerSession::Handle_GetEntityCfgInfo(SpReqAnsContext<HealthManagerService_GetEntityCfgInfo_Req, HealthManagerService_GetEntityCfgInfo_Ans>::Pointer ctx)
  113. {
  114. LOG_FUNCTION();
  115. m_pEntity->GetEntityCfgInfo(ctx);
  116. }
  117. void HealthManagerSession::Handle_GetNetworkState(SpReqAnsContext<HealthManagerService_GetNetworkState_Req, HealthManagerService_GetNetworkState_Ans>::Pointer ctx)
  118. {
  119. LOG_FUNCTION();
  120. m_pEntity->GetNetworkState(ctx);
  121. }
  122. void HealthManagerSession::Handle_QueryHardwareInfo(SpReqAnsContext<HealthManagerService_QueryHardwareInfo_Req, HealthManagerService_QueryHardwareInfo_Ans>::Pointer ctx)
  123. {
  124. LOG_FUNCTION();
  125. m_pEntity->QueryHardwareInfo(ctx);
  126. }
  127. void HealthManagerSession::Handle_ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
  128. {
  129. LOG_FUNCTION();
  130. }
  131. void HealthManagerSession::Handle_ControlTerminalLife(
  132. SpReqAnsContext<HealthManagerService_ControlTerminalLife_Req, HealthManagerService_ControlTerminalLife_Ans>::Pointer ctx)
  133. {
  134. LOG_FUNCTION();
  135. m_pEntity->ControlTerminalLife(ctx);
  136. }
  137. void HealthManagerSession::Handle_DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
  138. {
  139. LOG_FUNCTION();
  140. m_pEntity->DeployTerminal(ctx);
  141. }
  142. void HealthManagerSession::Handle_ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
  143. {
  144. LOG_FUNCTION();
  145. m_pEntity->ControlEntityLife(ctx);
  146. }
  147. void HealthManagerSession::Handle_Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
  148. {
  149. LOG_FUNCTION();
  150. m_pEntity->Gateway(ctx);
  151. }
  152. //通过当前实施步骤判断当前为第几次的临时重启
  153. static inline int GetDeployStepFromStatus(int status)
  154. {
  155. int result(-1);
  156. switch (status) {
  157. case DeployStep_Begin:
  158. case DeployStep_3rdParty_FontInstall:
  159. case DeployStep_3rdParty_SogouInstall:
  160. case DeployStep_GetTerminalInfo:
  161. result = 0;
  162. break;
  163. case DeployStep_AdapterConfig:
  164. result = 1;
  165. break;
  166. case DeployStep_MediaConfig:
  167. case DeployStep_FetchCenterSettings:
  168. case DeployStep_AccessAuthorize:
  169. result = 2;
  170. break;
  171. default:
  172. result = 0;
  173. break;
  174. }
  175. return result;
  176. }
  177. /**
  178. TerminalStage
  179. A: 准入通过?
  180. C: 准入不通过?
  181. D:设备故障
  182. B:
  183. N:
  184. U:
  185. */
  186. void CHealthManagerEntity::OnStarted()
  187. {
  188. ErrorCodeEnum result(Error_NotInit);
  189. int curStep(0);
  190. m_fConfigMode = IsNotConfigMode(curStep);
  191. if (m_fConfigMode) {
  192. //kill guardin process if exists
  193. char* relates[] = { "guardian" };
  194. alive_process_info processes[1];
  195. memset(processes, 0, sizeof(processes));
  196. int count = 1;
  197. osutil_detect_unique_app(relates, array_size(relates), &count, processes);
  198. if (count > 0) {
  199. Dbg("to kill guardian process which is seem alive.");
  200. osutil_terminate_related_process(relates, array_size(relates));
  201. }
  202. if (curStep >= 0) {
  203. Dbg("Change Framework status to NotConfig");
  204. this->GetFunction()->GetPrivilegeFunction()->RefreshFrameworkState(FrameworkState_NotConfig);
  205. }
  206. //挑一个状态判断为配置模式,以此操作其他实体的逻辑,比如:
  207. //集中配置实体不因无集中配置文件进行弹窗报错
  208. //初始化实体不会自行进行准入验证
  209. CSimpleStringA strSysValue = CSimpleStringA::Format("Z=%d", curStep);
  210. result = GetFunction()->SetSysVar("TerminalStage", strSysValue);
  211. Dbg("update TerminalStage=%s return %s", strSysValue.GetData(), SpStrError(result));
  212. /** 安装的时候是否需要延迟,毕竟涉及到重启 [Gifur@202231]*/
  213. m_fsm.WaitALittleIfNecessary();
  214. CSimpleStringA machineType = SP::Module::Comm::GetCurrMachineType(this);
  215. CSimpleStringA configPath = SP::Module::Comm::GetCurrEntityConfigPath(this);
  216. const int stepCount = GetDeployStepFromStatus(curStep);
  217. for (int i = stepCount, j=0; i >= 0; --i, j++) {
  218. switch (j) {
  219. case 0:
  220. {
  221. Dbg("Initial Boot Step.");
  222. std::shared_ptr<TerminalDeployStep> step = std::make_shared<TerminalDeployStep>("");
  223. step->LoadConfig(configPath);
  224. result = step->StartStartupEntities(this);
  225. if (result != Error_Succeed) {
  226. LogError(Severity_Middle, result, 0, CSimpleStringA::Format("Initial Boot Step failed: %s", SpStrError(result)));
  227. return;
  228. }
  229. }
  230. break;
  231. case 1:
  232. {
  233. Dbg("Second Boot Step.");
  234. LOG_ASSERT(!machineType.IsNullOrEmpty());
  235. std::shared_ptr<TerminalDeploySecondStep> step(nullptr);
  236. step = std::make_shared<TerminalDeploySecondStep>(machineType);
  237. step->LoadConfig(configPath);
  238. result = step->StartStartupEntities(this);
  239. if (result != Error_Succeed) {
  240. LogError(Severity_Middle, result, 0, CSimpleStringA::Format("Second Boot Step failed: %s", SpStrError(result)));
  241. return;
  242. }
  243. }
  244. break;
  245. case 2:
  246. {
  247. Dbg("Third Boot Step.");
  248. LOG_ASSERT(!machineType.IsNullOrEmpty());
  249. std::shared_ptr<TerminalDeployThirdStep> step(nullptr);
  250. step = std::make_shared<TerminalDeployThirdStep>(machineType);
  251. step->LoadConfig(configPath);
  252. result = step->StartStartupEntities(this);
  253. if (result != Error_Succeed) {
  254. LogError(Severity_Middle, result, 0, CSimpleStringA::Format("Third Boot Step failed: %s", SpStrError(result)));
  255. return;
  256. }
  257. }
  258. break;
  259. default:
  260. break;
  261. }
  262. }
  263. CSimpleStringA strUrl;
  264. result = GetGuidePageUrlWithStep(curStep, strUrl);
  265. Dbg("Url:{%s}", (LPCTSTR)strUrl);
  266. result = TellChromiumOpenGuidePage(strUrl);
  267. }
  268. }
  269. bool CHealthManagerEntity::DoWatchDog(WatchDogOp eOp)
  270. {
  271. switch(eOp)
  272. {
  273. case WD_OP_START:
  274. {
  275. if (m_pWatchDogClient == NULL)
  276. {
  277. m_pWatchDogClient = new WatchDogService_ClientBase(this);
  278. ErrorCodeEnum eErrConn = m_pWatchDogClient->Connect();
  279. if (eErrConn != Error_Succeed) {
  280. Dbg("WatchDog connected failed.");
  281. m_pWatchDogClient->SafeDelete();
  282. m_pWatchDogClient = NULL;
  283. break;
  284. }
  285. else
  286. Dbg("WatchDog connected.");
  287. }
  288. WatchDogService_StartWatch_Req req;
  289. req.Delay = 120;//oiltmp
  290. req.Timeout = 60;
  291. WatchDogService_StartWatch_Ans ans;
  292. ErrorCodeEnum eErrStart = m_pWatchDogClient->StartWatch(req,ans,10000);
  293. if (eErrStart == Error_Succeed)
  294. m_bWatchDog = true;
  295. Dbg("start watch %d.",eErrStart);
  296. }
  297. break;
  298. case WD_OP_STOP:
  299. {
  300. if (!m_bWatchDog)
  301. break;
  302. WatchDogService_StopWatch_Req req;
  303. WatchDogService_StopWatch_Ans ans;
  304. ErrorCodeEnum eErrStop = m_pWatchDogClient->StopWatch(req,ans,10000);
  305. if (eErrStop == Error_Succeed)
  306. m_bWatchDog = false;
  307. Dbg("stop watchd %d.",eErrStop);
  308. }
  309. break;
  310. case WD_OP_REFRESH:
  311. {
  312. if (!m_bWatchDog)
  313. break;
  314. WatchDogService_Refresh_Req req;
  315. WatchDogService_Refresh_Ans ans;
  316. ErrorCodeEnum eErrRefresh = m_pWatchDogClient->Refresh(req,ans,10000);
  317. Dbg("refresh watchdog %d.",eErrRefresh);
  318. }
  319. break;
  320. default:
  321. break;
  322. }
  323. return true;
  324. }
  325. void CHealthManagerEntity::OnWatchDogTimeout()
  326. {
  327. xxx++;
  328. if (m_bWatchDog && xxx == 5)
  329. {
  330. DoWatchDog(WD_OP_STOP);
  331. //oiltmp
  332. Sleep(180000);
  333. Dbg("have sleep 18000,wake up.");
  334. //DoWatchDog(WD_OP_START);
  335. }
  336. else if (m_bWatchDog && xxx<5)
  337. {
  338. DoWatchDog(WD_OP_REFRESH);
  339. GetFunction()->ResetTimer(HEALTHMANAGER_WD_TIMER_ID, HEALTHMANAGER_WD_TIMER_INTERVAL);
  340. }
  341. }
  342. int CHealthManagerEntity::SystemRestart(bool bPeriod, bool bImmediately,bool bNow)
  343. {
  344. if (bPeriod)
  345. {
  346. Dbg("restart periodly.");
  347. m_restartTimes = 0;
  348. }
  349. if (bNow)
  350. {
  351. m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
  352. int x = SystemShutdown(TRUE);
  353. Dbg("From ie to shutdown %d",x);
  354. return 0;
  355. }
  356. SYSTEMTIME localTime;
  357. GetLocalTimeRVC(localTime);
  358. CSmartPointer<IConfigInfo> spConfigRun;
  359. ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Run, spConfigRun);
  360. if (err != Error_Succeed) {
  361. LOG_TRACE("open cfg file failed!");
  362. return -1;
  363. }
  364. //
  365. //ups restart
  366. if (m_pUpsClient != NULL)
  367. {
  368. if (!m_bToRestart)
  369. {
  370. m_restartTimes++;
  371. if (m_restartTimes > m_maxRestartTimes)
  372. {
  373. Dbg("restart too many times(%d,%d),give up.",m_restartTimes,m_maxRestartTimes);
  374. m_restartTimes--;
  375. return -1;
  376. }
  377. Dbg("the %d restart.",m_restartTimes);
  378. spConfigRun->WriteConfigValueInt("Run","RestartTimes",m_restartTimes);
  379. if (m_lastHour != localTime.wHour)
  380. {
  381. m_lastHour = localTime.wHour;
  382. Dbg("set last hour to %d", m_lastHour);
  383. spConfigRun->WriteConfigValueInt("Run", "LastHour", m_lastHour);
  384. }
  385. }
  386. else
  387. return 0;
  388. UpsService_Shutdown_Req req;
  389. UpsService_Shutdown_Ans ans;
  390. if (bImmediately)
  391. {
  392. req.ShutdownTime = 1;
  393. req.UpTime = 1;
  394. }
  395. else
  396. {
  397. req.ShutdownTime = 1;//oiltmp
  398. req.UpTime = 3; //oiltmp
  399. }
  400. ErrorCodeEnum eErrShutdown = m_pUpsClient->Shutdown(req,ans,10000);
  401. if (eErrShutdown == Error_Succeed)
  402. {
  403. //m_lastHour = localTime.wHour;
  404. Dbg("to shutdown");
  405. m_bToRestart = true;
  406. Sleep(20000);
  407. m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger,m_eRebootWay);
  408. int ret;
  409. if (m_bGetUpsStateFlag)
  410. ret = SystemShutdown();
  411. else
  412. ret = SystemShutdown(TRUE);
  413. Dbg("after ups,SystemShutdown result %d",ret);
  414. }
  415. else
  416. Dbg("shutdown failed(%d)",eErrShutdown);
  417. }
  418. else
  419. {
  420. Dbg("no ups,so to restart directly.");
  421. if (!m_bToRestart)
  422. {
  423. m_restartTimes++;
  424. if (m_restartTimes > m_maxRestartTimes)
  425. {
  426. Dbg("restart too many times(%d,%d),give up.",m_restartTimes,m_maxRestartTimes);
  427. m_restartTimes--;
  428. return -1;
  429. }
  430. Dbg("the %d restart.",m_restartTimes);
  431. spConfigRun->WriteConfigValueInt("Run","RestartTimes",m_restartTimes);
  432. if (m_lastHour != localTime.wHour)
  433. {
  434. m_lastHour = localTime.wHour;
  435. Dbg("set last hour to %d", m_lastHour);
  436. spConfigRun->WriteConfigValueInt("Run", "LastHour", m_lastHour);
  437. }
  438. //oilyang 20140606
  439. //framework to reboot os
  440. //int ret = SystemShutdown(TRUE);
  441. m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger,RebootWay_OS);
  442. //Dbg("no ups,SystemShutdown result %d",ret);
  443. }
  444. }
  445. return 0;
  446. }
  447. /** 这里建议改用调用框架提供的接口,关机、重启均支持 [Gifur@202135]*/
  448. //system api shutdown
  449. int CHealthManagerEntity::SystemShutdown(BOOL bReboot)
  450. {
  451. #ifdef RVC_OS_WIN
  452. HANDLE hToken; // handle to process token
  453. TOKEN_PRIVILEGES tkp; // pointer to token structure
  454. BOOL fResult; // system shutdown flag
  455. // Get the current process token handle so we can get shutdown
  456. // privilege.
  457. if (!OpenProcessToken(GetCurrentProcess(),
  458. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  459. return FALSE;
  460. // Get the LUID for shutdown privilege.
  461. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
  462. &tkp.Privileges[0].Luid);
  463. tkp.PrivilegeCount = 1; // one privilege to set
  464. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  465. // Get shutdown privilege for this process.
  466. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  467. (PTOKEN_PRIVILEGES) NULL, 0);
  468. // Cannot test the return value of AdjustTokenPrivileges.
  469. if (GetLastError() != ERROR_SUCCESS)
  470. return FALSE;
  471. // Display the shutdown dialog box and start the countdown.
  472. fResult = InitiateSystemShutdown(
  473. NULL, // shut down local computer
  474. NULL, // message for user
  475. 0, // time-out period, in seconds
  476. FALSE, // ask user to close apps
  477. bReboot); // reboot after shutdown
  478. if (!fResult)
  479. return FALSE;
  480. // Disable shutdown privilege.
  481. tkp.Privileges[0].Attributes = 0;
  482. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
  483. (PTOKEN_PRIVILEGES) NULL, 0);
  484. return 0;
  485. #else
  486. sync();
  487. if (bReboot)
  488. system("init 6");
  489. else
  490. system("init 0");
  491. return 0;//oiltestlinux
  492. #endif //RVC_OS_WIN
  493. }
  494. ErrorCodeEnum CHealthManagerEntity::SystemShutdownThroughUPS(DWORD msPreShutdown, DWORD msPreRestart)
  495. {
  496. bool upsIsNull = true;
  497. ErrorCodeEnum result = Error_Unexpect;
  498. if (m_pUpsClient) {
  499. m_pUpsClient->GetFunction()->CloseSession();
  500. m_pUpsClient = NULL;
  501. upsIsNull = false;
  502. }
  503. m_pUpsClient = new UpsService_ClientBase(this);
  504. ErrorCodeEnum eErrConn = m_pUpsClient->Connect();
  505. if (eErrConn != Error_Succeed) {
  506. Dbg("Ups connected failed: %s", SpStrError(eErrConn));
  507. m_pUpsClient->SafeDelete();
  508. m_pUpsClient = NULL;
  509. return eErrConn;
  510. }
  511. do
  512. {
  513. UpsService_GetStatus_Req req;
  514. UpsService_GetStatus_Ans ans;
  515. ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req, ans, 3000);
  516. Dbg("current state %d", ans.Status);
  517. } while (false);
  518. do
  519. {
  520. UpsService_Shutdown_Req req;
  521. UpsService_Shutdown_Ans ans;
  522. req.ShutdownTime = msPreShutdown; //刚好可以等到框架退出
  523. req.UpTime = msPreRestart; //要求5分钟内拔掉电源来实现真正断电关机
  524. ErrorCodeEnum eErrShutdown = m_pUpsClient->Shutdown(req, ans, 10000);
  525. if (eErrShutdown == Error_Succeed) {
  526. Dbg("Invoke UPS::Shutdown successfully.");
  527. result = Error_Succeed;
  528. } else {
  529. CSimpleStringA tmp = CSimpleStringA::Format("通过UPS关机失败:%s", SpStrError(eErrShutdown));
  530. this->GetFunction()->ShowFatalError(tmp);
  531. result = eErrShutdown;
  532. }
  533. } while (false);
  534. if (upsIsNull && m_pUpsClient) {
  535. m_pUpsClient->GetFunction()->CloseSession();
  536. m_pUpsClient = NULL;
  537. }
  538. return result;
  539. }
  540. int CHealthManagerEntity::FrameworkShutdown(bool bRestart)
  541. {
  542. #ifdef RVC_OS_WIN
  543. STARTUPINFO si;
  544. PROCESS_INFORMATION pi;
  545. ZeroMemory( &si, sizeof(si) );
  546. si.cb = sizeof(si);
  547. ZeroMemory( &pi, sizeof(pi) );
  548. GetFunction()->FlushLogFile();
  549. // LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\\Program Files\\MyApp\" -L -S"));
  550. //CreateProcess(NULL, szCmdline, /*...*/);
  551. // Start the child process.
  552. CSimpleStringA csRestart,csVerPath,csAll,csSep("\""),csBlank(" "),csScript("wscript.exe"),csReFlag("r");
  553. csRestart = "sprestart.exe ";
  554. ErrorCodeEnum Error = GetFunction()->GetPath("RootVer", csVerPath);
  555. //csVerPath +="\\spexplorerfast.vbs";
  556. csVerPath +="\\VTM.exe";
  557. if (!bRestart)
  558. csReFlag = "n";
  559. //csAll = csSep + csRestart + csSep + csBlank + csSep + csScript+csBlank + csVerPath + csSep
  560. // + csBlank + csSep + csReFlag + csSep;
  561. csAll = csSep + csRestart + csSep + csBlank + csSep + csVerPath + csSep
  562. + csBlank + csSep + csReFlag + csSep;
  563. Dbg("allpath[%s]",(LPCTSTR)csAll);
  564. LPTSTR szCmdline = _strdup(csAll);
  565. if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
  566. {
  567. Dbg("CreateProcess failed (%d).\n", GetLastError());
  568. return -1;
  569. }
  570. m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
  571. //MessageBoxA(0,0,0,0);
  572. DWORD dwErr = GetLastError();
  573. // Wait until child process exits.
  574. WaitForSingleObject( pi.hProcess, INFINITE );
  575. // Close process and thread handles.
  576. CloseHandle( pi.hProcess );
  577. CloseHandle( pi.hThread );
  578. return 0;
  579. #else
  580. Dbg("FrameworkShutdown to call QuitFrameworkAndSaveInfo:%d,%d", m_eRebootTrigger, m_eRebootWay);
  581. m_fsm.QuitFrameworkAndSaveInfo(m_eRebootTrigger, m_eRebootWay);
  582. return 0;//oiltestlinux
  583. #endif
  584. }
  585. //almost disused.
  586. //the function moved to Entity "SelfChecker"
  587. ErrorCodeEnum CHealthManagerEntity::RestartModule(const char* pEntityName)
  588. {
  589. CSmartPointer<IEntityFunction> pFunc = GetFunction();
  590. CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
  591. if (pFuncPrivilege == NULL)
  592. {
  593. Dbg("restart mc NoPrivilege");
  594. return Error_NoPrivilege;
  595. }
  596. map<CSimpleStringA,ModuleRunInfo>::iterator it;
  597. it = m_modRunInfo.find(pEntityName);
  598. if (it == m_modRunInfo.end())
  599. {
  600. Dbg("add %s to modfuninfo(%d).",pEntityName,m_modRunInfo.size());
  601. m_modRunInfo[pEntityName].count = 1;
  602. m_modRunInfo[pEntityName].dwStart = GetTickCountRVC();
  603. }
  604. else
  605. {
  606. Dbg("modruninfo size %d",m_modRunInfo.size());
  607. Dbg("%d",m_modRunInfo[pEntityName].count);
  608. (m_modRunInfo[pEntityName].count)++;
  609. Dbg("%d",m_modRunInfo[pEntityName].count);
  610. }
  611. CSmartPointer<IAsynWaitSp> spWait;
  612. ErrorCodeEnum eErrCode = Error_Succeed;
  613. eErrCode = pFuncPrivilege->TerminateEntity(pEntityName,spWait);
  614. if (spWait != NULL)
  615. eErrCode = spWait->WaitAnswer(10000);
  616. if (eErrCode != Error_Succeed)
  617. {
  618. Dbg("kill %s %d",pEntityName,eErrCode);
  619. return eErrCode;
  620. }
  621. Sleep(3000);
  622. eErrCode = pFuncPrivilege->StartEntity(pEntityName,NULL,spWait);
  623. if (spWait != NULL)
  624. eErrCode = spWait->WaitAnswer(10000);
  625. if (eErrCode != Error_Succeed)
  626. {
  627. Dbg("start %s %d",pEntityName,eErrCode);
  628. return eErrCode;
  629. }
  630. //m_modRestartCount++;
  631. //if (m_modRestartCount == 1)
  632. // m_MCStart = GetTickCount();
  633. DWORD dwMaxTimes,dwInternal;
  634. if (m_modCfgInfo.find(pEntityName) == m_modCfgInfo.end())
  635. {
  636. dwMaxTimes = m_restartMode[RESTART_MODE_DEFAULT].dwTimes;
  637. dwInternal = m_restartMode[RESTART_MODE_DEFAULT].dwInternal;
  638. }
  639. else
  640. {
  641. dwMaxTimes = m_restartMode[m_modCfgInfo[pEntityName]].dwTimes;
  642. dwInternal = m_restartMode[m_modCfgInfo[pEntityName]].dwInternal;
  643. }
  644. Dbg("%d,%d,%s restart %d times",dwMaxTimes,dwInternal,pEntityName,m_modRunInfo[pEntityName].count);
  645. if (m_modRunInfo[pEntityName].count > dwMaxTimes)
  646. {
  647. m_MCEnd = GetTickCountRVC();
  648. if (m_MCEnd-m_modRunInfo[pEntityName].dwStart < dwInternal)
  649. {
  650. Dbg("wait chance to restart pc.");
  651. //if (_strnicmp(pEntityName, "FaceTracking", strlen("FaceTracking")) != 0)
  652. // m_bWaitRestartPC = true;
  653. }
  654. else
  655. {
  656. m_modRunInfo[pEntityName].dwStart = m_MCEnd;
  657. m_modRunInfo[pEntityName].count = 0;
  658. LogWarn(Severity_Low,Error_Unexpect,LOG_WARN_HEALTH_MODULE_RESTART_TIMES
  659. ,"restart x times in more than 10mins");
  660. }
  661. }
  662. return eErrCode;
  663. }
  664. void CHealthManagerEntity::AfterWaitRestartPC()
  665. {
  666. //ReadMachineDataBySyncSerivce();
  667. Dbg("menu:[%s]",(LPCTSTR)m_menuChoice);
  668. CSmartPointer<IEntityFunction> pFunc = GetFunction();
  669. CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
  670. if (pFuncPrivilege == NULL)
  671. {
  672. Dbg("restart pc NoPrivilege");
  673. return;
  674. }
  675. ErrorCodeEnum eErr;
  676. CSimpleStringA csCustomerHandle("");
  677. eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle);
  678. Dbg("cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle);
  679. if (eErr != Error_Succeed)
  680. {
  681. Dbg("get CustomerHandle failed (%d).",eErr);
  682. }
  683. else if (csCustomerHandle[0] == 'N')
  684. {
  685. m_bWaitRestartPC = false;
  686. pFuncPrivilege->DisplayBlueScreen("暂停服务test");
  687. Dbg("time comes,restart machine");
  688. m_eRebootTrigger = RebootTrigger_RunExcepition;
  689. m_eRebootWay = RebootWay_Power;
  690. SystemRestart(false, true);
  691. }
  692. }
  693. void CHealthManagerEntity::UpsSupplyLockScreen()
  694. {
  695. ErrorCodeEnum eErr;
  696. CSimpleStringA csCustomerHandle("");
  697. eErr = GetFunction()->GetSysVar("CustomerHandle",csCustomerHandle);
  698. Dbg("upslockscreen cust handle %d,%s",eErr,(LPCTSTR)csCustomerHandle);
  699. if (eErr != Error_Succeed)
  700. {
  701. Dbg("get CustomerHandle failed (%d).",eErr);
  702. }
  703. else// if (csCustomerHandle[0] == 'N')
  704. {
  705. CSmartPointer<IEntityFunction> pFunc = GetFunction();
  706. CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
  707. if (pFuncPrivilege == NULL)
  708. {
  709. Dbg("display screen NoPrivilege");
  710. return;
  711. }
  712. pFuncPrivilege->DisplayBlueScreen("暂停服务");
  713. LogEvent(Severity_High,LOG_EVT_HEALTH_UPS_NO_ELECTOR,"ups no elector,to shutdown machine");
  714. Dbg("ups no elector,display screen.");
  715. //oiltmp eject card and sth else
  716. Sleep(30000);
  717. if (m_bUpsWaitLock)
  718. {
  719. m_bUpsWaitLock = false;
  720. m_bScreenLock = true;
  721. int ret = SystemShutdown();
  722. Dbg("SystemShutdown result %d",ret);
  723. }
  724. else
  725. {
  726. pFuncPrivilege->UndisplayBlueScreen();
  727. m_bUpsWaitLock = false;
  728. m_bScreenLock = false;
  729. }
  730. }
  731. }
  732. void CHealthManagerEntity::OnCheckTimeTimeout()
  733. {
  734. if (m_bNeedToRestartIE)
  735. {
  736. //oilyang 20160704
  737. //to judge in main page & the phone is offline
  738. CSimpleStringA csCustHandle("");
  739. ErrorCodeEnum eErr = Error_Unexpect;
  740. eErr = GetFunction()->GetSysVar("CustomerHandle", csCustHandle);
  741. if (eErr == Error_Succeed)
  742. {
  743. if (csCustHandle.Compare("C") != 0 && csCustHandle.Compare("T") != 0 && csCustHandle.Compare("G") != 0)
  744. {
  745. if (m_bInMainPage)
  746. {
  747. Dbg("to restart iebrowser.");
  748. RestartIE();
  749. }
  750. }
  751. }
  752. }
  753. SYSTEMTIME localTime;
  754. GetLocalTimeRVC(localTime);
  755. //99 is initial value of m_preDay
  756. if (m_preDay != 99 && m_preDay != localTime.wDayOfWeek && m_bNeedToRestartPAD == false)
  757. m_bNeedToRestartPAD = true;
  758. m_preDay = localTime.wDayOfWeek;
  759. CSmartPointer<IConfigInfo> spConfigRun;
  760. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
  761. if (eErr != Error_Succeed)
  762. Dbg("timer open cfg file failed!");
  763. else
  764. {
  765. if (localTime.wHour != m_lastHour)
  766. {
  767. Dbg("hour changed,to set restart times to 0");
  768. spConfigRun->WriteConfigValueInt("Run", "RestartTimes", 0);
  769. }
  770. }
  771. if (_strnicmp(m_sysStaticInfo.strMachineType.GetData(), "RVC.PAD", strlen("RVC.PAD")) == 0)
  772. {
  773. if (m_bNeedToRestartPAD)
  774. {
  775. ULONGLONG ull = 0;
  776. ull = GetTickCountRVC();
  777. int osRunHours = 0, osRunDays = 0;
  778. osRunHours = (ull / (1000 * 60 * 60));
  779. osRunDays = osRunHours / 24;
  780. CSmartPointer<IConfigInfo> spConfigRun;
  781. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
  782. if (m_maxRunDays <= 0)
  783. m_maxRunDays = 7;
  784. if (osRunDays >= m_maxRunDays)
  785. {
  786. Dbg("os has run %d hour,to restart os.", osRunHours);
  787. spConfigRun->WriteConfigValueInt("Restart", "DayNum", 0);
  788. m_eRebootTrigger = RebootTrigger_Period;
  789. m_eRebootWay = RebootWay_Power;
  790. SystemRestart(true,true);
  791. }
  792. else if (osRunDays >= 1)
  793. {
  794. if (osRunDays > m_dayNum)
  795. {
  796. Dbg("os has run %d hour,to restart framework.", osRunHours);
  797. spConfigRun->WriteConfigValueInt("Restart", "DayNum", osRunDays);
  798. m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Period, RebootWay_Framework);
  799. }
  800. }
  801. }
  802. }
  803. else //not RVC.PAD
  804. {
  805. if (m_wDayOfWeek != localTime.wDayOfWeek)
  806. {
  807. if (localTime.wHour == m_restartHour && localTime.wMinute >= m_restartMinute
  808. && localTime.wMinute <= (m_restartMinute + HEALTHMANAGER_TIMER_INTERVAL_MINUTE))
  809. {
  810. m_wDayOfWeek = localTime.wDayOfWeek;
  811. m_eRebootTrigger = RebootTrigger_Period;
  812. m_eRebootWay = RebootWay_Power;
  813. BOOL bRet = SystemRestart(true,true);
  814. Dbg("restart machine[%d][%d] bRet=%d, LastError=%d", localTime.wHour, localTime.wMinute, bRet, GetLastError());
  815. Dbg("not rvc.pad %s,%s", m_sysStaticInfo.strMachineType.GetData(), (const char*)m_sysStaticInfo.strMachineType);
  816. }
  817. }
  818. }
  819. if (m_pUpsClient == NULL)
  820. {
  821. CSimpleStringA csRunState("B");
  822. GetFunction()->GetSysVar("RunState",csRunState);
  823. if (csRunState[0] != 'B' || csRunState[0] != 'I')
  824. {
  825. if (_strnicmp(m_sysStaticInfo.strMachineType.GetData(), "RVC.Stand2S", strlen("RVC.Stand2S") == 0))
  826. {
  827. int ret = ConnectUps();
  828. Dbg("connect ups %d.", ret);
  829. }
  830. }
  831. }
  832. else
  833. {
  834. UpsService_GetStatus_Req req;
  835. UpsService_GetStatus_Ans ans;
  836. ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req,ans,3000);
  837. if (eErrState == Error_Succeed)
  838. {
  839. m_bGetUpsStateFlag = true;
  840. switch(ans.Status)
  841. {
  842. case UPS_STATUS_NORMAL:
  843. m_bUpsWaitLock = false;
  844. m_upsNoElectorCount = 0;
  845. break;
  846. case UPS_STATUS_ERROR_TO_GET_STATUS:
  847. m_upsStateCount++;
  848. if (m_upsStateCount > 3)
  849. {
  850. //logwarn oiltmp
  851. }
  852. break;
  853. case UPS_STATUS_NO_ELECTOR:
  854. m_bUpsWaitLock = true;
  855. m_upsNoElectorCount++;
  856. if (m_upsNoElectorCount > 2)
  857. {
  858. //logwarn oiltmp
  859. //notify front end
  860. //shutdown pc or not?
  861. }
  862. break;
  863. default:
  864. break;
  865. }
  866. //Dbg("current state %d",ans.Status);
  867. }
  868. else
  869. {
  870. Dbg("get ups state failed(%d).",eErrState);
  871. m_bGetUpsStateFlag = false;
  872. if (eErrState == Error_NetBroken)
  873. {
  874. m_pUpsClient->GetFunction()->CloseSession();
  875. m_pUpsClient = NULL;
  876. }
  877. }
  878. }
  879. //ReadMachineDataBySyncSerivce();
  880. int iCheckGuardian = 0;
  881. if (m_fsm.GetFSMState() == HM_FSM_STATE_IDLE || (m_fsm.GetFSMState() == HM_FSM_STATE_CMS))
  882. {
  883. //oilyang@20210922 add comment
  884. //1、AccessAuth ok
  885. //2、have ever enter main page OR
  886. if (m_fsm.GetAccessAuthFlag() && (m_bEnterMainPageEver || (!m_bEnterMainPageEver && m_fsm.IfIEBeforeHealth())))//oilyang 20161219 改成通过是否成功进入主页来判断IE情况
  887. {
  888. //oilyang@20210923 N for "Normal",changed for liuwentao
  889. GetFunction()->SetSysVar("RunState", "N");
  890. iCheckGuardian = CheckGuardianIsRun(true);
  891. if (!m_bSayIdle)
  892. {
  893. m_bSayIdle = true;
  894. if (iCheckGuardian > 0)
  895. {
  896. if (m_pfUpgradeRestart != NULL)
  897. {
  898. int ret = m_pfUpgradeRestart(3, 0);
  899. Dbg("healthmanager say idle,so tell the guardian.%d", ret);
  900. }
  901. }
  902. CSimpleStringA csRunInfo,csStartTime;
  903. if ((GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
  904. {
  905. Dbg("get runinfo path failed(%d)");
  906. }
  907. else
  908. {
  909. csStartTime = csRunInfo + "/runcfg/starttime.dat";
  910. int ret = remove(csStartTime);
  911. if (ret == 0)
  912. Dbg("delete time file error.[%d]",GetLastError());
  913. }
  914. }
  915. if (iCheckGuardian > 0)
  916. {
  917. if (m_pfShake != NULL)
  918. {
  919. WorkStateEnum eShake;
  920. Dbg("to shake...");
  921. int ret = m_pfShake(eShake);
  922. //if (eErrShake != Error_Succeed)
  923. Dbg("shake hand result:%d,work state %d", ret, eShake);
  924. }
  925. if (!m_bHealthInit)
  926. {
  927. bool bStop = StopGuardian();
  928. if (bStop)
  929. {
  930. m_bHealthInit = true;
  931. bool bGuardian = StartGuardian();
  932. Dbg("restart guardian %d", bGuardian);
  933. }
  934. }
  935. }
  936. else if (iCheckGuardian == -1)
  937. {
  938. Dbg("to start guardian");
  939. bool bGuardian = StartGuardian();
  940. Dbg("start guardian %d",bGuardian);
  941. }
  942. }
  943. else
  944. {
  945. //oilyang@20190905 add if auth suc,tell guardian,for upgrade
  946. if (m_fsm.GetAccessAuthFlag())
  947. {
  948. if (CheckGuardianIsRun(true) > 0)
  949. {
  950. if (m_pfUpgradeRestart != NULL)
  951. {
  952. int ret = m_pfUpgradeRestart(5, 0);
  953. Dbg("auth suc,so tell the guardian.%d", ret);
  954. }
  955. }
  956. }
  957. }
  958. }
  959. else
  960. {
  961. m_bSayIdle = false;
  962. }
  963. //oilyang@20210331 if accessauth told me not to restart framework,so that it can have time to retry
  964. if (!m_bNeedGuardianRestart)
  965. {
  966. if (CheckGuardianIsRun(true) > 0)
  967. {
  968. if (m_pfShake != NULL)
  969. {
  970. WorkStateEnum eShake;
  971. int ret = m_pfShake(eShake);
  972. Dbg("accessauth told me not to restart framework,so that it can have time to retry.%d", ret);
  973. }
  974. }
  975. }
  976. if (m_fsm.GetFSMState() == HM_FSM_STATE_CMS)
  977. {
  978. GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL);
  979. return;
  980. }
  981. if (m_bWaitRestartPC)
  982. {
  983. Dbg("finally we the restart time come,no wait.");
  984. //m_bWaitRestartPC = false;
  985. AfterWaitRestartPC();
  986. }
  987. if (m_bUpsWaitLock)
  988. {
  989. UpsSupplyLockScreen();
  990. }
  991. else
  992. {
  993. //no need to un-display blue screen? oiltest 20140320
  994. //if (m_bScreenLock)
  995. //{
  996. // CSmartPointer<IEntityFunction> pFunc = GetFunction();
  997. // CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
  998. // if (pFuncPrivilege == NULL)
  999. // {
  1000. // Dbg("unlock screen NoPrivilege");
  1001. // return;
  1002. // }
  1003. // pFuncPrivilege->UndisplayBlueScreen();
  1004. // m_bScreenLock = false;
  1005. //}
  1006. }
  1007. GetFunction()->ResetTimer(HEALTHMANAGER_TIMER_ID, HEALTHMANAGER_TIMER_INTERVAL);
  1008. }
  1009. #if defined(RVC_OS_LINUX)
  1010. bool FindGuardianPid(pid_t &pid)
  1011. {
  1012. char* relate_processes[] = { "guardian" };
  1013. int count = 1;
  1014. alive_process_info processes[1];
  1015. memset(processes, 0, sizeof(processes));
  1016. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
  1017. if (count > 0) {
  1018. pid = processes[0].pid;
  1019. return true;
  1020. }
  1021. return false;
  1022. }
  1023. #endif //RVC_OS_LINUX
  1024. int CHealthManagerEntity::CheckGuardianIsRun(bool bStart)
  1025. {
  1026. if (!m_bNeedGuardian)//no need guardian
  1027. return 0;
  1028. #ifdef RVC_OS_WIN
  1029. HANDLE hSnapshot;
  1030. //find guardian.exe
  1031. hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  1032. if (hSnapshot)
  1033. {
  1034. PROCESSENTRY32 pe;
  1035. pe.dwSize = sizeof(pe);
  1036. if (Process32First(hSnapshot, &pe))
  1037. {
  1038. do {
  1039. if (_stricmp(&pe.szExeFile[0], "guardian.exe") == 0)
  1040. {
  1041. //Dbg("guardian is running.");
  1042. return true;
  1043. }
  1044. } while (Process32Next(hSnapshot, &pe));
  1045. }
  1046. CloseHandle(hSnapshot);
  1047. }
  1048. Sleep(1000);
  1049. Dbg("cannot find guardian.");
  1050. if (bStart)
  1051. return StartGuardian();
  1052. else
  1053. return false;
  1054. #else
  1055. Dbg("to check guardian is online.");
  1056. pid_t pID;
  1057. bool bFind = false;
  1058. bFind = FindGuardianPid(pID);
  1059. if (bFind)
  1060. {
  1061. Dbg("find guardian");
  1062. int ret = kill(pID, 0);
  1063. Dbg("ret= %d ", ret);
  1064. if (0 == ret)
  1065. {
  1066. Dbg("process: guardian.exe exist!");
  1067. return true;
  1068. }
  1069. else
  1070. {
  1071. Dbg("process: guardian.exe not exist!");
  1072. if (bStart)
  1073. return StartGuardian();
  1074. else
  1075. return false;
  1076. }
  1077. }
  1078. if (bStart)
  1079. return StartGuardian();
  1080. else
  1081. return false;
  1082. #endif //RVC_OS_WIN
  1083. }
  1084. bool CHealthManagerEntity::StopGuardian()
  1085. {
  1086. #ifdef RVC_OS_WIN
  1087. Dbg("to stop guardian");
  1088. HANDLE hSnapshot;
  1089. int rc = TRUE;
  1090. int result;
  1091. HANDLE hProcess;
  1092. //find and kill guardian.exe
  1093. hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  1094. if (hSnapshot)
  1095. {
  1096. PROCESSENTRY32 pe;
  1097. pe.dwSize = sizeof(pe);
  1098. if (Process32First(hSnapshot, &pe))
  1099. {
  1100. do {
  1101. if (_stricmp(&pe.szExeFile[0], "guardian.exe") == 0)
  1102. {
  1103. hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID );
  1104. if( hProcess == NULL )
  1105. {
  1106. Dbg("Fail to open process(%d)!",GetLastError());
  1107. return false;
  1108. }
  1109. else
  1110. {
  1111. result = TerminateProcess(hProcess,-1);
  1112. if (result)
  1113. {
  1114. Dbg("Terminate guardian suc.");
  1115. return true;
  1116. }
  1117. else
  1118. {
  1119. Dbg("Terminate guardian failed(%d).",GetLastError());
  1120. return false;
  1121. }
  1122. CloseHandle( hProcess );
  1123. }
  1124. Sleep(3000);
  1125. WaitForSingleObject(&pe.th32ProcessID, INFINITE );
  1126. break;
  1127. }
  1128. } while (Process32Next(hSnapshot, &pe));
  1129. }
  1130. CloseHandle(hSnapshot);
  1131. }
  1132. Sleep(3000);
  1133. return false;
  1134. #else
  1135. int ret = m_pfUpgradeRestart(6, 0);
  1136. Dbg("healthmanager tell the guardian to quit.%d", ret);
  1137. Sleep(5000);
  1138. pid_t pID;
  1139. bool bFind = false;
  1140. bFind = FindGuardianPid(pID);
  1141. if (bFind)
  1142. {
  1143. int ret = kill(pID, 9);
  1144. if (ret < 0)
  1145. {
  1146. Dbg("kill guardian failed:%d",errno);
  1147. return false;
  1148. }
  1149. else
  1150. {
  1151. Dbg("killed guardian.");
  1152. return true;
  1153. }
  1154. }
  1155. Dbg("can't find guardian pid.");
  1156. return true;
  1157. #endif //RVC_OS_WIN
  1158. }
  1159. bool CHealthManagerEntity::StartGuardian()
  1160. {
  1161. LOG_FUNCTION();
  1162. if (m_sysStaticInfo.strMachineType.Compare("RVC.IL") == 0)
  1163. {
  1164. Dbg("machine type is RVC.IL,no need to start guardian.exe");
  1165. return false;
  1166. }
  1167. Dbg("to start guardian");
  1168. // Start the child process.
  1169. CSimpleStringA csBinPath;
  1170. ErrorCodeEnum Error = GetFunction()->GetPath("Bin", csBinPath);
  1171. #ifdef RVC_OS_WIN
  1172. STARTUPINFO si;
  1173. PROCESS_INFORMATION pi;
  1174. ZeroMemory( &si, sizeof(si) );
  1175. si.cb = sizeof(si);
  1176. ZeroMemory( &pi, sizeof(pi) );
  1177. GetFunction()->FlushLogFile();
  1178. // Start the child process.
  1179. CSimpleStringA csAll,csSep("\"");
  1180. csBinPath +="\\guardian.exe";
  1181. csAll = csSep + csBinPath + csSep;
  1182. Dbg("guardian path[%s]",(LPCTSTR)csAll);
  1183. LPTSTR szCmdline = _strdup(csAll);
  1184. if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
  1185. {
  1186. Dbg("CreateProcess failed (%d).\n", GetLastError());
  1187. return false;
  1188. }
  1189. DWORD dwErr = GetLastError();
  1190. return true;
  1191. #else
  1192. char app[MAX_PATH];
  1193. memset(app,0, sizeof(app));
  1194. tk_process_t* process = NULL;
  1195. tk_process_option_t option;
  1196. csBinPath += "/guardian";
  1197. Dbg("path:%s",(const char*)csBinPath);
  1198. sprintf(app, "%s %s %d", (const char*)csBinPath,"oiltest",1);
  1199. option.exit_cb = NULL;
  1200. option.file = NULL;
  1201. option.flags = 0;
  1202. option.params = app;
  1203. if (0 == process_spawn(&option, &process)) {
  1204. Dbg("process_spawn guardian");
  1205. FREE(process);
  1206. return true;
  1207. }
  1208. Dbg("end of StartGuardian");
  1209. return false;
  1210. #endif //RVC_OS_WIN
  1211. }
  1212. bool CHealthManagerEntity::DoRestart()
  1213. {
  1214. LOG_FUNCTION();
  1215. CSmartPointer<IConfigInfo> spConfig;
  1216. ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Software, spConfig);
  1217. if (err != Error_Succeed) {
  1218. LOG_TRACE("open cfg file failed!");
  1219. return false;
  1220. }
  1221. m_restartHour = m_restartMinute = 1;
  1222. m_maxRestartTimes = 3;
  1223. int defaultTimesMax,defaultInternal,lowTimesMax,lowInternal;
  1224. defaultTimesMax = 10;
  1225. defaultInternal = 600000;
  1226. lowTimesMax = 5;
  1227. lowInternal = 600000;
  1228. spConfig->ReadConfigValueInt("init","RestartHour",m_restartHour);
  1229. spConfig->ReadConfigValueInt("init","RestartMinute",m_restartMinute);
  1230. int testflag;
  1231. spConfig->ReadConfigValueInt("init","TestFlag",testflag);
  1232. m_testFlag = testflag;
  1233. spConfig->ReadConfigValueInt("Run","MaxRestartTimes",m_maxRestartTimes);
  1234. Dbg("m_maxRestartTimes(%d)",m_maxRestartTimes);
  1235. spConfig->ReadConfigValueInt("ModRestartSettings","DefaultTimesMax",defaultTimesMax);
  1236. spConfig->ReadConfigValueInt("ModRestartSettings","DefaultInternal",defaultInternal);
  1237. spConfig->ReadConfigValueInt("ModRestartSettings","LowTimesMax",lowTimesMax);
  1238. spConfig->ReadConfigValueInt("ModRestartSettings","LowInternal",lowInternal);
  1239. m_restartMode[RESTART_MODE_DEFAULT].dwTimes = defaultTimesMax;
  1240. m_restartMode[RESTART_MODE_DEFAULT].dwInternal = defaultInternal;
  1241. m_restartMode[RESTART_MODE_LOW].dwTimes = lowTimesMax;
  1242. m_restartMode[RESTART_MODE_LOW].dwInternal = lowInternal;
  1243. CSimpleStringA csDefaultModule,csLowModule;
  1244. spConfig->ReadConfigValue("ModRestartSettings","DefaultModule",csDefaultModule);
  1245. spConfig->ReadConfigValue("ModRestartSettings","LowModule",csLowModule);
  1246. SplitModuleNames(csDefaultModule,RESTART_MODE_DEFAULT);
  1247. SplitModuleNames(csLowModule,RESTART_MODE_LOW);
  1248. Dbg("%d:%d",m_restartHour,m_restartMinute);
  1249. CSmartPointer<IConfigInfo> spConfigRun;
  1250. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1251. spConfigRun->ReadConfigValueInt("Run", "LastHour", m_lastHour);
  1252. m_dayNum = 1;
  1253. spConfigRun->ReadConfigValueInt("Restart", "DayNum", m_dayNum);
  1254. if (m_dayNum == 0)
  1255. {
  1256. spConfigRun->WriteConfigValueInt("Restart", "DayNum", 0);
  1257. }
  1258. spConfigRun->ReadConfigValueInt("Run", "RestartTimes", m_restartTimes);
  1259. CSmartPointer<IConfigInfo> spCerConfig;
  1260. eErr = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
  1261. spCerConfig->ReadConfigValueInt(GetEntityName(), "MaxRunDays", m_maxRunDays);
  1262. int xNdGuardian = 0;
  1263. spCerConfig->ReadConfigValueInt("NonExclusive", "NonGuardian", xNdGuardian);
  1264. if (xNdGuardian == 1)
  1265. m_bNeedGuardian = false;
  1266. Dbg("central setting:m_maxRunDays:%d,DayNum:%d,xNdGuardian:%d", m_maxRunDays,m_dayNum, xNdGuardian);
  1267. SYSTEMTIME localTime;
  1268. GetLocalTimeRVC(localTime);
  1269. if (m_bInit) {
  1270. m_bInit = false;
  1271. m_wDayOfWeek = localTime.wDayOfWeek;
  1272. }
  1273. eErr = GetFunction()->GetSystemStaticInfo(m_sysStaticInfo);
  1274. if (eErr != Error_Succeed)
  1275. {
  1276. Dbg("Get system static info failed(%s).", SpStrError(eErr));
  1277. m_sysStaticInfo.strMachineType = "";
  1278. m_sysStaticInfo.strSite = "";
  1279. m_sysStaticInfo.InstallVersion = CVersion();
  1280. }
  1281. //ReadMachineDataBySyncSerivce();
  1282. ITimerListener *pListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnCheckTimeTimeout);
  1283. Dbg("set timer");
  1284. GetFunction()->SetTimer(HEALTHMANAGER_TIMER_ID, pListener, HEALTHMANAGER_TIMER_INTERVAL);
  1285. //oiltmp 20131204 commented,the following upline(...)add it
  1286. //DoWatchDog(WD_OP_START);
  1287. //ITimerListener *pWDListener = new TimerOutHelper<CHealthManagerEntity>(this, &CHealthManagerEntity::OnWatchDogTimeout);
  1288. //GetFunction()->SetTimer(HEALTHMANAGER_WD_TIMER_ID, pWDListener, HEALTHMANAGER_WD_TIMER_INTERVAL);
  1289. CSimpleStringA deamonBasePath = "";
  1290. err = GetFunction()->GetPath("bin",deamonBasePath);
  1291. if (err != Error_Succeed) {
  1292. Dbg("for wait deamon get bin path failed(%d).",err);
  1293. return false;
  1294. }
  1295. #if defined(RVC_OS_LINUX)
  1296. deamonBasePath += "/libGuardianBase.so";
  1297. Dbg("gd path [%s]", (LPCTSTR)deamonBasePath);
  1298. void* handle = dlopen(deamonBasePath, RTLD_LAZY);
  1299. if (handle == NULL)
  1300. {
  1301. Dbg("load libGuardianBase.so failed(%d)", errno);
  1302. return false;
  1303. }
  1304. m_pfShake = (pfShakeHands)dlsym(handle, "ShakeHands");
  1305. if (m_pfShake == NULL)
  1306. {
  1307. Dbg("get ShakeHands failed(%d)", GetLastError());
  1308. return false;
  1309. }
  1310. m_pfUpgradeRestart = (pfUpgradeRestart)dlsym(handle, "UpgradeRestart");
  1311. if (m_pfUpgradeRestart == NULL)
  1312. {
  1313. Dbg("get UpgradeRestart failed(%d)", GetLastError());
  1314. return false;
  1315. }
  1316. #else
  1317. deamonBasePath += "\\GuardianBase.dll";
  1318. HMODULE hDll = LoadLibraryA(deamonBasePath);
  1319. Dbg("gd path [%s]", (LPCTSTR)deamonBasePath);
  1320. if (hDll == NULL)
  1321. {
  1322. Dbg("load guardianbase.dll failed(%d)", GetLastError());
  1323. return false;
  1324. }
  1325. m_pfShake = (pfShakeHands)GetProcAddress(hDll,"ShakeHands");
  1326. if (m_pfShake == NULL)
  1327. {
  1328. Dbg("get shakehands failed(%d)",GetLastError());
  1329. return false;
  1330. }
  1331. m_pfUpgradeRestart = (pfUpgradeRestart)GetProcAddress(hDll,"UpgradeRestart");
  1332. if (m_pfUpgradeRestart == NULL)
  1333. {
  1334. Dbg("get UpgradeRestart failed(%d)",GetLastError());
  1335. return false;
  1336. }
  1337. #endif //RVC_OS_LINUX
  1338. Dbg("have load guardian.");
  1339. if (CheckGuardianIsRun(true) > 0)
  1340. {
  1341. if (m_pfUpgradeRestart != NULL)
  1342. {
  1343. Sleep(500);
  1344. Dbg("to tell guardian framework is starting.");
  1345. int ret = m_pfUpgradeRestart(4, 0);//tell guardian framework is starting...oilyang 20150514
  1346. Dbg("feedback of framework is starting.%d", ret);
  1347. }
  1348. }
  1349. m_currentVer = "";
  1350. UpdateSiteToRuncfg();
  1351. return true;
  1352. }
  1353. void CHealthManagerEntity::SplitModuleNames(CSimpleStringA csLine, ModuleReMode eMode)
  1354. {
  1355. string str((const char*)csLine);
  1356. size_t pos = 0,nameEnd = 0;
  1357. size_t len = str.length();
  1358. while(1)
  1359. {
  1360. nameEnd = str.find(',',pos);
  1361. if (nameEnd != string::npos)
  1362. {
  1363. m_modCfgInfo[str.substr(pos,nameEnd-pos).c_str()] = eMode;
  1364. pos = nameEnd + 1;
  1365. }
  1366. else
  1367. {
  1368. if (pos < len)
  1369. m_modCfgInfo[str.substr(pos,nameEnd-pos).c_str()] = eMode;
  1370. break;
  1371. }
  1372. }
  1373. }
  1374. int CHealthManagerEntity::ConnectUps()
  1375. {
  1376. if (m_pUpsClient == NULL)
  1377. {
  1378. m_pUpsClient = new UpsService_ClientBase(this);
  1379. ErrorCodeEnum eErrConn = m_pUpsClient->Connect();
  1380. if (eErrConn != Error_Succeed) {
  1381. Dbg("Ups connected failed(%d).",eErrConn);
  1382. m_pUpsClient->SafeDelete();
  1383. m_pUpsClient = NULL;
  1384. }
  1385. else
  1386. {
  1387. Dbg("ups entity connected.");
  1388. UpsService_GetStatus_Req req;
  1389. UpsService_GetStatus_Ans ans;
  1390. ErrorCodeEnum eErrState = m_pUpsClient->GetStatus(req,ans,3000);
  1391. if (eErrState == Error_Succeed)
  1392. {
  1393. m_bGetUpsStateFlag = true;
  1394. Dbg("current state %d",ans.Status);
  1395. return 0;
  1396. }
  1397. else
  1398. Dbg("connect get ups state failed(%d).",eErrState);
  1399. }
  1400. }
  1401. return -1;
  1402. }
  1403. bool CHealthManagerEntity::SaveCurrentVersion()
  1404. {
  1405. CSimpleStringA csRootVer,csRunInfo,csBakFile,csVerFile;
  1406. ErrorCodeEnum eErr;
  1407. if ((eErr = GetFunction()->GetPath("RootVer",csRootVer)) != Error_Succeed)
  1408. {
  1409. LOG_TRACE("Get version path failed(%d).",eErr);
  1410. return false;
  1411. }
  1412. if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
  1413. {
  1414. Dbg("get runinfo path failed(%d)",eErr);
  1415. return false;
  1416. }
  1417. //csVerFile = csRootVer + "\\active.txt";
  1418. csBakFile = csRunInfo + "/runcfg/version.dat";
  1419. //ifstream infile(csVerFile,std::ifstream::binary);
  1420. ofstream outfile (csBakFile,std::ofstream::binary);
  1421. //infile.seekg (0,infile.end);
  1422. //long size = infile.tellg();
  1423. //infile.seekg (0,infile.beg);
  1424. CSimpleStringA csCurrVer = m_sysStaticInfo.InstallVersion.ToString();
  1425. Dbg("get current version [%s]",(LPCTSTR)csCurrVer);
  1426. int size = csCurrVer.GetLength();
  1427. char* buffer = new char[size];
  1428. ZeroMemory(buffer,size);
  1429. //infile.read (buffer,size);
  1430. memcpy(buffer,csCurrVer,size);
  1431. outfile.write (buffer,size);
  1432. delete[] buffer;
  1433. outfile.close();
  1434. //infile.close();
  1435. return true;
  1436. }
  1437. bool CHealthManagerEntity::SaveFrameStartTimeForUpgrade()
  1438. {
  1439. CSimpleStringA csRunInfo,csBakFile;
  1440. ErrorCodeEnum eErr;
  1441. if ((eErr = GetFunction()->GetPath("RunInfo",csRunInfo)) != Error_Succeed)
  1442. {
  1443. Dbg("get runinfo path failed(%d)",eErr);
  1444. return false;
  1445. }
  1446. //csVerFile = csRootVer + "\\active.txt";
  1447. csBakFile = csRunInfo + "/runcfg/starttime.dat";
  1448. //ifstream infile(csVerFile,std::ifstream::binary);
  1449. ofstream outfile (csBakFile,std::ofstream::binary);
  1450. CSystemRunInfo sysRunInfo;
  1451. GetFunction()->GetSystemRunInfo(sysRunInfo);
  1452. if (eErr != Error_Succeed)
  1453. {
  1454. Dbg("Get system run info failed(%d).",eErr);
  1455. return false;
  1456. }
  1457. CSimpleStringA csStartTime = sysRunInfo.tmStart.ToTimeString();
  1458. Dbg("get current time start [%s]",(LPCTSTR)csStartTime);
  1459. int size = csStartTime.GetLength();
  1460. char* buffer = new char[size];
  1461. ZeroMemory(buffer,size);
  1462. //infile.read (buffer,size);
  1463. memcpy(buffer,csStartTime,size);
  1464. outfile.write (buffer,size);
  1465. delete[] buffer;
  1466. outfile.close();
  1467. //infile.close();
  1468. return true;
  1469. }
  1470. bool CHealthManagerEntity::VersionRollBack(const char *pVerion)
  1471. {
  1472. CSimpleStringA csCurrVer = m_sysStaticInfo.InstallVersion.ToString();
  1473. if (_stricmp(csCurrVer,pVerion) == 0)
  1474. {
  1475. Dbg("destination version identified the current version.");
  1476. return false;
  1477. }
  1478. m_pUpgMgr = new UpgradeMgrService_ClientBase(this);
  1479. if (m_pUpgMgr == NULL)
  1480. {
  1481. Dbg("create UpgradeMgr client failed.");
  1482. return false;
  1483. }
  1484. CSmartPointer<IAsynWaitSp> pAsyncWait;
  1485. ErrorCodeEnum eErr = m_pUpgMgr->Connect(pAsyncWait);
  1486. if (eErr != Error_Succeed)
  1487. {
  1488. Dbg("connect to UpgradeMgr failed(%d)",eErr);
  1489. return false;
  1490. }
  1491. else
  1492. eErr = pAsyncWait->WaitAnswer(10000);
  1493. UpgradeMgrService_RollbackUpdate_Req req;
  1494. req.strVersion = pVerion;
  1495. UpgradeMgrService_RollbackUpdate_Ans ans;
  1496. eErr = m_pUpgMgr->RollbackUpdate(req,ans,10000);
  1497. if (eErr == Error_Succeed)
  1498. {
  1499. Dbg("version rollback doing.");
  1500. m_bVerRollback = true;
  1501. return true;
  1502. }
  1503. else
  1504. {
  1505. Dbg("UpgradeMgr rollback failed(%d)",eErr);
  1506. return false;
  1507. }
  1508. }
  1509. /*
  1510. void CHealthManagerEntity::ReadMachineDataBySyncSerivce()
  1511. {
  1512. ErrorCodeEnum eSync;
  1513. if (m_pSync == NULL)
  1514. {
  1515. m_pSync = new SyncService_ClientBase(this);
  1516. if (m_pSync != NULL)
  1517. {
  1518. ErrorCodeEnum eSync = m_pSync->Connect();
  1519. if (eSync != Error_Succeed)
  1520. {
  1521. Dbg("connect to SyncService failed %d.",eSync);
  1522. m_pSync->SafeDelete();
  1523. m_pSync = NULL;
  1524. }
  1525. }
  1526. }
  1527. else
  1528. {
  1529. SyncService_GetMachineData_Req req;
  1530. SyncService_GetMachineData_Ans ans;
  1531. req.key = "MenuChoice";
  1532. eSync = m_pSync->GetMachineData(req,ans,10000);
  1533. if (eSync == Error_Succeed)
  1534. {
  1535. m_menuChoice = ans.value;
  1536. if (m_menuPre.Compare(m_menuChoice) != 0)
  1537. {
  1538. m_menuPre = m_menuChoice;
  1539. Dbg("menu:[%s]", (LPCTSTR)m_menuChoice);
  1540. if (m_menuChoice.Compare("Main") == 0)
  1541. {
  1542. //according to yangzixiong,comment it. by oilyang 20160615
  1543. //LogEvent(Severity_Middle, LOG_EVT_USB_CONTROL_OFF, "usb off");//just for Stand2S
  1544. }
  1545. }
  1546. }
  1547. else
  1548. {
  1549. m_menuChoice = "";
  1550. }
  1551. }
  1552. }
  1553. */
  1554. int CHealthManagerEntity::UpdateSiteChangeFlag()
  1555. {
  1556. CSmartPointer<IConfigInfo> spConfig;
  1557. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
  1558. if (eErr != Error_Succeed) {
  1559. Dbg("UpdateSiteChangeFlag open run cfg file failed!");
  1560. return -1;
  1561. }
  1562. eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 1);
  1563. Dbg("Write SiteChanged 1.err[%d]",eErr);
  1564. return 0;
  1565. }
  1566. int CHealthManagerEntity::UpdateSiteToRuncfg(bool bWriteSite,bool bClearSiteFlag)
  1567. {
  1568. Dbg("bClearSiteFlag[%d]",bClearSiteFlag);
  1569. CSmartPointer<IConfigInfo> spConfig;
  1570. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
  1571. if (eErr != Error_Succeed) {
  1572. Dbg("UpdateSiteToRuncfg open run cfg file failed!");
  1573. return -1;
  1574. }
  1575. if (!bClearSiteFlag)
  1576. {
  1577. int siteChangedFlag = 0;
  1578. eErr = spConfig->ReadConfigValueInt("AboutSite", "SiteChanged", siteChangedFlag);
  1579. if (eErr == Error_Succeed)
  1580. {
  1581. if (siteChangedFlag != 0)
  1582. {
  1583. bWriteSite = false;
  1584. }
  1585. }
  1586. }
  1587. else
  1588. {
  1589. eErr = spConfig->WriteConfigValueInt("AboutSite", "SiteChanged", 0);
  1590. Dbg("UpdateSiteToRuncfg.Write Site (%d).", eErr);
  1591. }
  1592. if (bWriteSite)
  1593. {
  1594. spConfig->WriteConfigValue("AboutSite", "Site", m_sysStaticInfo.strSite);
  1595. }
  1596. return 0;
  1597. }
  1598. int CHealthManagerEntity::WriteSiteToRootIni()
  1599. {
  1600. LOG_FUNCTION();
  1601. CSmartPointer<IConfigInfo> spConfig;
  1602. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
  1603. if (eErr != Error_Succeed) {
  1604. Dbg("UpdateSiteToRuncfg open run cfg file failed!");
  1605. return -1;
  1606. }
  1607. CSimpleStringA csSite("");
  1608. eErr = spConfig->ReadConfigValue("AboutSite", "Site", csSite);
  1609. if (eErr == Error_Succeed)
  1610. {
  1611. CSimpleStringA path("");
  1612. GetFunction()->GetPath("HardwareCfg", path);
  1613. path.Append("\\");
  1614. path.Append("root.ini");
  1615. Dbg("WriteSiteToRootIni[%s]",(LPCTSTR)path);
  1616. //oiltestlinux comment the following 2 lines
  1617. //BOOL bRet = ::WritePrivateProfileStringA("Terminal", "Site", csSite, path);
  1618. //Dbg("WriteSiteToRootIni:write site bRet = %d", bRet);
  1619. }
  1620. return 0;
  1621. }
  1622. int CHealthManagerEntity::RestartIE()
  1623. {
  1624. CSimpleStringA csBrowserName = "IEBrowser";
  1625. m_bNeedToRestartIE = false;
  1626. CSmartPointer<IAsynWaitSp> spWait;
  1627. CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = GetFunction().ConvertCase<IEntityFunctionPrivilege>();
  1628. if (m_fsm.IsCutIEBrowser())
  1629. csBrowserName = "Chromium";
  1630. ErrorCodeEnum eErr = pFuncPrivilege->TerminateEntity(csBrowserName.GetData(), spWait);
  1631. if (eErr == Error_Succeed)
  1632. {
  1633. if (spWait != NULL)
  1634. spWait->WaitAnswer(10000);
  1635. }
  1636. else
  1637. Dbg("TerminateEntity browser failed.%d", eErr);
  1638. eErr = pFuncPrivilege->StartEntity(csBrowserName.GetData(), "", spWait);
  1639. if (eErr == Error_Succeed)
  1640. {
  1641. if (spWait != NULL)
  1642. eErr = spWait->WaitAnswer(15000);
  1643. }
  1644. else
  1645. {
  1646. Dbg("Start browser failed(%d).", eErr);
  1647. }
  1648. return 0;
  1649. }
  1650. void CHealthManagerEntity::QueryHardwareInfo(SpReqAnsContext<HealthManagerService_QueryHardwareInfo_Req, HealthManagerService_QueryHardwareInfo_Ans>::Pointer ctx)
  1651. {
  1652. CSystemStaticInfo info;
  1653. GetFunction()->GetSystemStaticInfo(info);
  1654. NetworkAddressesList macAddrs;
  1655. NetworkAddressesList ipAddrs;
  1656. SP::Module::Net::GetINETMacAddresses(macAddrs, ipAddrs);
  1657. ctx->Ans.ip = ipAddrs;
  1658. ctx->Ans.mac = macAddrs;
  1659. ctx->Ans.machineType = info.strMachineType;
  1660. ctx->Ans.site = info.strSite;
  1661. ctx->Ans.terminalNo = info.strTerminalID;
  1662. ctx->Ans.termLimit = __ReadCenterConfigStr("TermLimitSwitch", "IEBrowser");
  1663. ctx->Ans.termVersion = info.InstallVersion.ToString();
  1664. ctx->Answer(Error_Succeed);
  1665. }
  1666. void CHealthManagerEntity::ReadCenterConfigStr(SpReqAnsContext<HealthManagerService_ReadCenterConfigStr_Req, HealthManagerService_ReadCenterConfigStr_Ans>::Pointer ctx)
  1667. {
  1668. ctx->Ans.value = __ReadCenterConfigStr(ctx->Req.key, ctx->Req.entity);
  1669. ctx->Answer(Error_Succeed);
  1670. }
  1671. void CHealthManagerEntity::ControlTerminalLife(
  1672. SpReqAnsContext<HealthManagerService_ControlTerminalLife_Req, HealthManagerService_ControlTerminalLife_Ans>::Pointer ctx)
  1673. {
  1674. //< !--1:restart app; 2: shutdown app; 3:shutdown app and guardian; 4: restart pc; 5: poweroff; 6:poweroff with ups-- >
  1675. int retCode = 0;
  1676. ErrorCodeEnum result = Error_Unexpect;
  1677. switch (ctx->Req.cmdType) {
  1678. case 1:
  1679. retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_Framework);
  1680. result = Error_Succeed;
  1681. break;
  1682. case 2:
  1683. retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_Unknown, RebootWay_Framework);
  1684. result = Error_Succeed;
  1685. break;
  1686. case 3:
  1687. retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_Framework);
  1688. result = Error_Succeed;
  1689. break;
  1690. case 4:
  1691. retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_OS);
  1692. result = Error_Succeed;
  1693. break;
  1694. case 5:
  1695. retCode = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_OS);
  1696. result = Error_Succeed;
  1697. break;
  1698. case 6:
  1699. if(ctx->Req.reserved1 > 0 && ctx->Req.reserved2 > 0)
  1700. result = SystemShutdownThroughUPS(ctx->Req.reserved1, ctx->Req.reserved2);
  1701. else
  1702. result = SystemShutdownThroughUPS();
  1703. if (result == Error_Succeed) {
  1704. Sleep(300);
  1705. m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_OS);
  1706. }
  1707. break;
  1708. default:
  1709. result = Error_Param;
  1710. break;
  1711. }
  1712. ctx->Ans.retCode = retCode;
  1713. ctx->Answer(result);
  1714. }
  1715. CSimpleStringA CHealthManagerEntity::__ReadCenterConfigStr(CSimpleStringA key, CSimpleStringA entityName = "")
  1716. {
  1717. CSimpleStringA str = "";
  1718. CSmartPointer<IConfigInfo> spCerConfig;
  1719. ErrorCodeEnum err = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig);
  1720. if (entityName == "")
  1721. {
  1722. spCerConfig->ReadConfigValue("IEBrowser", key, str);
  1723. }
  1724. else
  1725. {
  1726. spCerConfig->ReadConfigValue(entityName, key, str);
  1727. }
  1728. return str;
  1729. }
  1730. void CHealthManagerEntity::GetINETMacAddresses(NetworkAddressesList &macList, NetworkAddressesList &ipList)
  1731. {
  1732. #ifdef RVC_OS_WIN
  1733. PIP_ADAPTER_ADDRESSES pAddresses = NULL;
  1734. ULONG family = AF_INET;
  1735. ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
  1736. ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
  1737. Dbg("GetINETMacAddresses");
  1738. // Make an initial call to GetAdaptersAddresses to get the
  1739. // size needed into the outBufLen variable
  1740. if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW)
  1741. {
  1742. pAddresses = static_cast<PIP_ADAPTER_ADDRESSES>(HeapAlloc(GetProcessHeap(), 0, outBufLen));
  1743. }
  1744. Dbg("GetAdaptersAddresses 1");
  1745. if (NULL == pAddresses)
  1746. {
  1747. Dbg("pAddresses = NULL");
  1748. return;
  1749. }
  1750. // _ASSERT( pAddresses );
  1751. // Make a second call to GetAdapters Addresses to get the
  1752. // actual data we want
  1753. DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
  1754. Dbg("GetAdaptersAddresses 2");
  1755. /* MACAddresses vAddress;*/
  1756. if (dwRetVal != ERROR_SUCCESS)
  1757. {
  1758. Dbg("dwRetVal = %d", dwRetVal);
  1759. return;
  1760. }
  1761. PIP_ADAPTER_ADDRESSES pFirst = pAddresses;
  1762. while (pAddresses)
  1763. {
  1764. if (pAddresses->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET &&
  1765. pAddresses->OperStatus == IfOperStatusUp &&
  1766. pAddresses->IfType != IF_TYPE_SOFTWARE_LOOPBACK)
  1767. {
  1768. Dbg("in while if 1");
  1769. BYTE* pa = pAddresses->PhysicalAddress;
  1770. if (!pa)
  1771. {
  1772. pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
  1773. continue;
  1774. }
  1775. Dbg("in while if 2");
  1776. char bAddressBytes[MACSESION];
  1777. int bAddressInt[MACSESION];
  1778. memset(bAddressBytes, 0, MACSESION);
  1779. size_t nAddressSize = pAddresses->PhysicalAddressLength;
  1780. memcpy(bAddressBytes, pa, (nAddressSize < MACSESION ? nAddressSize : MACSESION));
  1781. char CommarSeperatedAddress[MACSESION * 3] = { 0 };
  1782. for (int i = 0; i < MACSESION; ++i)
  1783. {
  1784. bAddressInt[i] = bAddressBytes[i];
  1785. bAddressInt[i] &= 0x000000ff; // avoid "ff" leading bytes when "char" is lager then 0x7f
  1786. }
  1787. Dbg("in while if 3");
  1788. sprintf(CommarSeperatedAddress, "%02x:%02x:%02x:%02x:%02x:%02x",
  1789. bAddressInt[0],
  1790. bAddressInt[1],
  1791. bAddressInt[2],
  1792. bAddressInt[3],
  1793. bAddressInt[4],
  1794. bAddressInt[5]); // Should use scl::FormatString inside
  1795. CSimpleStringA tmpmac = CSimpleStringA(CommarSeperatedAddress);
  1796. Dbg("in while if 4");
  1797. macList.Append(&tmpmac, 0, 1);
  1798. // macList.push_back( std::string( CommarSeperatedAddress ) );
  1799. Dbg("Description : %s", pAddresses->Description);
  1800. Dbg("OperStatus : %d, IfType = %d, mac = %s", pAddresses->OperStatus, pAddresses->IfType, CommarSeperatedAddress);
  1801. sockaddr_in *sa_in = (sockaddr_in *)pAddresses->FirstUnicastAddress->Address.lpSockaddr;
  1802. char buf_addr[100] = { 0 };
  1803. CSimpleStringA tmpip = CSimpleStringA(inet_ntop(AF_INET, &(sa_in->sin_addr), buf_addr, 100));
  1804. ipList.Append(&tmpip, 0, 1);
  1805. }
  1806. pAddresses = pAddresses->Next ? pAddresses->Next : NULL;
  1807. }
  1808. HeapFree(GetProcessHeap(), 0, pFirst);
  1809. return;
  1810. #else
  1811. return;//oiltestlinux
  1812. #endif //RVC_OS_WIN
  1813. }
  1814. void CHealthManagerEntity::OnLog(const CAutoArray<CUUID> &SubIDs, const CUUID nLogID, const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
  1815. const DWORD dwSysError, const DWORD dwUserCode, const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
  1816. const CAutoArray<DWORD> &Param, const char *pszEntityName, const char *pszModuleName, const char *pszMessage, const linkContext& pLinkInfo)
  1817. {
  1818. // MessageBoxA(0,0,0,0);
  1819. //if (dwUserCode != LOG_EVT_HEARTBEAT_UN_CONNECTED)
  1820. // Dbg("user code:%x,from entity:%s",dwUserCode,pszEntityName);
  1821. switch (dwUserCode) {
  1822. case EVENT_RESTART_SHELL:
  1823. case Event_Req_Framework_Restart: //case framework restart after upgrade
  1824. case EVENT_CONSOLE_REQ_RESTART_SHELL:
  1825. case Event_Req_Framework_Rollback://case after rollback
  1826. //according to zl commented the following line 20150828
  1827. //case EVENT_UKEY_CUSTOMER_MANANAGER_SYS_EXIT:
  1828. case LOG_EVT_IEBROWSER_RESET_SITE_RESTART: //重设root.ini的site,重启框架
  1829. case LOG_EVT_HEARTBEAT_UN_CONNECTED: //重设site后框架分行服务连接不上,再次重启回退到前一版本
  1830. case Event_Req_Framework_No_Upgrade_Restart://升级请求重启框架(体系外升级等等)
  1831. {
  1832. Dbg("user code:%x,from entity:%s", dwUserCode, pszEntityName);
  1833. int iCheckGuardian = CheckGuardianIsRun();
  1834. if (iCheckGuardian < 0)
  1835. {
  1836. bool bStartGuardian = StartGuardian();
  1837. if (!bStartGuardian)
  1838. {
  1839. Dbg("Before restart frame,start guardian failed.");
  1840. break;
  1841. }
  1842. Dbg("Before restart frame,start guardian suc.");
  1843. Sleep(2000);
  1844. }
  1845. if (dwUserCode == Event_Req_Framework_Restart)
  1846. {
  1847. SaveCurrentVersion();
  1848. SaveFrameStartTimeForUpgrade();
  1849. if (CheckGuardianIsRun(true) > 0)
  1850. {
  1851. if (m_pfUpgradeRestart != NULL)
  1852. {
  1853. ErrorCodeEnum eErr = Error_Unexpect;
  1854. int ret = m_pfUpgradeRestart(1, 0);
  1855. Dbg("to tell guardian framework is restarting.%d", ret);
  1856. }
  1857. }
  1858. m_eRebootTrigger = RebootTrigger_FrameUpgrade;
  1859. }
  1860. else if (dwUserCode == Event_Req_Framework_Rollback)
  1861. {
  1862. Dbg("version rollback succeed.to restart framework");
  1863. m_bVerRollback = false;
  1864. m_eRebootTrigger = RebootTrigger_RollBack;
  1865. }
  1866. else if (dwUserCode == LOG_EVT_IEBROWSER_RESET_SITE_RESTART)
  1867. {
  1868. //oilyang@20211021 comment the following line
  1869. //can't see why update this ,as browser haven't changed site
  1870. //UpdateSiteChangeFlag();
  1871. m_eRebootTrigger = RebootTrigger_Resource;
  1872. }
  1873. else if (dwUserCode == LOG_EVT_HEARTBEAT_UN_CONNECTED)
  1874. {
  1875. CSmartPointer<IConfigInfo> spConfig;
  1876. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfig);
  1877. int tmpFlag = 99;
  1878. spConfig->ReadConfigValueInt("AboutSite", "SiteChanged", tmpFlag);
  1879. if (tmpFlag != 1)
  1880. {
  1881. //Dbg("heartbeat can't connect(normal).no need to rollback.");
  1882. break;
  1883. }
  1884. WriteSiteToRootIni();
  1885. UpdateSiteToRuncfg(false, true);
  1886. }
  1887. else if (dwUserCode == Event_Req_Framework_No_Upgrade_Restart)
  1888. {
  1889. Dbg("Event_Req_Framework_No_Upgrade_Restart.");
  1890. }
  1891. m_eRebootWay = RebootWay_Framework;
  1892. BOOL bRet = FrameworkShutdown();
  1893. Dbg("framework shutdown [%d]", bRet);
  1894. }
  1895. break;
  1896. case EVENT_CONSOLE_REQ_SHUTDOWN_SHELL:
  1897. {
  1898. BOOL bRet = FrameworkShutdown(false);
  1899. Dbg("framework shutdown from console [%d]", bRet);
  1900. }
  1901. break;
  1902. case EVENT_RESTART_MACHINE:
  1903. case Event_Req_OS_Restart://case os restart after outside update
  1904. case EVENT_CONSOLE_REQ_RESTART_POWER:
  1905. {
  1906. if (dwUserCode == Event_Req_OS_Restart)
  1907. m_eRebootTrigger = RebootTrigger_OSUpgrade;
  1908. else
  1909. m_eRebootTrigger = RebootTrigger_Resource;
  1910. m_eRebootWay = RebootWay_Power;
  1911. BOOL bRet = SystemRestart(false,true);
  1912. Dbg("os restart [%d]", bRet);
  1913. }
  1914. break;
  1915. case LOG_EVT_IEBROWSER_RESTART_MACHINE:
  1916. {
  1917. m_eRebootTrigger = RebootTrigger_Resource;
  1918. m_eRebootWay = RebootWay_Power;
  1919. BOOL bRet = SystemRestart(false, true,true);
  1920. Dbg("machine restart now [%d]", bRet);
  1921. break;
  1922. }
  1923. case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE:
  1924. {
  1925. Dbg("User descktop said to shutdown machine now.");
  1926. SystemShutdown();
  1927. break;
  1928. }
  1929. case LOG_EVT_IEBROWSER_SHUTDOWN_MACHINE_THROUGH_UPS:
  1930. {
  1931. Dbg("User descktop said to shutdown machine now through UPS");
  1932. if (Error_Succeed == SystemShutdownThroughUPS()) {
  1933. ///**TODO(Gifur@7/16/2021): 主动跟监护进程做一次握手,避免在关机过程中提前重启了框架 */
  1934. Sleep(300);
  1935. m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_DeadForever, RebootWay_Framework);
  1936. }
  1937. break;
  1938. }
  1939. case LOG_EVT_SELFCHECK_OS_RESTART:
  1940. Dbg("selfcheck to wait chance to restart(os) pc.");
  1941. m_eRebootTrigger = RebootTrigger_RunExcepition;
  1942. m_eRebootWay = RebootWay_Power;
  1943. m_bWaitRestartPC = true;
  1944. break;
  1945. case LOG_EVT_SELFCHECK_POWER_RESTART:
  1946. Dbg("selfcheck to wait chance to restart(power) pc.");
  1947. m_eRebootTrigger = RebootTrigger_RunExcepition;
  1948. m_eRebootWay = RebootWay_Power;
  1949. m_bWaitRestartPC = true;
  1950. break;
  1951. case EVENT_ACCESSAUTH_SUCCEED:
  1952. Dbg("access auth succeed.");
  1953. m_fsm.SetAccessAuth();
  1954. m_bAccessSuc = true;
  1955. m_bNeedAuthRetry = false;
  1956. m_bNeedGuardianRestart = true;
  1957. break;
  1958. //oilyang@20210331 distinguish reasons of accessauth failed to decide what to do next
  1959. //case EVENT_ACCESSAUTH_FAILED:
  1960. //case EVENT_ACCESSAUTH_TIMEOUT:
  1961. case CONTROL_ACCESSAUTH_NORETRY_NORESTART:
  1962. case CONTROL_ACCESSAUTH_RETRY_NORESTART:
  1963. case CONTROL_ACCESSAUTH_RETRY_RESTART:
  1964. case CONTROL_ACCESSAUTH_UNKNOWN:
  1965. {
  1966. if (dwUserCode == CONTROL_ACCESSAUTH_NORETRY_NORESTART) {
  1967. Dbg("no retry,no restart.");
  1968. m_bNeedAuthRetry = false;
  1969. m_bNeedGuardianRestart = false;
  1970. }else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_NORESTART) {
  1971. Dbg("retry,no restart.");
  1972. m_bNeedAuthRetry = true;
  1973. m_bNeedGuardianRestart = false;
  1974. }
  1975. else if (dwUserCode == CONTROL_ACCESSAUTH_RETRY_RESTART) {
  1976. Dbg("retry,restart.");
  1977. m_bNeedAuthRetry = true;
  1978. m_bNeedGuardianRestart = true;
  1979. }
  1980. else if (dwUserCode == CONTROL_ACCESSAUTH_UNKNOWN) {
  1981. Dbg("unkown access failed.no retry,restart.");
  1982. m_bNeedAuthRetry = false;
  1983. m_bNeedGuardianRestart = true;
  1984. }
  1985. m_fsm.SetAccessFailedFlag();
  1986. //oilyang@20210929
  1987. GetFunction()->SetSysVar("TerminalStage", "C");
  1988. Dbg("access auth failed %d.", dwUserCode);
  1989. m_bAccessSuc = false;
  1990. if (m_bNeedAuthRetry)
  1991. {
  1992. Dbg("retry AccessAuth");
  1993. m_fsm.ToReAccessAuth();
  1994. }
  1995. }
  1996. break;
  1997. case EVENT_MOD_INITIALIZER_MK_LOADED:
  1998. Dbg("init succeed.");
  1999. m_fsm.SetInitSucFlag();
  2000. break;
  2001. case EVENT_MOD_INITIALIZER_MK_FAILED:
  2002. Dbg("init failed.");
  2003. m_fsm.SetInitFailFlag();
  2004. break;
  2005. case EVENT_MOD_FACE_OPENCV_ERROR:
  2006. RestartModule("FaceTracking");
  2007. break;
  2008. case LOG_EVT_INC_VERSION_ROLLBACK:
  2009. Dbg("version to be rollback to %s", pszMessage);
  2010. if (!m_bVerRollback)
  2011. {
  2012. Dbg("rollbacking");
  2013. VersionRollBack(pszMessage);
  2014. }
  2015. break;
  2016. case LOG_EVT_SELFCHECK_TOKEN_KEEPER_LOST:
  2017. {
  2018. ErrorCodeEnum eErr = RestartModule("TokenKeeper");
  2019. Dbg("to re accessauth");
  2020. m_fsm.ToReAccessAuth();
  2021. }
  2022. break;
  2023. case EVENT_UKEY_CUSTOMER_MANANAGER_SYS_ENTER:
  2024. {
  2025. Dbg("to enter customer manager system.");
  2026. m_fsm.SetCustomerMngerState(CM_ENTER);//set enter state
  2027. FSMEvent *pEvt = new FSMEvent(USER_EVT_ENTER_CUSTOMER_MANAGER);
  2028. m_fsm.PostEventFIFO(pEvt);
  2029. }
  2030. break;
  2031. case LOG_EVT_HEARTBEAT_CONNECTED:
  2032. UpdateSiteToRuncfg(true, true);
  2033. break;
  2034. case EVENT_MOD_CENTERSETTING_RVCWEBVER_CHANGE:
  2035. m_bNeedToRestartIE = true;
  2036. break;
  2037. //case EVENT_UKEY_NOT_ENTER_CUSTOMER_MANANAGER:
  2038. // {
  2039. // Dbg("NOT to enter customer manager system.");
  2040. // m_fsm.SetCustomerMngerState(CM_NOT_ENTER);//set enter state
  2041. // }
  2042. // break;
  2043. case EVENT_MOD_RELEASESIP_TIMEOUT:
  2044. Dbg("RELEASESIP_TIMEOUT.");
  2045. RestartModule("SIPPhone");
  2046. break;
  2047. case LOG_EVT_SELFCHECK_IEBROWSER_IDLE:
  2048. //IE重启之后,重置是否进入主页变量
  2049. Dbg("Browser(IE/Chromuim) to idle.");
  2050. LogWarn(Severity_Low, Error_Unexpect, HealthManager_UserErrorCode_Receive_Browser_Idle
  2051. , "Browser(IE/Chromuim) to idle.");
  2052. m_bBrowserIdleFirst = true;
  2053. break;
  2054. case LOG_EVT_INC_TRADE_MANAGER_NORMAL:
  2055. case LOG_EVT_INC_TRADE_MANAGER_ON:
  2056. case LOG_EVT_INC_TRADE_MANAGER_OFF:
  2057. {
  2058. TradeManage tm;
  2059. if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_NORMAL)
  2060. tm.op = 0;
  2061. else if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_ON)
  2062. tm.op = 1;
  2063. else if (dwUserCode == LOG_EVT_INC_TRADE_MANAGER_OFF)
  2064. tm.op = 2;
  2065. tm.time = pszMessage;
  2066. Dbg("trademanager:%d,%s",tm.op,(const char*)tm.time);
  2067. SpSendBroadcast(GetFunction(), SP_MSG_OF(TradeManage), SP_MSG_SIG_OF(TradeManage), tm);
  2068. }
  2069. case LOG_EVT_INC_DEVICE_LOCK_ON:
  2070. case LOG_EVT_INC_DEVICE_UNLOCK:
  2071. case LOG_EVT_INC_DEVICE_KICK_OFF:
  2072. {
  2073. TerminalManager tm;
  2074. if (dwUserCode == LOG_EVT_INC_DEVICE_LOCK_ON)
  2075. tm.op = 0;
  2076. else if (dwUserCode == LOG_EVT_INC_DEVICE_UNLOCK)
  2077. {
  2078. if (m_bAccessSuc)
  2079. tm.op = 1;
  2080. else
  2081. tm.op = 99;//oilyang@20170818 according to xingzichen
  2082. }
  2083. else if (dwUserCode == LOG_EVT_INC_DEVICE_KICK_OFF)
  2084. tm.op = 2;
  2085. Dbg("terminal manager:%d", tm.op);
  2086. SpSendBroadcast(GetFunction(), SP_MSG_OF(TerminalManager), SP_MSG_SIG_OF(TerminalManager), tm);
  2087. }
  2088. break;
  2089. case LOG_EVT_SYSTMECUSTOM_START_ACCESSAUTH:
  2090. Dbg("receive md5 ok event.");
  2091. m_fsm.SetMD5OK(1);
  2092. break;
  2093. case LOG_EVT_PINPAD_OPEN_SUC:
  2094. //oilyang@20210421 if have called AccessAuth before,we need to recall AccessAuth
  2095. m_fsm.JudgeIfNeedInitFWB();
  2096. if (m_fsm.QueryHaveAuthEver())
  2097. {
  2098. Dbg("receive pinpad open success event.");
  2099. m_fsm.DeviceReConnect();
  2100. }
  2101. case LOG_EVT_CARDSWIPER_DISCONNECTED:
  2102. //oilyang@20210425 if device disconnected,we need to recall AccessAuth
  2103. //RestartModule("CardSwiper");
  2104. //RestartModule("PinPad");
  2105. if (m_fsm.QueryHaveAuthEver())
  2106. {
  2107. Dbg("receive device disconnected event.");
  2108. m_fsm.DeviceReConnect();
  2109. }
  2110. default:
  2111. //Dbg("unknown event(%d)...", dwUserCode);
  2112. return;
  2113. }
  2114. }
  2115. void CHealthManagerEntity::OnSysVarEvent(const char *pszKey, const char *pszValue, const char *pszOldValue, const char *pszEntityName)
  2116. {
  2117. if ((_strnicmp(pszKey, "UIState", strlen("UIState")) == 0))
  2118. {
  2119. if (_strnicmp(pszValue, "M", strlen("M")) == 0)
  2120. {
  2121. CSmartPointer<IConfigInfo> spConfigRun;
  2122. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2123. m_bInMainPage = true;
  2124. if (!m_bHaveThrowMainPage)
  2125. {
  2126. m_bHaveThrowMainPage = true;
  2127. Dbg("the first enter main page from HealthManger started.");
  2128. LogEvent(Severity_Low, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START
  2129. , "first enter main page from HealthManager started.");
  2130. CSmartPointer<IConfigInfo> spConfigShell;
  2131. GetFunction()->OpenConfig(Config_Shell, spConfigShell);
  2132. CSimpleStringA shellVersion(true);
  2133. spConfigShell->ReadConfigValue("Main", "SoftwareVersion", shellVersion);
  2134. LogWarn(Severity_Low, Error_Unexpect,LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE_FROM_HEALTH_START
  2135. , CSimpleStringA::Format("First enter main page from HealthManger started: %s, test: %s",
  2136. m_sysStaticInfo.InstallVersion.ToString().GetData(), shellVersion.GetData()));
  2137. }
  2138. if (m_bBrowserIdleFirst)
  2139. {
  2140. Dbg("the first enter main page from browser started.");
  2141. m_bBrowserIdleFirst = false;
  2142. m_bEnterMainPageEver = true;
  2143. LogEvent(Severity_Low, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE, "enter main page");
  2144. LogWarn(Severity_Low, Error_Unexpect, LOG_EVT_HEALTH_FIRST_ENTER_MAINPADE,
  2145. CSimpleStringA::Format("first enter main page from browser started: %s", m_sysStaticInfo.InstallVersion.ToString().GetData()));
  2146. spConfigRun->WriteConfigValueInt("Run", "UpgradeRestartTimes", 0);
  2147. Dbg("As have been in main page,reset UpgradeRestartTimes.");
  2148. }
  2149. }
  2150. else
  2151. m_bInMainPage = false;
  2152. }
  2153. }
  2154. void CHealthManagerEntity::OnBroadcastEvent(CUUID SubID, const char *pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer)
  2155. {
  2156. #if defined(RVC_OS_WIN)
  2157. if (_strnicmp(pszEntityName, "CardSwiper", strlen("CardSwiper")) == 0) {
  2158. if (dwMessageSignature == eMsgSig_ConnectStatus) {
  2159. CSimpleStringA tmpDevSN("");
  2160. GetFunction()->GetSysVar("FWBDevSN", tmpDevSN);
  2161. if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2) {
  2162. Dbg("This is fwb device.no need to reconnect here.");
  2163. return;
  2164. }
  2165. CardSwiper::ConnectStatus cs;
  2166. SpBuffer2Object(Buffer, cs);
  2167. if (cs.status == 0) {
  2168. if (m_connectStatus == 1) {
  2169. m_connectStatus = 0;
  2170. }
  2171. } else if (cs.status == 1) {
  2172. if (m_connectStatus == 0) {
  2173. m_connectStatus = 1;
  2174. m_fsm.DeviceReConnect();
  2175. }
  2176. }
  2177. }
  2178. }
  2179. #endif //RVC_OS_WIN
  2180. }
  2181. void CHealthManagerEntity::ControlEntityLife(SpReqAnsContext<HealthManagerService_ControlEntityLife_Req, HealthManagerService_ControlEntityLife_Ans>::Pointer ctx)
  2182. {
  2183. ErrorCodeEnum result(Error_Succeed);
  2184. ErrorCodeEnum tmpResult(Error_Succeed);
  2185. CSimpleStringA tmpMsg(true);
  2186. if (ctx->Req.devId == 0 && ctx->Req.entityName.IsNullOrEmpty()) {
  2187. result = Error_Param;
  2188. } else {
  2189. if (ctx->Req.entityName.IsNullOrEmpty()) {
  2190. ///**TODO(Gifur@10/22/2021): */
  2191. result = Error_NotImpl;
  2192. } else {
  2193. tmpResult = DealSpecifiedEntity((DealType)ctx->Req.option, ctx->Req.entityName, ctx->Req.param, ctx->Req.force, tmpMsg);
  2194. }
  2195. }
  2196. ctx->Ans.result = tmpResult;
  2197. ctx->Ans.msg = tmpMsg;
  2198. ctx->Answer(result);
  2199. }
  2200. void CHealthManagerEntity::Gateway(SpReqAnsContext<HealthManagerService_Gateway_Req, HealthManagerService_Gateway_Ans>::Pointer ctx)
  2201. {
  2202. ErrorCodeEnum result(Error_Succeed);
  2203. ErrorCodeEnum tmpResult(Error_Succeed);
  2204. CSimpleStringA tmpMsg(true);
  2205. if (ctx->Req.type != 1) {
  2206. result = Error_NotSupport;
  2207. } else {
  2208. if (m_fConfigMode) {
  2209. result = Error_InvalidState;
  2210. } else {
  2211. CSimpleStringA shellScriptPath;
  2212. GetFunction()->GetPath("Base", shellScriptPath);
  2213. shellScriptPath += SPLIT_SLASH_STR;
  2214. shellScriptPath += "res" SPLIT_SLASH_STR "RunScript" SPLIT_SLASH_STR "startSettings.sh";
  2215. if (!ExistsFileA(shellScriptPath)) {
  2216. tmpResult = Error_NotExist;
  2217. tmpMsg = CSimpleStringA::Format("%s 文件不存在", shellScriptPath.GetData());
  2218. } else {
  2219. char app[MAX_PATH] = { '\0' };
  2220. tk_process_t* process = NULL;
  2221. tk_process_option_t option;
  2222. option.exit_cb = NULL;
  2223. option.file = NULL;
  2224. option.flags = 0;
  2225. sprintf(app, "bash %s", shellScriptPath.GetData());
  2226. option.params = app;
  2227. const int res = process_spawn(&option, &process);
  2228. if (0 == res) {
  2229. FREE(process);
  2230. Dbg("execute {%s} suc", shellScriptPath.GetData());
  2231. tmpMsg = shellScriptPath;
  2232. } else {
  2233. tmpResult = (ErrorCodeEnum)res;
  2234. tmpMsg = CSimpleStringA::Format("执行文件 %s 失败", shellScriptPath.GetData());
  2235. }
  2236. }
  2237. }
  2238. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_HEALTH_GATEWAY_CMD,
  2239. CSimpleStringA::Format("GateWay: %s", tmpMsg.GetData()));
  2240. }
  2241. ctx->Ans.result = tmpResult;
  2242. ctx->Ans.msg = tmpMsg;
  2243. ctx->Answer(result);
  2244. }
  2245. ErrorCodeEnum CHealthManagerEntity::GetTmpRootFilePath(CSimpleStringA& rootPath, CSimpleStringA& rootTmpPath, CSimpleStringA& rootBackPath)
  2246. {
  2247. CSimpleStringA strRootCfgPath;
  2248. ErrorCodeEnum ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath);
  2249. rootPath = strRootCfgPath;
  2250. rootPath += SPLIT_SLASH_STR;
  2251. rootPath += "root.ini";
  2252. rootTmpPath = rootPath + ".tmp";
  2253. SYSTEMTIME curTime = CSmallDateTime::GetNow().ToSystemTime();
  2254. CSimpleStringA strBackupFileSuffix = CSimpleStringA::Format(".bak%04d%02d%02d%02d%02d%02d%03d",
  2255. curTime.wYear, curTime.wMonth, curTime.wDay,curTime.wHour, curTime.wMinute, curTime.wSecond, curTime.wMilliseconds);
  2256. rootBackPath = rootPath + strBackupFileSuffix;
  2257. return ec;
  2258. }
  2259. void CHealthManagerEntity::RecordInstallBeginTimeStamp(const CSimpleString& strTimeStamp, BOOL forceReset)
  2260. {
  2261. if (!forceReset) {
  2262. CSimpleStringA strReserved(true);
  2263. const ErrorCodeEnum rc = GetInstallBeginTimeStamp(strReserved);
  2264. if (!strReserved.IsNullOrEmpty()) {
  2265. return;
  2266. }
  2267. }
  2268. CSmartPointer<IConfigInfo> pConfig;
  2269. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2270. if (strTimeStamp.IsNullOrEmpty()) {
  2271. pConfig->WriteConfigValue("TerminalDeploy", "StartTimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  2272. } else {
  2273. pConfig->WriteConfigValue("TerminalDeploy", "StartTimeStamp", strTimeStamp);
  2274. }
  2275. }
  2276. ErrorCodeEnum CHealthManagerEntity::GetInstallBeginTimeStamp(CSimpleString& strTimeStamp)
  2277. {
  2278. CSmartPointer<IConfigInfo> pConfig;
  2279. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2280. CSimpleStringA strValue(true);
  2281. pConfig->ReadConfigValue("TerminalDeploy", "StartTimeStamp", strValue);
  2282. if (strValue.IsNullOrEmpty()) {
  2283. return Error_DataCheck;
  2284. }
  2285. strTimeStamp = strValue;
  2286. return Error_Succeed;
  2287. }
  2288. ErrorCodeEnum CHealthManagerEntity::GetGuidePageUrlWithStep(int whichStep, CSimpleStringA& strUrl)
  2289. {
  2290. strUrl.Clear();
  2291. CSimpleStringA pagePath;
  2292. ErrorCodeEnum ec = GetFunction()->GetPath("Base", pagePath);
  2293. pagePath.Append(SPLIT_SLASH_STR "res" SPLIT_SLASH_STR "ManagerDesktop" SPLIT_SLASH_STR "guide.html");
  2294. if (whichStep > 0) {
  2295. CSimpleStringA terminalNo;
  2296. CSimpleStringA vendorType;
  2297. CSimpleStringA serverIP;
  2298. do {
  2299. CSmartPointer<IConfigInfo> pConfig;
  2300. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2301. const ErrorCodeEnum ec0 = pConfig->ReadConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
  2302. const ErrorCodeEnum ec1 = pConfig->ReadConfigValue("TerminalDeploy", "Manufacturer", vendorType);
  2303. const ErrorCodeEnum ec2 = pConfig->ReadConfigValue("TerminalDeploy", "ServerIP", serverIP);
  2304. Dbg("read step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
  2305. } while (false);
  2306. pagePath = CSimpleStringA::Format("%s?page=%d", pagePath.GetData(), whichStep);
  2307. bool prefix(true);
  2308. if (!terminalNo.IsNullOrEmpty() || !vendorType.IsNullOrEmpty() || !serverIP.IsNullOrEmpty()) {
  2309. CSimpleStringA strSearch(true);
  2310. if (!terminalNo.IsNullOrEmpty()) {
  2311. if (prefix) strSearch += "&";
  2312. strSearch += CSimpleStringA("terminalno=") + terminalNo;
  2313. prefix = true;
  2314. }
  2315. if (!vendorType.IsNullOrEmpty()) {
  2316. if (prefix) strSearch += "&";
  2317. strSearch += CSimpleStringA("vendor=") + vendorType;
  2318. prefix = true;
  2319. }
  2320. if (!serverIP.IsNullOrEmpty()) {
  2321. if (prefix) strSearch += "&";
  2322. strSearch += CSimpleStringA("ip=") + serverIP;
  2323. prefix = true;
  2324. }
  2325. pagePath += strSearch;
  2326. }
  2327. }
  2328. strUrl = CSimpleStringA("file:///") + pagePath + CSimpleStringA("");
  2329. return ec;
  2330. }
  2331. namespace
  2332. {
  2333. ErrorCodeEnum SplitAdapterFileName(CSimpleStringA strFileName, CAutoArray<CSimpleStringA>& values)
  2334. {
  2335. #ifdef RVC_OS_WIN
  2336. CSimpleStringA strPrefix("");
  2337. CSimpleStringA strSuffix(".dll");
  2338. #else
  2339. CSimpleStringA strPrefix("lib");
  2340. CSimpleStringA strSuffix(".so");
  2341. #endif //RVC_OS_WIN
  2342. if (strFileName.GetLength() < strPrefix.GetLength() + strSuffix.GetLength()) {
  2343. return Error_Param;
  2344. }
  2345. CSimpleStringA pureAdapterName = strFileName.SubString(
  2346. strPrefix.GetLength(), strFileName.GetLength() - strPrefix.GetLength() - strSuffix.GetLength());
  2347. values = pureAdapterName.Split('.');
  2348. if (values.GetCount() != 4) {
  2349. return Error_DataCheck;
  2350. }
  2351. return Error_Succeed;
  2352. }
  2353. }
  2354. ErrorCodeEnum CHealthManagerEntity::TellChromiumOpenGuidePage(const CSimpleStringA& pageUrl)
  2355. {
  2356. ErrorCodeEnum result(Error_Succeed);
  2357. auto pClient = new ChromiumSrv_ClientBase(this);
  2358. result = pClient->Connect();
  2359. if (result == Error_Succeed) {
  2360. ChromiumSrv_OpenBrowser_Req req;
  2361. ChromiumSrv_OpenBrowser_Ans ans;
  2362. req.mainUrl = pageUrl;
  2363. req.viceUrl = "";
  2364. req.exclusiveMode = true;
  2365. req.type = 0;
  2366. result = pClient->OpenBrowser(req, ans, 10000);
  2367. if (result == Error_Succeed) {
  2368. Dbg("Request Chromium::OpenBrowser succ!");
  2369. } else {
  2370. Dbg("Request Chromium::OpenBrowser failed: %s", SpStrError(result));
  2371. }
  2372. pClient->GetFunction()->CloseSession();
  2373. } else {
  2374. pClient->SafeDelete();
  2375. Dbg("Connect to Chromium entity failed: %s", SpStrError(result));
  2376. }
  2377. return result;
  2378. }
  2379. ErrorCodeEnum CHealthManagerEntity::DealSpecifiedEntity(DealType type, LPCTSTR lpcszEntityName, LPCTSTR lpcszCmdline, bool bForce, CSimpleStringA& strErrMsg)
  2380. {
  2381. ErrorCodeEnum result(Error_Succeed);
  2382. strErrMsg.Clear();
  2383. switch (type) {
  2384. case Deal_Start:
  2385. {
  2386. CSmartPointer<IEntityFunction> pFunc = GetFunction();
  2387. CSmartPointer<IEntityFunctionPrivilege> pFuncPrivilege = pFunc.ConvertCase<IEntityFunctionPrivilege>();
  2388. CSimpleStringA strEntityName(lpcszEntityName);
  2389. CEntityRunInfo info = {};
  2390. result = GetFunction()->GetEntityRunInfo(strEntityName, info);
  2391. bool toStart(true);
  2392. Dbg("entity: %s, %s,%s", strEntityName.GetData(), SpStrError(result), SpStrEntityState(info.eState));
  2393. if ((info.eState != EntityState_NoStart && info.eState == EntityState_Lost
  2394. && info.eState == EntityState_Close && info.eState == EntityState_UnLoading)
  2395. && (bForce)) {
  2396. }
  2397. if (info.eState != EntityState_NoStart && bForce) {
  2398. Dbg("to terminal entity..");
  2399. CSmartPointer<IAsynWaitSp> spWait;
  2400. result = pFuncPrivilege->StopEntity(strEntityName, spWait);
  2401. Dbg("stop entity return %s", SpStrError(result));
  2402. if (result == Error_Succeed && spWait != NULL) {
  2403. Dbg("to wait after stop...");
  2404. result = spWait->WaitAnswer(60 * 1000);
  2405. Dbg("wait result: %s", SpStrError(result));
  2406. if (result != Error_Succeed) {
  2407. CSmartPointer<IAsynWaitSp> spWait2;
  2408. result = pFuncPrivilege->TerminateEntity(strEntityName, spWait2);
  2409. Dbg("terminal entity return %s", SpStrError(result));
  2410. if (result == Error_Succeed && spWait2 != NULL) {
  2411. Dbg("to wait after terminal...");
  2412. result = spWait2->WaitAnswer(60 * 1000);
  2413. Dbg("wait result: %s", SpStrError(result));
  2414. }
  2415. }
  2416. }
  2417. if (result != Error_Succeed) {
  2418. strErrMsg = CSimpleStringA::Format("重启前停止实体失败 %s, %s", SpStrEntityState(info.eState), SpStrError(result));
  2419. toStart = false;
  2420. }
  2421. } else if (info.eState != EntityState_NoStart) {
  2422. result = Error_InvalidState;
  2423. strErrMsg = CSimpleStringA::Format("实体[%s]当前状态(%s)不支持该操作", strEntityName.GetData(), SpStrEntityState(info.eState));
  2424. toStart = false;
  2425. }
  2426. if (toStart) {
  2427. Dbg("to start entity..");
  2428. CSmartPointer<IAsynWaitSp> spWait;
  2429. result = pFuncPrivilege->StartEntity(strEntityName, lpcszCmdline, spWait);
  2430. Dbg("start entity return %s", SpStrError(result));
  2431. if (result == Error_Succeed && spWait != NULL) {
  2432. Dbg("to wait...");
  2433. result = spWait->WaitAnswer(60 * 1000);
  2434. Dbg("wait result: %s", SpStrError(result));
  2435. }
  2436. if (result != Error_Succeed) {
  2437. strErrMsg = CSimpleStringA::Format("启动实体失败 %s", SpStrError(result));
  2438. }
  2439. }
  2440. }
  2441. break;
  2442. case Deal_Close:
  2443. result = Error_NotImpl;
  2444. break;
  2445. case Deal_Pause:
  2446. result = Error_NotImpl;
  2447. break;
  2448. case Deal_Continue:
  2449. result = Error_NotImpl;
  2450. break;
  2451. case Deal_Kill:
  2452. result = Error_NotImpl;
  2453. break;
  2454. case Deal_Test:
  2455. result = Error_NotImpl;
  2456. break;
  2457. case Deal_Restart:
  2458. result = Error_NotImpl;
  2459. break;
  2460. default:
  2461. result = Error_NotSupport;
  2462. break;
  2463. }
  2464. return result;
  2465. }
  2466. void CHealthManagerEntity::DeployTerminal(SpReqAnsContext<HealthManagerService_DeployTerminal_Req, HealthManagerService_DeployTerminal_Ans>::Pointer ctx)
  2467. {
  2468. LOG_FUNCTION();
  2469. ErrorCodeEnum result(Error_Succeed);
  2470. int tmpResult = 0;
  2471. CSimpleStringA tmpMsg(true);
  2472. Dbg("Cmd: %d", ctx->Req.currStep);
  2473. switch (ctx->Req.currStep) {
  2474. case DeployStep_Begin:
  2475. {
  2476. if (ctx->Req.options == 1) { //重置配置
  2477. CSmartPointer<IConfigInfo> pConfig;
  2478. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2479. int lastStep(0), stepStatus(0);
  2480. pConfig->ReadConfigValueInt("TerminalDeploy", "CurrStep", lastStep);
  2481. pConfig->ReadConfigValueInt("TerminalDeploy", "CurrState", stepStatus);
  2482. if (lastStep > 0 && (stepStatus == DEPLOYSTATE_NOTINIT)) {
  2483. lastStep--;
  2484. Dbg("draw back to %d", lastStep);
  2485. } else if(lastStep != 0) {
  2486. Dbg("current step: %d", lastStep);
  2487. } else if(!m_fConfigMode) {
  2488. lastStep = DeployStep_Finished;
  2489. Dbg("reset to finished step");
  2490. }
  2491. for (int cur = lastStep; cur > 0; --cur) {
  2492. switch (cur) {
  2493. case DeployStep_GetTerminalInfo:
  2494. {
  2495. Dbg("clear terminalno etc at cache file...");
  2496. pConfig->WriteConfigValue("TerminalDeploy", "TerminalNo", NULL);
  2497. pConfig->WriteConfigValue("TerminalDeploy", "Manufacturer", NULL);
  2498. pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", NULL);
  2499. pConfig->WriteConfigValue("TerminalDeploy", "HeadOfficeMode", NULL);
  2500. pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", NULL);
  2501. pConfig->WriteConfigValue("TerminalDeploy", "LastInfo", NULL);
  2502. }
  2503. break;
  2504. case DeployStep_FetchCenterSettings:
  2505. {
  2506. //清理集中配置文件
  2507. Dbg("clear centersetting files...");
  2508. CSimpleStringA strEntityCfgPath;
  2509. tmpResult = GetFunction()->GetPath("Cfg", strEntityCfgPath);
  2510. array_header_t* subs = fileutil_get_sub_files_a(strEntityCfgPath);
  2511. if (subs) {
  2512. regex_t reg;
  2513. CSimpleStringA pattern = "CenterSetting\.[a-zA-Z0-9_\\(\\)\\-]*\.ini";
  2514. int ret = regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB);
  2515. if (ret) {
  2516. char ebuff[256];
  2517. regerror(ret, &reg, ebuff, 256);
  2518. Dbg("regex failed: %s", ebuff);
  2519. tmpResult = Error_Unexpect;
  2520. tmpMsg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
  2521. toolkit_array_free2(subs);
  2522. break;
  2523. }
  2524. Dbg("pattern: %s", pattern.GetData());
  2525. for (int i = 0; i < subs->nelts; ++i) {
  2526. char* filenamePath = ARRAY_IDX(subs, i, char*);
  2527. char* filename = &filenamePath[strEntityCfgPath.GetLength() + 1];
  2528. ret = regexec(&reg, filename, 0, NULL, 0);
  2529. if (0 == ret) {
  2530. Dbg("filename %s matched and remove it.", filename);
  2531. fileutil_delete_file(filenamePath);
  2532. }
  2533. }
  2534. toolkit_array_free2(subs);
  2535. }
  2536. }
  2537. break;
  2538. case DeployStep_AccessAuthorize:
  2539. break;
  2540. case DeployStep_MediaConfig:
  2541. break;
  2542. default:
  2543. break;
  2544. }
  2545. }
  2546. /*读取第一启动的时间戳,有用*/
  2547. CSimpleStringA strBeginTimeReserved(true);
  2548. GetInstallBeginTimeStamp(strBeginTimeReserved);
  2549. CSimpleStringA strCachePath;
  2550. CSimpleStringA strRootTmpFile;
  2551. CSimpleStringA strRootIniFullPath;
  2552. CSimpleStringA strRunInfoDirPath;
  2553. CSimpleStringA strRunCfgDirPath;
  2554. ///**TODO(Gifur@4/21/2022): 既然删除了,前面就没必要清空字段内容了 */
  2555. GetFunction()->GetPath("RunInfo", strRunInfoDirPath);
  2556. strCachePath = strRunInfoDirPath + SPLIT_SLASH_STR + "Global.ini";
  2557. if (ExistsFileA(strCachePath)) {
  2558. Dbg("delete cache file");
  2559. fileutil_delete_file(strCachePath);
  2560. }
  2561. GetFunction()->GetPath("RunCfg", strRunCfgDirPath);
  2562. if (strRunCfgDirPath.IsNullOrEmpty()) {
  2563. strRunCfgDirPath = strRunInfoDirPath + SPLIT_SLASH_STR + "runcfg";
  2564. } else {
  2565. Dbg("Get RunCfg from GetPath directly:%s", strRunCfgDirPath.GetData());
  2566. }
  2567. if (ExistsDirA(strRunCfgDirPath)) {
  2568. Dbg("remove runinfo dir");
  2569. RemoveDirRecursiveA(strRunCfgDirPath);
  2570. }
  2571. CSimpleStringA strBackupFile;
  2572. GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strBackupFile);
  2573. if (ExistsFileA(strRootIniFullPath)) {
  2574. Dbg("delete root.ini");
  2575. fileutil_copy_file(strBackupFile, strRootIniFullPath);
  2576. fileutil_delete_file(strRootIniFullPath);
  2577. }
  2578. LogWarn(Severity_High, Error_Debug, LOG_WARN_HEALTH_INSTALL_RESET, "user requires installation reset!");
  2579. /** 将首次安装的时间写进去*/
  2580. if (!strBeginTimeReserved.IsNullOrEmpty()) {
  2581. RecordInstallBeginTimeStamp(strBeginTimeReserved);
  2582. }
  2583. } else {
  2584. result = Error_NotImpl;
  2585. }
  2586. }
  2587. break;
  2588. case DeployStep_GetTerminalInfo:
  2589. {
  2590. if (ctx->Req.options == 0) {
  2591. CAutoArray<CSimpleStringA> arrs = ctx->Req.param4.Split('|');
  2592. const CSimpleStringA& terminalNo = arrs[0];
  2593. //终端类型(行内定义)
  2594. const CSimpleStringA& strTerminalType = arrs[1];
  2595. const CSimpleStringA& serverIP = ctx->Req.param3;
  2596. Dbg("server ip: %s, terminal no: %s, type: %s", serverIP.GetData(), (LPCTSTR)terminalNo, (LPCTSTR)strTerminalType);
  2597. CSimpleStringA strVendorName(true);
  2598. CSimpleStringA strZhCNVendorName(true);
  2599. CSimpleStringA strDeviceModel(true);
  2600. CSimpleStringA strDeviceSN(true);
  2601. if (ctx->Req.array2.GetCount() > 0) {
  2602. //硬件厂商
  2603. strVendorName = ctx->Req.array2[0];
  2604. //硬件设备型号(厂商)
  2605. strDeviceModel = ctx->Req.array2[1];
  2606. //设备序列号
  2607. strDeviceSN = ctx->Req.array2[2];
  2608. Dbg("vendor: %s, model:%s, sn: %s", strVendorName.GetData(), strDeviceModel.GetData(), strDeviceSN.GetData());
  2609. }
  2610. bool toRecord(false);
  2611. bool fHeadOfficeMode(false);
  2612. CSimpleStringA matchInfo(true);
  2613. ///**TODO(Gifur@4/21/2022): 走分行的逻辑后续要移除 */
  2614. if (ctx->Req.param1 == 0) { //走分行服务
  2615. CTerminalInfoQuery* pCnn = new CTerminalInfoQuery(this);
  2616. /** 1050 是固定的服务端实体端口 [Gifur@20211013]*/
  2617. const bool ret = pCnn->ConnectServer(serverIP.GetData(), 1050);
  2618. Dbg("Connect finished: %d", ret);
  2619. if (pCnn->IsConnectionOK()) {
  2620. Dbg("Connect OK!");
  2621. TerminalRegistRet info;
  2622. result = pCnn->GetTerminalInfo(terminalNo.GetData(), &info);
  2623. pCnn->Close();
  2624. PrintTerminalRegistInfo(&info);
  2625. if (strlen(info.TerminalNo) == 0) {
  2626. tmpResult = Error_NotExist;
  2627. tmpMsg = "查询终端信息不存在,请检测输入的终端号是否正确";
  2628. } else if (terminalNo.Compare(info.TerminalNo) != 0) {
  2629. tmpResult = Error_MisMatched;
  2630. tmpMsg = CSimpleStringA::Format("查询返回的终端信息不匹配,输入:%s,返回:%s", terminalNo.GetData(), info.TerminalNo);
  2631. } else {
  2632. toRecord = true;
  2633. }
  2634. } else {
  2635. Dbg("Connect Failed!");
  2636. result = Error_ConnectFailed;
  2637. }
  2638. pCnn->DecRefCount();
  2639. pCnn = NULL;
  2640. } else if (ctx->Req.param1 == 1) { //走总行服务
  2641. fHeadOfficeMode = true;
  2642. HttpClientRequestConfig config(serverIP.GetData());
  2643. HttpClientResponseResult result;
  2644. config.SetChildUri(URLPATH_REGISTER_FULL_LIST);
  2645. config.AppendQuery("terminalNo", terminalNo.GetData());
  2646. RestfulClient client = RestfulClient::getInstance();
  2647. config.PreDo();
  2648. client.Do(&config, &result);
  2649. if (result.ResponseOK()) {
  2650. struct CommResponseJson : public MicroServices::API::CommResponse {
  2651. JSONCONVERT2OBJECT_MEMEBER_REGISTER(success, errorCode, returnCode, errorMsg, message)
  2652. };
  2653. CommResponseJson reponseStatus;
  2654. struct RegistInfoJson : public MicroServices::API::Manage::RegistDetailInfo {
  2655. JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, deviceNo, initIP, machineNo, machineType, machineVersion, sites, terminalNo, manufactureID, manufacturerName, deviceTye)
  2656. } terminalRegistInfo;
  2657. Json::Value rawRoot;
  2658. bool testSucc(false);
  2659. do
  2660. {
  2661. if (!GetJsonRootObject(rawRoot, result.content)) {
  2662. Dbg("%d", __LINE__);
  2663. break;
  2664. }
  2665. if (!Json2Object(reponseStatus, rawRoot)) {
  2666. Dbg("%d", __LINE__);
  2667. break;
  2668. }
  2669. if (!reponseStatus.IsOperatedOK()) {
  2670. Dbg("%d", __LINE__);
  2671. break;
  2672. }
  2673. if (!(rawRoot["data"].size() > 0)) {
  2674. Dbg("%d", __LINE__);
  2675. break;
  2676. }
  2677. if (!Json2Object(terminalRegistInfo, rawRoot["data"][0])) {
  2678. Dbg("%d", __LINE__);
  2679. break;
  2680. }
  2681. testSucc = true;
  2682. } while (false);
  2683. if (testSucc) {
  2684. auto printFunc = [&terminalRegistInfo]() {
  2685. Dbg("TerminalNo: %s", terminalRegistInfo.terminalNo.c_str());
  2686. Dbg("BranchNo: %s", terminalRegistInfo.branchNo.c_str());
  2687. Dbg("DeviceNo: %s", terminalRegistInfo.deviceNo.c_str());
  2688. Dbg("IP: %s", terminalRegistInfo.initIP.c_str());
  2689. Dbg("MachineNo: %s", terminalRegistInfo.machineNo.c_str());
  2690. Dbg("MachineType: %s", terminalRegistInfo.machineType.c_str());
  2691. Dbg("MachineVersion: %s", terminalRegistInfo.machineVersion.c_str());
  2692. Dbg("Sites: %s", terminalRegistInfo.sites.c_str());
  2693. Dbg("manufactureID: %s", terminalRegistInfo.manufactureID.c_str());
  2694. Dbg("manufacturerName: %s", terminalRegistInfo.manufacturerName.c_str());
  2695. /** Agent: 终端设备型号*/
  2696. Dbg("deviceTye: %s", terminalRegistInfo.deviceTye.c_str());
  2697. };
  2698. printFunc();
  2699. if (!terminalRegistInfo.manufactureID.empty() && terminalRegistInfo.manufacturerName.empty()) {
  2700. CommResponseJson reponseStatus2;
  2701. HttpClientResponseResult result2;
  2702. Json::Value rawRoot2;
  2703. config.SetChildUri(URLPATH_MANUFACTURE_GET_ALL);
  2704. config.ResetQuery();
  2705. config.PreDo();
  2706. client.Do(&config, &result2);
  2707. bool fetchManufactureDone(false);
  2708. if (result2.ResponseOK() && GetJsonRootObject(rawRoot2, result2.content)
  2709. && Json2Object(reponseStatus2, rawRoot2) && reponseStatus2.IsOperatedOK()) {
  2710. struct ManufactureInfoJson : public MicroServices::API::Manufacture::ManufactureInfo {
  2711. JSONCONVERT2OBJECT_MEMEBER_REGISTER(manufacturerId, manufacturerName)
  2712. };
  2713. struct ManufactureList {
  2714. std::vector<ManufactureInfoJson> data;
  2715. JSONCONVERT2OBJECT_MEMEBER_REGISTER(data)
  2716. } manufactureList;
  2717. if (Json2Object(manufactureList, rawRoot2)) {
  2718. for (auto it = manufactureList.data.begin(); it != manufactureList.data.end(); ++it) {
  2719. if (it->manufacturerId.compare(terminalRegistInfo.manufactureID) == 0) {
  2720. terminalRegistInfo.manufacturerName = it->manufacturerName;
  2721. Dbg("get manufacturer name: %s", terminalRegistInfo.manufacturerName.c_str());
  2722. fetchManufactureDone = true;
  2723. break;
  2724. }
  2725. }
  2726. }
  2727. }
  2728. if (!fetchManufactureDone) {
  2729. if (reponseStatus2.IsNotEmpty() && !reponseStatus2.IsOperatedOK()) {
  2730. Dbg("请求失败:%s", reponseStatus2.WhatError().c_str());
  2731. } else {
  2732. Dbg("解析返回内容失败:%s", result2.content.c_str());
  2733. }
  2734. }
  2735. }
  2736. printFunc();
  2737. if (terminalRegistInfo.terminalNo.empty()) {
  2738. tmpResult = Error_NotExist;
  2739. tmpMsg = "查询终端信息不存在,请检测输入的终端号是否正确";
  2740. } else if (terminalRegistInfo.terminalNo != terminalNo.GetData()) {
  2741. tmpResult = Error_MisMatched;
  2742. tmpMsg = CSimpleStringA::Format("查询返回的终端信息不匹配,输入:%s,返回:%s"
  2743. , terminalNo.GetData(), terminalRegistInfo.terminalNo.c_str());
  2744. } else {
  2745. bool bMatched(true);
  2746. if (strTerminalType.Compare(terminalRegistInfo.machineType.c_str()) != 0) {
  2747. if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
  2748. matchInfo += CSimpleStringA::Format("终端类型不匹配:[%s]vs[%s]", strTerminalType.GetData(), terminalRegistInfo.machineType.c_str());
  2749. bMatched = false;
  2750. }
  2751. //terminalRegistInfo.manufacturerName = "中钞科堡现金处理";
  2752. if (strVendorName.Compare(terminalRegistInfo.manufacturerName.c_str(), true) != 0) {
  2753. do {
  2754. CSmartPointer<IConfigInfo> spCfgConfig;
  2755. GetFunction()->OpenConfig(Config_Software, spCfgConfig);
  2756. spCfgConfig->ReadConfigValue("VendorZhCN", strVendorName, strZhCNVendorName);
  2757. } while (false);
  2758. if (!strZhCNVendorName.IsNullOrEmpty()
  2759. && terminalRegistInfo.manufacturerName.find(strZhCNVendorName.GetData()) != std::string::npos) {
  2760. //let it empty.
  2761. } else {
  2762. if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
  2763. if (strZhCNVendorName.IsNullOrEmpty()) {
  2764. matchInfo += CSimpleStringA::Format("设备厂商不匹配:[%s]vs[%s]", strVendorName.GetData(), terminalRegistInfo.manufacturerName.c_str());
  2765. } else {
  2766. matchInfo += CSimpleStringA::Format("设备厂商不匹配:[%s]vs[%s]", strZhCNVendorName.GetData(), terminalRegistInfo.manufacturerName.c_str());
  2767. }
  2768. bMatched = false;
  2769. }
  2770. }
  2771. if (strDeviceModel.Compare(terminalRegistInfo.deviceTye.c_str()) != 0) {
  2772. if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
  2773. matchInfo += CSimpleStringA::Format("设备型号不匹配:[%s]vs[%s]", strDeviceModel.GetData(), terminalRegistInfo.deviceTye.c_str());
  2774. bMatched = false;
  2775. }
  2776. /** Agent: 设备编号*/
  2777. if (strDeviceSN.Compare(terminalRegistInfo.machineNo.c_str()) != 0) {
  2778. if (!matchInfo.IsNullOrEmpty()) { matchInfo += ";"; }
  2779. matchInfo += CSimpleStringA::Format("设备序列号(编号)不匹配:[%s]vs[%s]", strDeviceSN.GetData(), terminalRegistInfo.machineNo.c_str());
  2780. bMatched = false;
  2781. }
  2782. /** 其他信息的校验和应用 [Gifur@2022123]*/
  2783. if (!bMatched) {
  2784. tmpResult = Error_DataCheck;
  2785. if (!matchInfo.IsNullOrEmpty()) { matchInfo += "。请核验录入信息是否准确!"; }
  2786. tmpMsg = matchInfo;
  2787. } else {
  2788. toRecord = true;
  2789. }
  2790. }
  2791. } else {
  2792. if (reponseStatus.IsNotEmpty() && !reponseStatus.IsOperatedOK()) {
  2793. tmpResult = Error_DataCheck;
  2794. tmpMsg = CSimpleStringA::Format("请求失败:%s", reponseStatus.WhatError().c_str());
  2795. Dbg(tmpMsg);
  2796. } else {
  2797. tmpResult = Error_DataCheck;
  2798. tmpMsg = CSimpleStringA::Format("解析返回内容失败:%s", result.content.c_str());
  2799. Dbg(tmpMsg);
  2800. Dbg("rawRoot[data].size(): %d", rawRoot["data"].size());
  2801. }
  2802. }
  2803. } else {
  2804. tmpResult = Error_ServerNotAvailable;
  2805. if (!result.content.empty()) {
  2806. tmpMsg = CSimpleStringA::Format("访问 %s 失败:%d,%s", config.GetRequestUri().c_str(), result.statusCode, result.content.c_str());
  2807. } else {
  2808. tmpMsg = CSimpleStringA::Format("访问 %s 失败:%d", config.GetRequestUri().c_str(), result.statusCode);
  2809. }
  2810. }
  2811. }
  2812. if (toRecord) {
  2813. ErrorCodeEnum ec(Error_Succeed);
  2814. do {
  2815. Dbg("record to cache...");
  2816. CSmartPointer<IConfigInfo> pConfig;
  2817. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2818. const ErrorCodeEnum ec0 = pConfig->WriteConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
  2819. const ErrorCodeEnum ec1 = pConfig->WriteConfigValue("TerminalDeploy", "Manufacturer", strVendorName);
  2820. const ErrorCodeEnum ec2 = pConfig->WriteConfigValue("TerminalDeploy", "ServerIP", serverIP);
  2821. const ErrorCodeEnum ec3 = pConfig->WriteConfigValueInt("TerminalDeploy", "HeadOfficeMode", fHeadOfficeMode ? 1 : 0);
  2822. if (!matchInfo.IsNullOrEmpty()) {
  2823. pConfig->WriteConfigValue("TerminalDeploy", "LastInfo", matchInfo);
  2824. }
  2825. Dbg("record step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2), SpStrError(ec3));
  2826. } while (false);
  2827. do {
  2828. CSimpleStringA strRootCfgPath;
  2829. CSimpleStringA strRootTmpFile;
  2830. CSimpleStringA strRootIniFullPath;
  2831. CSimpleStringA strRootChosenFile(true);
  2832. CSimpleStringA strNousedPath;
  2833. ec = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
  2834. ///**TODO(Gifur@10/16/2021): ASSERT 在这个步骤root.ini 文件不应该出现的,可能是字段的缺失才识别为未配置模式 */
  2835. if (ExistsFileA(strRootIniFullPath)) {
  2836. fileutil_copy_file(strNousedPath, strRootIniFullPath);
  2837. fileutil_delete_file(strRootIniFullPath);
  2838. Dbg("root.ini exists!");
  2839. }
  2840. const CSimpleStringA machineType(strTerminalType);
  2841. const CSimpleStringA rootPattern("root");
  2842. const CSimpleStringA pattern = rootPattern + "\\-" + machineType + "\\-" + strVendorName + "\\-[a-zA-Z0-9_\\(\\)\\-]*" + ".ini";
  2843. ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath);
  2844. array_header_t* subs = fileutil_get_sub_files_a(strRootCfgPath);
  2845. if (subs) {
  2846. regex_t reg;
  2847. int ret = regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB);
  2848. if (ret) {
  2849. char ebuff[256];
  2850. regerror(ret, &reg, ebuff, 256);
  2851. Dbg("regex failed: %s", ebuff);
  2852. tmpResult = Error_Unexpect;
  2853. tmpMsg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
  2854. toolkit_array_free2(subs);
  2855. break;
  2856. }
  2857. Dbg("pattern: %s", pattern.GetData());
  2858. for (int i = 0; i < subs->nelts; ++i) {
  2859. char* filenamePath = ARRAY_IDX(subs, i, char*);
  2860. char* filename = &filenamePath[strRootCfgPath.GetLength() + 1];
  2861. Dbg("filename: %s", filename);
  2862. ret = regexec(&reg, filename, 0, NULL, 0);
  2863. if (0 == ret) {
  2864. Dbg("matched!");
  2865. strRootChosenFile = filenamePath;
  2866. break;
  2867. }
  2868. Dbg("not matched.");
  2869. }
  2870. toolkit_array_free2(subs);
  2871. }
  2872. if (!strRootChosenFile.IsNullOrEmpty()) {
  2873. ///**TODO(Gifur@1/23/2022): 根据服务器返回的信息填充其他字段内容 */
  2874. fileutil_copy_file(strRootTmpFile, strRootChosenFile);
  2875. inifile_write_str(strRootTmpFile, "Terminal", "TerminalNo", terminalNo);
  2876. //inifile_write_str(strRootTmpFile, "Terminal", "Manufacturer", vendorType);
  2877. if (!strDeviceSN.IsNullOrEmpty()) {
  2878. inifile_write_str(strRootTmpFile, "Terminal", "SN", strDeviceSN);
  2879. }
  2880. } else {
  2881. CSimpleStringA::Format("%s", pattern.GetData());
  2882. tmpMsg = "harewarecfg下匹配不到相应的配置文件,请确认选择的机型和设备厂商是否正确";
  2883. tmpResult = Error_InvalidState;
  2884. }
  2885. } while (false);
  2886. ctx->Ans.param2 = serverIP;
  2887. }
  2888. } else if(ctx->Req.options == 1){
  2889. //从缓存文件中获取,避免出现依赖
  2890. CSimpleStringA terminalNo;
  2891. CSimpleStringA vendorType;
  2892. CSimpleStringA serverIP;
  2893. bool fHeadOfficeMode(false);
  2894. do {
  2895. Dbg("read from cache...");
  2896. CSmartPointer<IConfigInfo> pConfig;
  2897. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2898. int nTemp(0);
  2899. const ErrorCodeEnum ec0 = pConfig->ReadConfigValue("TerminalDeploy", "TerminalNo", terminalNo);
  2900. const ErrorCodeEnum ec1 = pConfig->ReadConfigValue("TerminalDeploy", "Manufacturer", vendorType);
  2901. const ErrorCodeEnum ec2 = pConfig->ReadConfigValue("TerminalDeploy", "ServerIP", serverIP);
  2902. const ErrorCodeEnum ec3 = pConfig->ReadConfigValueInt("TerminalDeploy", "HeadOfficeMode", nTemp);
  2903. fHeadOfficeMode = (nTemp > 0);
  2904. Dbg("read step: %s, %s, %s", SpStrError(ec0), SpStrError(ec1), SpStrError(ec2));
  2905. } while (false);
  2906. int checkFlag = 0;
  2907. if (terminalNo.IsNullOrEmpty()) checkFlag |= 1;
  2908. if (vendorType.IsNullOrEmpty()) checkFlag |= 2;
  2909. if (serverIP.IsNullOrEmpty()) checkFlag |= 4;
  2910. if (checkFlag != 0) {
  2911. tmpResult = Error_Null;
  2912. tmpMsg = CSimpleStringA::Format("获取终端缓存信息失败 Mask=0x%X", checkFlag);
  2913. } else {
  2914. ctx->Ans.array1.Init(3);
  2915. ctx->Ans.array1[0] = ctx->Ans.array1[1] = ctx->Ans.array1[2] = 0;
  2916. ctx->Ans.array1[0] = fHeadOfficeMode ? 1 : 0;
  2917. ctx->Ans.array2.Init(3);
  2918. ctx->Ans.array2[0] = terminalNo;
  2919. ctx->Ans.array2[1] = vendorType;
  2920. ctx->Ans.array2[2] = serverIP;
  2921. }
  2922. } else {
  2923. tmpResult = Error_NotSupport;
  2924. }
  2925. }
  2926. break;
  2927. case DeployStep_FetchCenterSettings:
  2928. {
  2929. const CSimpleStringA& serverIP = ctx->Req.param3;
  2930. const int nPort = ctx->Req.param1;
  2931. const bool headOfficeMode = (ctx->Req.param2 == 1);
  2932. if (serverIP.IsNullOrEmpty() || (!headOfficeMode && nPort <= 0)) {
  2933. result = Error_Param;
  2934. break;
  2935. }
  2936. ErrorCodeEnum ec(Error_Succeed);
  2937. Dbg("to connect centersetting...%s::%d", serverIP.GetData(), nPort);
  2938. auto pCenterSettingClient = new CenterSettingService_ClientBase(this);
  2939. ec = pCenterSettingClient->Connect();
  2940. if (ec != Error_Succeed) {
  2941. tmpMsg = CSimpleStringA::Format("连接集中配置模块失败: %s", SpStrError(ec));
  2942. pCenterSettingClient->SafeDelete();
  2943. Dbg("connect to centersetting failed: %s", SpStrError(ec));
  2944. } else {
  2945. CenterSettingService_Download_Req req = {};
  2946. req.strAddr = serverIP;
  2947. req.nPort = nPort;
  2948. CenterSettingService_Download_Ans ans = {};
  2949. /**TODO(Gifur@10/14/2021): 未知行内还是行外的情况 */
  2950. Dbg("to download...");
  2951. ec = pCenterSettingClient->Download(req, ans, 60000);
  2952. if (ec != Error_Succeed) {
  2953. tmpMsg = CSimpleStringA::Format("下载集中配置文件请求失败: %s", SpStrError(ec));
  2954. Dbg("to download failed: %s", SpStrError(ec));
  2955. }
  2956. pCenterSettingClient->GetFunction()->CloseSession();
  2957. }
  2958. tmpResult = ec;
  2959. ctx->Ans.param2 = serverIP;
  2960. }
  2961. break;
  2962. case DeployStep_AccessAuthorize:
  2963. {
  2964. const CSimpleStringA& serverIP = ctx->Req.param3;
  2965. const int nPort = ctx->Req.param1;
  2966. CSimpleStringA strUsername("admin");
  2967. CSimpleStringA strPassword("88888888");
  2968. if (ctx->Req.array2.GetCount() == 2) {
  2969. strUsername = ctx->Req.array2[0];
  2970. strPassword = ctx->Req.array2[1];
  2971. }
  2972. if (serverIP.IsNullOrEmpty() || nPort <= 0) {
  2973. result = Error_Param;
  2974. break;
  2975. }
  2976. ErrorCodeEnum ec(Error_Succeed);
  2977. CSmartPointer<IConfigInfo> pConfig;
  2978. GetFunction()->OpenConfig(Config_Cache, pConfig);
  2979. Dbg("to connect initializer...%s::%d", serverIP.GetData(), nPort);
  2980. auto pClient = new InitializerService_ClientBase(this);
  2981. ec = pClient->Connect();
  2982. if (ec != Error_Succeed) {
  2983. tmpMsg = CSimpleStringA::Format("连接初始化模块失败: %s", SpStrError(ec));
  2984. pClient->SafeDelete();
  2985. Dbg("connect to initializer module failed: %s", SpStrError(ec));
  2986. tmpResult = ec;
  2987. } else {
  2988. InitializerService_InitializeNew_Req req = {};
  2989. req.strAuthServer = serverIP;
  2990. req.nAuthPort = nPort;
  2991. req.strUserID = strUsername;
  2992. req.strPassword = strPassword;
  2993. InitializerService_InitializeNew_Ans ans = {};
  2994. Dbg("to initializer...");
  2995. ec = pClient->InitializeNew(req, ans, 60000);
  2996. if (ec != Error_Succeed) {
  2997. tmpMsg = CSimpleStringA::Format("初始化请求失败: %s", SpStrError(ec));
  2998. tmpResult = ec;
  2999. Dbg("to initialize failed: %s", SpStrError(ec));
  3000. } else {
  3001. const int errUserCode = (int)(ans.Errcode);
  3002. if (errUserCode != 0) {
  3003. if (ans.ErrMsg.IsNullOrEmpty()) {
  3004. tmpMsg = CSimpleStringA::Format("%d", errUserCode);
  3005. } else {
  3006. tmpMsg = CSimpleStringA::Format("%s", ans.ErrMsg.GetData());
  3007. }
  3008. tmpResult = errUserCode;
  3009. Dbg("initialize failed: %s", (LPCTSTR)tmpMsg);
  3010. } else {
  3011. Dbg("initialize succ.");
  3012. }
  3013. }
  3014. pClient->GetFunction()->CloseSession();
  3015. }
  3016. ctx->Ans.param2 = serverIP;
  3017. }
  3018. break;
  3019. case DeployStep_MediaConfig:
  3020. {
  3021. CSimpleStringA strRootTmpFile;
  3022. CSimpleStringA strRootIniFullPath;
  3023. CSimpleStringA strNousedPath;
  3024. tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
  3025. CSimpleStringA strRecordFilePath = (ctx->Req.options == 1) ? strRootIniFullPath : strRootTmpFile;
  3026. if (!ExistsFileA(strRecordFilePath)) {
  3027. Dbg("%s not exists!", strRecordFilePath.GetData());
  3028. tmpMsg = CSimpleStringA::Format("%文件不存在,请重置后重新进行配置!", strRecordFilePath.GetData());
  3029. tmpResult = Error_NotExist;
  3030. } else {
  3031. for (int i = 0; i < ctx->Req.array1.GetCount() && tmpResult == Error_Succeed; ++i) {
  3032. CSimpleStringA key(true), value(ctx->Req.array2[i]);
  3033. const int type = ctx->Req.array1[i];
  3034. Dbg("%d: %s - %d", i, value.GetData(), type);
  3035. switch (type) {
  3036. case MediaDev_OutSpeaker:
  3037. key = "handfree_out_dev";
  3038. break;
  3039. case MediaDev_InSpeaker:
  3040. key = "pickup_out_dev";
  3041. break;
  3042. case MediaDev_OutMicrophone:
  3043. key = "handfree_in_dev";
  3044. break;
  3045. case MediaDev_InMicrophone:
  3046. key = "pickup_in_dev";
  3047. break;
  3048. default:
  3049. tmpResult = Error_Param;
  3050. break;
  3051. }
  3052. if (!key.IsNullOrEmpty()) {
  3053. tmpResult = inifile_write_str(strRecordFilePath, "Audio", key, value);
  3054. Dbg("write %s=%s into root.ini tmp file: %s", key.GetData(), value.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
  3055. } else {
  3056. Dbg("unrecognize: %d, %s", type, value.GetData());
  3057. tmpResult = Error_Unexpect;
  3058. }
  3059. }
  3060. }
  3061. }
  3062. break;
  3063. case DeployStep_AdapterConfig:
  3064. {
  3065. if ((ctx->Req.options & 0x2) || (ctx->Req.options & 0x1)) {
  3066. CSimpleStringA& strAdapterFileName = ctx->Req.param3;
  3067. CAutoArray<CSimpleStringA> adapterInfo;
  3068. tmpResult = SplitAdapterFileName(strAdapterFileName, adapterInfo);
  3069. Dbg("%s, %s", strAdapterFileName.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
  3070. if (tmpResult == 0) {
  3071. CSimpleStringA strDevice(adapterInfo[0]);
  3072. CSimpleStringA strDeviceSection("Device.");
  3073. strDeviceSection += strDevice;
  3074. CSimpleStringA strVendor(adapterInfo[1]);
  3075. CSimpleStringA strVersion(adapterInfo[2]);
  3076. CSimpleStringA strBatch(adapterInfo[3]);
  3077. const int port = ctx->Req.param1;
  3078. const int baudrate = ctx->Req.param2;
  3079. if ((ctx->Req.options & 0x1)) { //更新到缓存
  3080. CSimpleStringA strRootTmpFile;
  3081. CSimpleStringA strRootIniFullPath;
  3082. CSimpleStringA strNousedPath;
  3083. tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
  3084. if (!ExistsFileA(strRootTmpFile)) {
  3085. Dbg("%s not exists!", strRootTmpFile.GetData());
  3086. tmpMsg = "临时配置文件不存在,请重置后重新进行配置!";
  3087. tmpResult = Error_NotExist;
  3088. } else {
  3089. tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Vendor", strVendor);
  3090. tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Version", strVersion);
  3091. tmpResult = inifile_write_str(strRootTmpFile, strDeviceSection, "Batch", strBatch);
  3092. tmpResult = inifile_write_int(strRootTmpFile, strDeviceSection, "Port", port);
  3093. tmpResult = inifile_write_int(strRootTmpFile, strDeviceSection, "Baudrate", baudrate);
  3094. }
  3095. } else { //更新到root.ini
  3096. CSmartPointer<IConfigInfo> pRootConfig;
  3097. GetFunction()->OpenConfig(Config_Root, pRootConfig);
  3098. tmpResult = pRootConfig->WriteConfigValue(strDeviceSection, "Vendor", strVendor);
  3099. Dbg("%s,%s,%s,%s,%s", strDeviceSection.GetData(), strVendor.GetData(), strVersion.GetData(), strBatch.GetData(), SpStrError((ErrorCodeEnum)tmpResult));
  3100. if (tmpResult == 0) {
  3101. pRootConfig->WriteConfigValue(strDeviceSection, "Version", strVersion);
  3102. pRootConfig->WriteConfigValue(strDeviceSection, "Batch", strBatch);
  3103. pRootConfig->WriteConfigValueInt(strDeviceSection, "Port", port);
  3104. pRootConfig->WriteConfigValueInt(strDeviceSection, "Baudrate", baudrate);
  3105. } else {
  3106. tmpMsg = CSimpleStringA::Format("写入ROOT配置文件失败:%s", SpStrError((ErrorCodeEnum)tmpResult));
  3107. }
  3108. }
  3109. } else {
  3110. tmpMsg = CSimpleStringA::Format("适配器文件名称不符合规范:%s", strAdapterFileName.GetData());
  3111. }
  3112. }
  3113. else if ((ctx->Req.options & 0x4)) { //启动实体
  3114. CSimpleStringA& strEntityName = ctx->Req.param3;
  3115. tmpResult = DealSpecifiedEntity((DealType)ctx->Req.param1, strEntityName, ctx->Req.param4, (ctx->Req.param2 != 0), tmpMsg);
  3116. }
  3117. }
  3118. break;
  3119. case DeployStep_3rdParty_SogouInstall:
  3120. {
  3121. if ((ctx->Req.options == 1)) { //检测输入法的安装状态
  3122. auto pClient = new ResourceWatcherService_ClientBase(this);
  3123. tmpResult = pClient->Connect();
  3124. if (tmpResult != 0) {
  3125. tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
  3126. pClient->SafeDelete();
  3127. Dbg(tmpMsg);
  3128. } else {
  3129. ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
  3130. ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
  3131. req.mode = 1;
  3132. Dbg("to invoke...");
  3133. tmpResult = pClient->GetThirdPartyInstallState(req, ans, 30000);
  3134. if (tmpResult != 0) {
  3135. tmpMsg = CSimpleStringA::Format("获取安装状态请求失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
  3136. Dbg(tmpMsg);
  3137. } else {
  3138. ctx->Ans.param1 = 0;
  3139. if (ans.status == 1) {
  3140. ctx->Ans.param1 = 1;
  3141. ctx->Ans.array1.Init(3);
  3142. ctx->Ans.array2.Init(3);
  3143. ctx->Ans.array2[0] = ans.version;
  3144. ctx->Ans.array2[1] = ans.path;
  3145. ctx->Ans.array2[2] = ans.reserverd1; //安装时间
  3146. }
  3147. }
  3148. pClient->GetFunction()->CloseSession();
  3149. }
  3150. } else if (ctx->Req.options == 2) { //安装搜狗输入法
  3151. auto pClient = new ResourceWatcherService_ClientBase(this);
  3152. tmpResult = pClient->Connect();
  3153. if (tmpResult != 0) {
  3154. tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
  3155. pClient->SafeDelete();
  3156. Dbg(tmpMsg);
  3157. } else {
  3158. ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
  3159. ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
  3160. req.type = 1;
  3161. req.reserved1 = req.reserved2 = 0;
  3162. /** 健康实体过来的调用,1表示不直接重启机器 [Gifur@202275]*/
  3163. req.reserved1 = 1;
  3164. Dbg("to install...");
  3165. tmpResult = pClient->InstallThirdPartyProgram(req, ans, 60000);
  3166. if (tmpResult != 0) {
  3167. tmpMsg = CSimpleStringA::Format("调用安装请求返回错误:%s", SpStrError((ErrorCodeEnum)tmpResult));
  3168. Dbg(tmpMsg);
  3169. } else {
  3170. tmpResult = ans.result;
  3171. tmpMsg = ans.msg;
  3172. if (tmpResult == 0) {
  3173. ctx->Ans.array1.Init(3);
  3174. ctx->Ans.array2.Init(3);
  3175. ctx->Ans.array2[0] = ans.reserverd1;
  3176. ctx->Ans.array2[1] = ans.path;
  3177. ctx->Ans.array2[2] = ans.reserverd2; //安装时间
  3178. }
  3179. }
  3180. pClient->GetFunction()->CloseSession();
  3181. }
  3182. } else {
  3183. result = Error_NotSupport;
  3184. }
  3185. }
  3186. break;
  3187. case DeployStep_3rdParty_FontInstall:
  3188. {
  3189. if ((ctx->Req.options == 1)) { //检测字体的安装状态
  3190. auto pClient = new ResourceWatcherService_ClientBase(this);
  3191. tmpResult = pClient->Connect();
  3192. if (tmpResult != 0) {
  3193. tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
  3194. pClient->SafeDelete();
  3195. Dbg(tmpMsg);
  3196. } else {
  3197. ResourceWatcherService_GetThirdPartyInstallState_Req req = {};
  3198. ResourceWatcherService_GetThirdPartyInstallState_Ans ans = {};
  3199. req.mode = 2;
  3200. Dbg("to invoke...");
  3201. tmpResult = pClient->GetThirdPartyInstallState(req, ans, 30000);
  3202. if (tmpResult != 0) {
  3203. tmpMsg = CSimpleStringA::Format("获取安装状态请求失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
  3204. Dbg(tmpMsg);
  3205. } else {
  3206. ctx->Ans.param1 = 0;
  3207. if (ans.status == 1) {
  3208. ctx->Ans.param1 = 1;
  3209. ctx->Ans.array1.Init(3);
  3210. ctx->Ans.array2.Init(3);
  3211. ctx->Ans.array2[0] = ans.version;
  3212. ctx->Ans.array2[1] = ans.path;
  3213. ctx->Ans.array2[2] = ans.reserverd1; //安装时间
  3214. }
  3215. }
  3216. pClient->GetFunction()->CloseSession();
  3217. }
  3218. } else if ((ctx->Req.options == 2)) { //字体的安装
  3219. auto pClient = new ResourceWatcherService_ClientBase(this);
  3220. tmpResult = pClient->Connect();
  3221. if (tmpResult != 0) {
  3222. tmpMsg = CSimpleStringA::Format("连接资源管理模块失败: %s", SpStrError((ErrorCodeEnum)tmpResult));
  3223. pClient->SafeDelete();
  3224. Dbg(tmpMsg);
  3225. } else {
  3226. ResourceWatcherService_InstallThirdPartyProgram_Req req = {};
  3227. ResourceWatcherService_InstallThirdPartyProgram_Ans ans = {};
  3228. req.type = 2; //
  3229. req.reserved1 = req.reserved2 = 0;
  3230. Dbg("to install font....");
  3231. tmpResult = pClient->InstallThirdPartyProgram(req, ans, 60000);
  3232. if (tmpResult != 0) {
  3233. tmpMsg = CSimpleStringA::Format("调用安装请求返回错误:%s", SpStrError((ErrorCodeEnum)tmpResult));
  3234. Dbg(tmpMsg);
  3235. } else {
  3236. tmpResult = ans.result;
  3237. tmpMsg = ans.msg;
  3238. }
  3239. pClient->GetFunction()->CloseSession();
  3240. }
  3241. } else {
  3242. result = Error_NotSupport;
  3243. }
  3244. }
  3245. break;
  3246. case DeployStep_Finished:
  3247. {
  3248. CSimpleStringA strRootTmpFile;
  3249. CSimpleStringA strRootIniFullPath;
  3250. CSimpleStringA strRootChosenFile(true);
  3251. CSimpleStringA strNousedPath;
  3252. GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
  3253. strRootChosenFile = strRootIniFullPath + ".bak";
  3254. if (ExistsFileA(strRootChosenFile)) {
  3255. fileutil_delete_file(strRootChosenFile);
  3256. Dbg("to clear root.ini backup file.");
  3257. }
  3258. CSystemStaticInfo info;
  3259. GetFunction()->GetSystemStaticInfo(info);
  3260. CSmartPointer<IConfigInfo> pConfig;
  3261. GetFunction()->OpenConfig(Config_Cache, pConfig);
  3262. pConfig->WriteConfigValue("TerminalDeploy", "InstallVersion", info.InstallVersion.ToString());
  3263. Dbg("received finish install cmd!");
  3264. LogWarn(Severity_High, Error_Debug, LOG_WARN_HEALTH_INSTALL_FINISHED, "install finished");
  3265. result = Error_Succeed;
  3266. }
  3267. break;
  3268. default:
  3269. result = Error_MisMatched;
  3270. break;
  3271. }
  3272. //////////////////////////////////////////////////////////////////////////
  3273. bool restartApp(false), restartPC(false);
  3274. if (result == Error_Succeed) {
  3275. CSmartPointer<IConfigInfo> pConfig;
  3276. GetFunction()->OpenConfig(Config_Cache, pConfig);
  3277. if (tmpResult == 0) {
  3278. if ((ctx->Req.additional & 0x1)) //重命名 root.ini
  3279. {
  3280. CSimpleStringA strRootTmpFile;
  3281. CSimpleStringA strRootIniFullPath;
  3282. CSimpleStringA strNousedPath;
  3283. tmpResult = GetTmpRootFilePath(strRootIniFullPath, strRootTmpFile, strNousedPath);
  3284. if (!ExistsFileA(strRootTmpFile)) {
  3285. tmpMsg = "临时配置文件不存在,无法加载配置文件,请重置后重新进行配置";
  3286. tmpResult = Error_NotExist;
  3287. } else {
  3288. Dbg("rename tmp file to root.ini..");
  3289. fileutil_copy_file(strRootIniFullPath, strRootTmpFile);
  3290. fileutil_delete_file(strRootTmpFile);
  3291. if (!ExistsFileA(strRootIniFullPath)) {
  3292. tmpResult = Error_IO;
  3293. } else {
  3294. Dbg("root.ini has been renamed!");
  3295. }
  3296. }
  3297. }
  3298. pConfig->WriteConfigValueInt("TerminalDeploy", "CurrStep", ctx->Req.nextStep);
  3299. pConfig->WriteConfigValueInt("TerminalDeploy", "CurrState", DEPLOYSTATE_NOTINIT);
  3300. pConfig->WriteConfigValue("TerminalDeploy", "TimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  3301. restartApp = ctx->Req.restartApp;
  3302. restartPC = ctx->Req.restartPC;
  3303. } else {
  3304. pConfig->WriteConfigValueInt("TerminalDeploy", "CurrStep", ctx->Req.currStep);
  3305. pConfig->WriteConfigValueInt("TerminalDeploy", "CurrState", DEPLOYSTATE_FAILED);
  3306. pConfig->WriteConfigValue("TerminalDeploy", "TimeStamp", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  3307. }
  3308. }
  3309. if (restartPC || restartApp) {
  3310. /** 无奈,有时处理太快,导致界面上看不到提示,所以只能选择战略性延迟,剩下的靠前端自己了 [Gifur@20211022]*/
  3311. Dbg("sleep suitable second for providing time for fontside to tell user to wait while restarting pc or app");
  3312. Sleep(3000);
  3313. }
  3314. if (restartPC) {
  3315. tmpResult = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_OS);
  3316. if (tmpResult != 0) {
  3317. tmpMsg = CSimpleStringA::Format("重启设备失败(%s),请手动重启", SpStrError((ErrorCodeEnum)tmpResult));
  3318. Dbg(tmpMsg);
  3319. }
  3320. } else if (restartApp) {
  3321. tmpResult = m_fsm.QuitFrameworkAndSaveInfo(RebootTrigger_ManualLocal, RebootWay_Framework);
  3322. if (tmpResult != 0) {
  3323. tmpMsg = CSimpleStringA::Format("重启应用失败(%s),请手动重启", SpStrError((ErrorCodeEnum)tmpResult));
  3324. Dbg(tmpMsg);
  3325. }
  3326. }
  3327. ctx->Ans.result = tmpResult;
  3328. ctx->Ans.additionalMsg = tmpMsg;
  3329. ctx->Ans.nextStep = ctx->Req.nextStep;
  3330. ctx->Answer(result);
  3331. }
  3332. bool CHealthManagerEntity::IsTestMode()
  3333. {
  3334. static int flag = -1;
  3335. if (flag == -1) {
  3336. CSystemRunInfo runInfo;
  3337. bool result = (GetFunction()->GetSystemRunInfo(runInfo) == Error_Succeed
  3338. && !!(runInfo.dwBootOption & SystemBootOptionEnum::BootOption_Test));
  3339. flag = result ? 1 : 0;
  3340. }
  3341. return !!flag;
  3342. }
  3343. bool CHealthManagerEntity::IsNotConfigMode(int& stepMode)
  3344. {
  3345. stepMode = 0;
  3346. int lastRecordTime = 0;
  3347. CSystemRunInfo runInfo;
  3348. ErrorCodeEnum ec = GetFunction()->GetSystemRunInfo(runInfo);
  3349. if (ec != Error_Succeed) {
  3350. stepMode = ec;
  3351. Dbg("get framework info failed: %s", SpStrError(ec));
  3352. return false;
  3353. }
  3354. if (runInfo.eState == FrameworkState_NotConfig) {
  3355. Dbg("not config from framework");
  3356. stepMode = -1;
  3357. return true;
  3358. } else {
  3359. CSmartPointer<IConfigInfo> pConfig;
  3360. GetFunction()->OpenConfig(Config_Cache, pConfig);
  3361. int stepStatus(0);
  3362. pConfig->ReadConfigValueInt("TerminalDeploy", "CurrStep", stepMode);
  3363. pConfig->ReadConfigValueInt("TerminalDeploy", "CurrState", stepStatus);
  3364. pConfig->ReadConfigValueInt("TerminalDeploy", "TimeStamp", lastRecordTime);
  3365. if (stepMode != 0 && DeployStep_Finished != stepMode) {
  3366. Dbg("not config from cache: step=%d, status=%d", stepMode, stepStatus);
  3367. return true;
  3368. }
  3369. }
  3370. return false;
  3371. }
  3372. SP_BEGIN_ENTITY_MAP()
  3373. SP_ENTITY(CHealthManagerEntity)
  3374. SP_END_ENTITY_MAP()