mod_healthmanager.cpp 125 KB

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