mod_healthmanager.cpp 115 KB

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