mod_healthmanager.cpp 122 KB

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