mod_healthmanager.cpp 111 KB

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