mod_healthmanager.cpp 114 KB

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