mod_healthmanager.cpp 108 KB

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