mod_chromium.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. #include "stdafx.h"
  2. #if (defined _WIN32 || defined _WIN64)
  3. #include <Windows.h>
  4. #include <WinUser.h>
  5. #include <tchar.h>
  6. #define SPLIT_SLASH_STR "\\"
  7. #include "chromelink_export.h"
  8. #pragma comment(lib, "cefControl.lib")
  9. #else
  10. #include <signal.h>
  11. #endif
  12. #include "fileutil.h"
  13. #include "baseEx.h"
  14. #include "CWebsocketServer.h"
  15. #include "mod_chromium.h"
  16. #include "base64.h"
  17. #include "CModTools.h"
  18. #include "cJSON.h"
  19. #include "SpIni.h"
  20. #include "CSocketClient.h"
  21. #include "processControl.h"
  22. #include <boost/chrono.hpp>
  23. #include <boost/bind.hpp>
  24. #include "../mod_upload/Upload_client_g.h"
  25. #include <tuple>
  26. #include <string>
  27. #include <algorithm>
  28. #include "EventCode.h"
  29. #ifdef OPEN_PERF
  30. #include <gperftools/profiler.h>
  31. #endif // OPEN_PERF
  32. #include <boost/date_time/posix_time/posix_time.hpp>
  33. #include "../mod_ResourceWatcher/ResourceWatcher_msg_g.h"
  34. #include "CommEntityUtil.hpp"
  35. #define COMPKEY_TERMINATE ((UINT_PTR) 0)
  36. #define COMPKEY_STATUS ((UINT_PTR) 1)
  37. #define COMPKEY_JOBOBJECT ((UINT_PTR) 2)
  38. void DbgByCefControl(const char * strMethod, const char* buf)
  39. {
  40. #if defined(_MSC_VER)
  41. doWithDebugModeData(strMethod, buf);
  42. #endif //_MSC_VER
  43. }
  44. namespace Chromium {
  45. void ChromiumSession::Handle_OpenBrowser(SpReqAnsContext<ChromiumSrv_OpenBrowser_Req, ChromiumSrv_OpenBrowser_Ans>::Pointer ctx)
  46. {
  47. DbgToBeidou(ctx->link, __FUNCTION__)();
  48. m_pEntity->OpenBrowser(ctx);
  49. }
  50. void ChromiumSession::Handle_CloseBrowser(SpReqAnsContext<ChromiumSrv_CloseBrowser_Req, ChromiumSrv_CloseBrowser_Ans>::Pointer ctx)
  51. {
  52. DbgToBeidou(ctx->link, __FUNCTION__)();
  53. m_pEntity->CloseBrowser(ctx);
  54. }
  55. void ChromiumSession::Handle_OpenCommonPage(SpReqAnsContext<ChromiumSrv_OpenCommonPage_Req, ChromiumSrv_OpenCommonPage_Ans>::Pointer ctx)
  56. {
  57. DbgToBeidou(ctx->link, __FUNCTION__)();
  58. m_pEntity->OpenCommonPage(ctx);
  59. }
  60. void ChromiumSession::Handle_CloseCommonPage(SpReqAnsContext<ChromiumSrv_CloseCommonPage_Req, ChromiumSrv_CloseCommonPage_Ans>::Pointer ctx)
  61. {
  62. DbgToBeidou(ctx->link, __FUNCTION__)();
  63. m_pEntity->CloseCommonPage(ctx);
  64. }
  65. CChromiumEntity::CChromiumEntity() :m_pWsServer(NULL), m_iTcpBridgePort(4504), m_pTimerListener(NULL), m_strCustomMainUrl(true)
  66. , m_runAd(false), m_runMain(false), m_runExtend(false), m_runLogin(false), m_withBrowser(false), m_withMin(false), m_withClose(false)
  67. , m_withDebugMode(false), m_withMagic(false), m_withNoFileLog(false), m_installMode(false), m_withMedia(false), m_withSpecialTest(false), m_withConsole(false),
  68. m_withLinkLog(false), m_withUnsafeAd(false)
  69. {
  70. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CChromiumEntity constructor");
  71. //boost::thread(boost::bind(&CChromiumEntity::CefClintNotify, this)).detach(); //后台自动运行
  72. }
  73. CChromiumEntity::~CChromiumEntity()
  74. {
  75. if (NULL != m_pWsServer)
  76. {
  77. delete m_pWsServer;
  78. m_pWsServer = NULL;
  79. }
  80. //DeleteCriticalSection(&g_csInvokFreeRDP);
  81. }
  82. #if (defined _WIN32 || defined _WIN64)
  83. void CChromiumEntity::JobNotify() {
  84. TCHAR sz[2000] = _T("");
  85. BOOL fDone = FALSE;
  86. while (!fDone) {
  87. DWORD dwBytesXferred;
  88. ULONG_PTR CompKey;
  89. LPOVERLAPPED po;
  90. GetQueuedCompletionStatus(m_hIOCP, &dwBytesXferred, &CompKey, &po, INFINITE);
  91. fDone = (CompKey == COMPKEY_TERMINATE);
  92. if (CompKey == COMPKEY_JOBOBJECT) {
  93. switch (dwBytesXferred) {
  94. case JOB_OBJECT_MSG_END_OF_JOB_TIME:
  95. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Job time limit reached");
  96. break;
  97. case JOB_OBJECT_MSG_END_OF_PROCESS_TIME:
  98. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Job process (Id=%d) time limit reached", po);
  99. break;
  100. case JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT:
  101. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Too many active processes in job");
  102. break;
  103. case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO:
  104. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Job contains no active processes");
  105. break;
  106. case JOB_OBJECT_MSG_NEW_PROCESS:
  107. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("New process (Id=%d) in Job", po);
  108. break;
  109. case JOB_OBJECT_MSG_EXIT_PROCESS:
  110. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Process (Id=%d) terminated", po);
  111. break;
  112. case JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS:
  113. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Process (Id=%d) terminated abnormally", po);
  114. break;
  115. case JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT:
  116. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Process (Id=%d) exceeded memory limit", po);
  117. break;
  118. case JOB_OBJECT_MSG_JOB_MEMORY_LIMIT:
  119. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Process (Id=%d) exceeded job memory limit", po);
  120. break;
  121. default:
  122. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Unknown notification: %d", dwBytesXferred);
  123. break;
  124. }
  125. CompKey = 1;
  126. }
  127. }
  128. }
  129. #endif
  130. void CChromiumEntity::OpenCommonPage(SpReqAnsContext<ChromiumSrv_OpenCommonPage_Req, ChromiumSrv_OpenCommonPage_Ans>::Pointer ctx)
  131. {
  132. auto openCommonPageThread = [this](SpReqAnsContext<ChromiumSrv_OpenCommonPage_Req, ChromiumSrv_OpenCommonPage_Ans>::Pointer ctx)
  133. {
  134. LOG_FUNCTION();
  135. boost::unique_lock<boost::mutex> commonPageLock(m_commonPageLock);
  136. std::string strTitle = ctx->Req.title.GetData();
  137. std::string strUrl = ctx->Req.url.GetData();
  138. int width = ctx->Req.width;
  139. int height = ctx->Req.height;
  140. int point_x = ctx->Req.point_x;
  141. int point_y = ctx->Req.point_y;
  142. std::string strTop = ctx->Req.top.GetData();
  143. #ifdef RVC_OS_WIN
  144. auto ret = CModTools::get_mutable_instance().startCommonPage(strTitle, strUrl, width, height, point_x, point_y, strTop);
  145. #else
  146. auto srcPids = getUosBrowserPIDs(CModTools::get_mutable_instance().getUosBrowser());
  147. auto ret = CModTools::get_mutable_instance().startCommonPage(strTitle, strUrl, width, height, point_x, point_y, strTop);
  148. std::this_thread::sleep_for(std::chrono::seconds(2));
  149. auto dstPids = getUosBrowserPIDs(CModTools::get_mutable_instance().getUosBrowser());
  150. if (m_commonPageArr.find(strTitle) == m_commonPageArr.end())
  151. {
  152. std::vector<int> tmp;
  153. m_commonPageArr[strTitle] = tmp;
  154. }
  155. std::vector<int> difference;
  156. // 使用 std::set_difference 查找差值
  157. std::set_difference(dstPids.begin(), dstPids.end(), srcPids.begin(), srcPids.end(), std::back_inserter(difference));
  158. /*
  159. for (auto it : srcPids)
  160. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("srcPids %d", it);
  161. for (auto it : dstPids)
  162. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("dstPids %d", it);
  163. */
  164. for (auto it : difference)
  165. {
  166. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("open commonPage %d", it);
  167. m_commonPageArr[strTitle].push_back(it);
  168. }
  169. #endif
  170. ctx->Answer(ret.first, ret.first);
  171. };
  172. std::thread(openCommonPageThread, ctx).detach();
  173. }
  174. void CChromiumEntity::CloseCommonPage(SpReqAnsContext<ChromiumSrv_CloseCommonPage_Req, ChromiumSrv_CloseCommonPage_Ans>::Pointer ctx)
  175. {
  176. auto closePage = [this](SpReqAnsContext<ChromiumSrv_CloseCommonPage_Req, ChromiumSrv_CloseCommonPage_Ans>::Pointer ctx)
  177. {
  178. LOG_FUNCTION();
  179. boost::unique_lock<boost::mutex> commonPageLock(m_commonPageLock);
  180. std::string strName = ctx->Req.title.GetData();
  181. #ifdef RVC_OS_WIN
  182. CModTools::get_mutable_instance().stopCommonPage(strName);
  183. std::this_thread::sleep_for(std::chrono::seconds(1));
  184. CModTools::get_mutable_instance().stopCommonPage(strName);
  185. #else
  186. if (m_commonPageArr.find(strName) != m_commonPageArr.end())
  187. {
  188. auto arr = m_commonPageArr[strName];
  189. for (auto it : arr)
  190. {
  191. CSimpleStringA cmd = CSimpleStringA::Format("sudo kill -9 %d", it);
  192. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CloseCommonPage %s", cmd.GetData());
  193. system(cmd.GetData());
  194. }
  195. arr.clear();
  196. m_commonPageArr[strName] = arr;
  197. }
  198. std::this_thread::sleep_for(std::chrono::seconds(1));
  199. #endif // RVC_OS_WIN
  200. ctx->Answer(ErrorCodeEnum::Error_Succeed);
  201. };
  202. std::thread(closePage, ctx).detach();
  203. }
  204. void CChromiumEntity::CloseBrowser(SpReqAnsContext<ChromiumSrv_CloseBrowser_Req, ChromiumSrv_CloseBrowser_Ans>::Pointer ctx)
  205. {
  206. CSimpleString strType = ctx->Req.type;
  207. CSimpleString strNmae = ctx->Req.name;
  208. DbgToBeidou(ctx->link, "CloseBrowser")();
  209. if (!strType.Compare((+ERR_PAGE_REASON::OutsideRequest)._to_string(), true))
  210. {
  211. CModTools::get_mutable_instance().StopSingleChromiumBrowserByName((+ERR_PAGE_REASON::OutsideRequest)._to_string());
  212. ctx->Answer(ErrorCodeEnum::Error_Succeed);
  213. }
  214. else if (!strType.Compare((+ERR_PAGE_REASON::SpecialPageFromOtherEntity)._to_string(), true))
  215. {
  216. CSimpleStringA dstBrowserName = strType + "_" + strNmae;
  217. CModTools::get_mutable_instance().StopSingleChromiumBrowserByName(dstBrowserName.GetData());
  218. ctx->Answer(ErrorCodeEnum::Error_Succeed);
  219. }
  220. else
  221. {
  222. ctx->Answer(ErrorCodeEnum::Error_NoTarget);
  223. }
  224. }
  225. void CChromiumEntity::OpenBrowser(SpReqAnsContext<ChromiumSrv_OpenBrowser_Req, ChromiumSrv_OpenBrowser_Ans>::Pointer ctx)
  226. {
  227. std::shared_ptr<void> CleanParamFun((void*)0, [&](void*) {
  228. CModTools::get_mutable_instance().SetSpecialPageParam("", "", "", 0);
  229. });
  230. CSimpleStringA strType = ctx->Req.type;
  231. DbgToBeidou(ctx->link, "OpenBrowser")();
  232. if (!strType.Compare((+ERR_PAGE_REASON::OutsideRequest)._to_string(), true))
  233. {
  234. CSimpleStringA strUrl = ctx->Req.mainUrl, strUrl2 = ctx->Req.viceUrl;
  235. if (strUrl.IsNullOrEmpty()) {
  236. ctx->Answer(Error_Param);
  237. return;
  238. }
  239. auto ret = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::OutsideRequest, std::make_tuple(strUrl.GetData(), strUrl2.GetData()));
  240. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open OutsideRequest browser page %s return %d", (LPCTSTR)strUrl, ret.first);
  241. ctx->Answer(ret.first);
  242. }
  243. else if (!strType.Compare((+ERR_PAGE_REASON::SpecialPageFromOtherEntity)._to_string(), true))
  244. {
  245. CSimpleStringA strUrl = ctx->Req.mainUrl, strUrl2 = ctx->Req.viceUrl, sizeParam = ctx->Req.param1
  246. , pointParam = ctx->Req.param2, browserName = ctx->Req.name;
  247. CSimpleStringA dstBrowserName = strType + "_" + browserName;
  248. int browserTopZ = ctx->Req.top;
  249. CModTools::get_mutable_instance().SetSpecialPageParam(dstBrowserName.GetData(), sizeParam.GetData(), pointParam.GetData(), browserTopZ);
  250. //用一个临时变量解决,可能在高并发时有问题。
  251. auto ret = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::SpecialPageFromOtherEntity,
  252. std::make_tuple(strUrl.GetData(), strUrl2.GetData()));
  253. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open %s browser page %s return %d", dstBrowserName.GetData(), (LPCTSTR)strUrl, ret.first);
  254. ctx->Answer(ret.first);
  255. }
  256. else
  257. ctx->Answer(ErrorCodeEnum::Error_NoTarget);
  258. }
  259. void CChromiumEntity::OnPaused() {
  260. #ifdef OPEN_PERF
  261. ProfilerStop();//停止性能分析
  262. #endif // OPEN_PERF
  263. }
  264. void CChromiumEntity::OnPreStart_Init(CAutoArray<CSimpleStringA>& strArgs, CSmartPointer<ITransactionContext>& pTransactionContext)
  265. {
  266. LOG_FUNCTION();
  267. #ifdef OPEN_PERF
  268. auto profStr = CSimpleString::Format("chromiumAnalyze_%s.prof", generateTimeStr(true).c_str());
  269. std::thread([](std::string str) {
  270. ProfilerStart(str.c_str());//开启性能分析
  271. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Generate chromiumAnalyze, %s", str.c_str());
  272. }, profStr.GetData()).detach();
  273. #endif // OPEN_PERF
  274. //init the chrome params from centersetting
  275. FetchCustomMainUrl(strArgs);
  276. CModTools::get_mutable_instance().InitCModTools(this);
  277. #if (defined _WIN32 || defined _WIN64)
  278. const int ArgsCount = strArgs.GetCount();
  279. LOG_TRACE("strArgs.GetCount() = %d", ArgsCount);
  280. for (int i = 0; i < ArgsCount; ++i) {
  281. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("strArgs[%d] = %s", i, strArgs[i].GetData());
  282. }
  283. if (ArgsCount == 1) {
  284. m_strCustomMainUrl = strArgs[0];
  285. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Get custom main ulr: %s", m_strCustomMainUrl.GetData());
  286. }
  287. else if (ArgsCount == 2)
  288. {
  289. m_strCustomMainUrl = strArgs[0];
  290. m_strCustomAdUrl = strArgs[1];
  291. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Get custom main url: %s, ad url: %s", m_strCustomMainUrl.GetData(), m_strCustomAdUrl.GetData());
  292. }
  293. #endif
  294. GetFunction()->GetSystemStaticInfo(m_sysInfo);
  295. if (!IsConfigMode()) {
  296. CSmartPointer<IConfigInfo> spConfig;
  297. if (Error_Succeed == GetFunction()->OpenConfig(Config_CenterSetting, spConfig))//特别坑,这个OpenConfig返回一直都是success
  298. {
  299. auto webMaskKey = CSimpleString::Format("WebMask_%s", m_sysInfo.strMachineType.GetData());
  300. CSimpleString webMaskStr;
  301. if (Error_Succeed == spConfig->ReadConfigValue("Chromium", webMaskKey.GetData(), webMaskStr))
  302. {
  303. auto maskArr = webMaskStr.Split('|');
  304. for (int i = 0; i < maskArr.GetCount(); i++)
  305. {
  306. auto trimStr = maskArr[i].Trim();
  307. if (!trimStr.Compare("ad", true))//will open ad browser
  308. m_runAd = true;
  309. else if (!trimStr.Compare("main", true))//will open main browser
  310. m_runMain = true;
  311. else if (!trimStr.Compare("extend", true))//will open extend browser
  312. m_runExtend = true;
  313. else if (!trimStr.Compare("login", true))//will open login(User Desktop) browser
  314. m_runLogin = true;
  315. else if (!trimStr.Compare("with_browser", true))//will not open any browser
  316. m_withBrowser = true;
  317. else if (!trimStr.Compare("with_min", true))//the errPage contains min button
  318. m_withMin = true;
  319. else if (!trimStr.Compare("with_close", true))//the errPage contains close button
  320. m_withClose = true;
  321. else if (!trimStr.Compare("with_debugmode", true))//the browser will open remote control function
  322. m_withDebugMode = true;
  323. else if (!trimStr.Compare("with_magic", true))//the browser will open special queue for log sender.
  324. m_withMagic = true;
  325. else if (!trimStr.Compare("with_media", true))//the browser will support media play and RTC function
  326. m_withMedia = true;
  327. else if (!trimStr.Compare("with_unsafe_ad", true))
  328. m_withUnsafeAd = g_unsafeAd = true;
  329. else if (!trimStr.Compare("with_specialTest", true))//chromium will run specical test
  330. m_withSpecialTest = true;
  331. else if (!trimStr.Compare("with_LinkLog", true))//control do_sendJson to print more logs(request)
  332. m_withLinkLog = true;
  333. else if (!trimStr.Compare("with_nofilelog", true))//DbgEx do not print logs to local storage, but DbgEx() is discard.
  334. m_withNoFileLog = true;
  335. else if (!trimStr.Compare("with_console", true))//control browser will print console logs
  336. g_withConsole = m_withConsole = true;
  337. }
  338. #if (defined _WIN32 || defined _WIN64)
  339. if (m_withDebugMode)
  340. CModTools::get_mutable_instance().setWithDebugMode(m_withDebugMode);
  341. #else
  342. //对于UOS来说,没有最小化和关闭按钮
  343. m_withMin = false;
  344. m_withClose = false;
  345. #endif
  346. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("MachineType: %s, find %s, readStr:%s, m_runAd:%d, m_runMain:%d, m_runExtend:%d, m_runLogin:%d, \
  347. m_withBrowser:%d, with_min:%d, with_close:%d, m_withDebugMode:%d, m_withMagic:%d, m_withNoFileLog:%d, m_withMedia:%d, m_withSpecialTest:%d, m_withConsole:%d, m_withLinkLog:%d",
  348. m_sysInfo.strMachineType.GetData(), webMaskKey.GetData(), webMaskStr.GetData(), m_runAd, m_runMain, m_runExtend, m_runLogin, m_withBrowser
  349. ,m_withMin, m_withClose, m_withDebugMode, m_withMagic, m_withNoFileLog, m_withMedia, m_withSpecialTest, m_withConsole, m_withLinkLog);
  350. if (m_withMin)
  351. CModTools::get_mutable_instance().setWithMin(m_withMin);
  352. if (m_withClose)
  353. CModTools::get_mutable_instance().setWithClose(m_withClose);
  354. g_logToFile = !m_withNoFileLog;
  355. g_withMedia = m_withMedia;
  356. g_withLinkLog = m_withLinkLog;
  357. int forceCacheClean = false;
  358. if (Error_Succeed == spConfig->ReadConfigValueInt("Chromium", "forceCacheClean", forceCacheClean) && forceCacheClean)
  359. {
  360. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("forceCacheClean, call OnOnBrowserCacheClean");
  361. ResourceWatcher::BrowserCacheClean evt;
  362. evt.needClean = 1;
  363. OnBrowserCacheClean(NULL, 0, 0, evt);
  364. }
  365. }
  366. else
  367. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("can not find %s, use default", webMaskKey.GetData());
  368. }
  369. if (!m_runAd && !m_runMain && !m_runExtend && !m_withBrowser)
  370. {
  371. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("can not open centerSetting, maybe fault");
  372. }
  373. #ifdef RVC_OS_WIN
  374. if (m_withMagic)
  375. {
  376. std::string magicStr = CModTools::get_mutable_instance().getMagicStr();
  377. boost::thread(boost::bind(SaveCefclientLog, magicStr)).detach();
  378. }
  379. #endif
  380. }
  381. if (m_withSpecialTest)
  382. {
  383. CSimpleString strPath;
  384. GetFunction()->GetPath("Downloads", strPath);
  385. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Downloads path %s, ", strPath.GetData());
  386. }
  387. }
  388. bool CChromiumEntity::OnPreStart_socketStart(CAutoArray<CSimpleStringA>& strArgs, CSmartPointer<ITransactionContext>& pTransactionContext)
  389. {
  390. ErrorCodeEnum Error;
  391. if (Error_Succeed != (Error = GetFunction()->StartTcpBridgeServer(m_iTcpBridgePort)))
  392. {
  393. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start tcp bridge server failed!");
  394. pTransactionContext->SendAnswer(Error);
  395. return false;
  396. }
  397. // load all struct define xml & start websocket server
  398. CSimpleStringA strStructPath;
  399. GetFunction()->GetPath("Base", strStructPath);
  400. strStructPath.Append(CSimpleStringA(SPLIT_SLASH_STR) + "res" + SPLIT_SLASH_STR + "StructConfig" + SPLIT_SLASH_STR);
  401. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find struct config files in path %s", strStructPath.GetData());
  402. m_pWsServer = new CWebsocketServer(strStructPath, this);
  403. m_pWsServer->run();
  404. return true;
  405. }
  406. bool CChromiumEntity::OnPreStart_register(CAutoArray<CSimpleStringA>& strArgs, CSmartPointer<ITransactionContext>& pTransactionContext)
  407. {
  408. ErrorCodeEnum Error;
  409. #if defined(RVC_OS_LINUX)
  410. Error = GetFunction()->SubscribeLog(m_uuidAllFault, this, Log_Notify, Severity_High, Error_IgnoreAll, -2, NULL, false);
  411. if (Error_Succeed == Error) {
  412. this->GetFunction()->GetPrivilegeFunction()->RefreshFrameworkState(FrameworkState_NotDisturb);
  413. } else {
  414. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("subscribe log for notify failed! %s", SpStrError(Error));
  415. }
  416. #endif //RVC_OS_LINUX
  417. if (!m_withBrowser)
  418. {
  419. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("subscribe AccessAuthorization %s, %d",
  420. Error_Succeed == (Error = GetFunction()->SubscribeLog(m_uuidAccessAuth, this, Log_Event, Severity_None, Error_IgnoreAll, -1, "AccessAuthorization")) ? "success" : "failed", Error);
  421. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("subscribe ResourceWatcher %s, %d",
  422. Error_Succeed == (Error = GetFunction()->SubscribeBroadcast("ResourceWatcher", NULL, this, m_uuidResourceWatch)) ? "success" : "failed", Error);
  423. if (Error_Succeed != GetFunction()->RegistSysVarEvent("UIState", this))
  424. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RegistSysVarEvent UIState failed!");
  425. if (Error_Succeed != GetFunction()->RegistSysVarEvent("TerminalStage", this))
  426. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RegistSysVarEvent TerminalStage failed!");
  427. if (Error_Succeed != GetFunction()->RegistSysVarEvent("CardStoreInUse", this))
  428. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RegistSysVarEvent CardStoreInUse failed!");
  429. }
  430. return true;
  431. }
  432. bool CChromiumEntity::OnPreStart_openWeb()
  433. {
  434. if (m_runExtend)
  435. openExtendPage();
  436. if (!m_runMain)//不启动页面
  437. return true;
  438. do
  439. {
  440. CSimpleStringA t_terminalState;
  441. ErrorCodeEnum rc = ErrorCodeEnum::Error_Succeed;
  442. if ((rc = GetFunction()->GetSysVar("TerminalStage", t_terminalState)) != ErrorCodeEnum::Error_Succeed)
  443. {
  444. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s read TerminalStage Error %d, maybe not exist", __FUNCTION__, rc);
  445. break;
  446. }
  447. else if ('A' != t_terminalState[0] && 'Z' != t_terminalState[0])
  448. {
  449. if (m_withBrowser)
  450. break;//run IEBrowser
  451. if ('X' == t_terminalState[0])
  452. {
  453. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("do not begin accessAuth, terminalStage X, do nothing.");
  454. break;
  455. }
  456. else if ('S' == t_terminalState[0])
  457. {
  458. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::warnPrompt,
  459. std::tuple <std::string, std::string>(m_sysInfo.strTerminalID.GetData(), generateTimeStr()));
  460. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("access failed, open page warnPrompt %s, %d", Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  461. }
  462. else
  463. {
  464. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::breakdown,
  465. std::tuple <std::string, std::string>(m_sysInfo.strTerminalID.GetData(), generateTimeStr()));
  466. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("access failed, open page breakdown %s, %d", Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  467. }
  468. }
  469. else
  470. {
  471. if (m_runAd) openAdPage();
  472. openMainPage();
  473. #if (defined _WIN32 || defined _WIN64)
  474. if (m_withDebugMode)
  475. getNetworkInfo(L"127.0.0.1:9222", L"", &DbgByCefControl);
  476. #endif
  477. }
  478. } while (false);
  479. return true;
  480. }
  481. void CChromiumEntity::openMainPage()
  482. {
  483. #if (defined _WIN32 || defined _WIN64)
  484. generateCefclientTimer();
  485. #else
  486. CSystemRunInfo sysruninfo;
  487. GetFunction()->GetSystemRunInfo(sysruninfo);
  488. if (!(sysruninfo.dwBootOption & SystemBootOptionEnum::BootOption_Test))
  489. generateCefclientTimer();//非--test时,才会打开浏览器
  490. #endif
  491. }
  492. void CChromiumEntity::openAdPage()
  493. {
  494. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::Ad);
  495. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open page Ad %s, pid:%d", Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  496. }
  497. void CChromiumEntity::openExtendPage()
  498. {
  499. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::extend);
  500. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open page extend %s, pid:%d", Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  501. }
  502. void CChromiumEntity::openInstallPage()
  503. {
  504. /*
  505. LogWarn(Severity_Middle, Error_NotSupport, LOG_WARN_CHROMIUM_INSTALL_NOTSURPORT,
  506. CSimpleStringA::Format("Not surport install mode").GetData());
  507. return;
  508. */
  509. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::Install);
  510. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open page install %s, pid:%d",
  511. Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  512. }
  513. void CChromiumEntity::openStartupPage()
  514. {
  515. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::startup);
  516. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open page startup %s, pid:%d",
  517. Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  518. }
  519. void CChromiumEntity::openPerformanceMonitorPage()
  520. {
  521. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::performance_monitor);
  522. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open page performance_monitor %s, pid:%d",
  523. Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  524. }
  525. void CChromiumEntity::startWithCfg()
  526. {
  527. OnPreStart_Init(m_strArgs, m_pTransactionContext);//初始化部分, perf ,killchromium, signal, get custom url
  528. if (!IsConfigMode()) {
  529. if (!OnPreStart_register(m_strArgs, m_pTransactionContext)) {
  530. return;
  531. }
  532. //if contain default setting, then oepn web by setting
  533. #if (defined _WIN32 || defined _WIN64)
  534. if (m_strArgs.GetCount())
  535. {
  536. if (!m_strCustomMainUrl.IsNullOrEmpty())
  537. openMainPage();
  538. if (!m_strCustomAdUrl.IsNullOrEmpty())
  539. openAdPage();
  540. return;
  541. }
  542. #endif
  543. if (!OnPreStart_openWeb()) {
  544. return;
  545. }
  546. }
  547. else
  548. {
  549. openInstallPage();
  550. LogEvent(Severity_High, LOG_EVT_CHROMIUM_OPEN_INSTALLPAGE, CSimpleStringA::Format("open install page"));
  551. }
  552. }
  553. void CChromiumEntity::OnPreStart(CAutoArray<CSimpleStringA> strArgs, CSmartPointer<ITransactionContext> pTransactionContext)
  554. {
  555. #if defined(RVC_OS_LINUX)
  556. // clear all the browser
  557. CModTools::get_mutable_instance().killAllChromium();
  558. DoBrowserCacheClearJob();
  559. CSimpleStringA strDbgPath;
  560. GetFunction()->GetPath("Dbg", strDbgPath);
  561. set_traceback_path(strDbgPath.GetData());
  562. boost::thread([]() {
  563. for (auto i = 1; i < 28; i++)
  564. {
  565. if (SIGTERM == i)
  566. signal(i, [](int signum)->void {
  567. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("receive signal:%d, closeChromium", signum);
  568. CModTools::get_mutable_instance().killAllChromiumByThread(3);
  569. CWebsocketServer::stopServer();
  570. signal(signum, SIG_DFL);
  571. raise(signum);
  572. });
  573. else if (SIGSEGV == i || SIGABRT == i)
  574. signal(i, &seg_signal_handler);
  575. else if (SIGPROF == i || SIGALRM == i || SIGVTALRM == i)
  576. continue;
  577. else
  578. signal(i, &normal_signal_handle);
  579. }
  580. }).detach();
  581. #endif
  582. //all the init,register,openWeb run thread
  583. auto startFun = [&]() {
  584. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create thread:%s", __FUNCTION__);
  585. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnPreStart - startFun");
  586. // init cef logger first
  587. #if (defined _WIN32 || defined _WIN64)
  588. if (!logProducer)
  589. logProducer = create_log_producer_storage("cefclient_logger", "0", "", "", "");
  590. #else
  591. CSimpleString dbgPath;
  592. GetFunction()->GetPath("Dbg", dbgPath);
  593. std::string dstDbgPath = dbgPath.GetData();
  594. dstDbgPath.append(SPLIT_SLASH_STR).append("mod_chromium");
  595. #endif
  596. OnPreStart_Init(m_strArgs, m_pTransactionContext);//初始化部分, perf ,killchromium, signal, get custom url
  597. boost::thread(boost::bind(&CChromiumEntity::DoWithSysVarEvent, this)).detach();//用于处理sysvar,避免由于阻塞动作,导致实体卡住,lost
  598. if (!OnPreStart_socketStart(m_strArgs, m_pTransactionContext)) {//OnPreStart_socketStart()->new CWebsocketServer(strStructPath, this) 时间过长
  599. return;
  600. }
  601. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnPreStart - OnPreStart_socketStart end");
  602. //the system info may be not complete.If the device is not install ,it can't not read the terminalNo.
  603. CSystemStaticInfo t_sysInfo;
  604. GetFunction()->GetSystemStaticInfo(t_sysInfo);
  605. if (t_sysInfo.strTerminalID.GetLength() == 0)// the machine is in install mode, hence start a simple init and open the install page
  606. {
  607. openStartupPage();//open startup page in install mode
  608. m_installMode = true;
  609. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("subscribe VtmLoader %s",
  610. (Error_Succeed == GetFunction()->SubscribeLog(m_uuidVTMLoader, this, Log_Event, Severity_None, Error_IgnoreAll, -1, "VtmLoader")) ? "success" : "failed");
  611. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("startWithCfg:open install page");
  612. //if in install mode, need clear
  613. CSimpleString tmpCacheDir;
  614. if (Error_Succeed != GetFunction()->GetPath("Temp", tmpCacheDir) || tmpCacheDir.GetLength() == 0)
  615. {
  616. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnBrowserCacheClean get cache path err");
  617. return;
  618. }
  619. #if (defined _WIN32 || defined _WIN64)
  620. auto tmpArr = find_files(tmpCacheDir.GetData(), "cefCache*", true);
  621. std::shared_ptr<std::vector<std::string>> tmpDirArr(new std::vector<std::string>());
  622. for each (auto it in tmpArr)
  623. tmpDirArr.get()->push_back(it);
  624. auto runCacheClean = [](std::shared_ptr<std::vector<std::string>> p) ->void {
  625. //CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::breakdown, true);//close all tab
  626. for each (auto it in *p.get())
  627. {
  628. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_BROWSER_CACHE_CLEAER, CSimpleStringA::Format("clear chromium browser cache %s %s", it.c_str(),
  629. RemoveDirRecursive(it.c_str()) ? "success" : "fail"));
  630. }
  631. };
  632. runCacheClean(tmpDirArr);
  633. #else
  634. //uos 由于无guard,需要重启整个chromium实体
  635. //CModTools::get_mutable_instance().killAllChromium();
  636. auto tmpDirArr = find_files(tmpCacheDir.GetData(), "cefCache*", true);
  637. auto uosTmpDirArr = find_files(tmpCacheDir.GetData(), "UOSBrowser*", true);
  638. std::for_each(uosTmpDirArr.begin(), uosTmpDirArr.end(), [&](std::string tmp) {
  639. tmpDirArr.push_back(tmp);
  640. });//insert uosTmpDirArr into tmpDirArr
  641. for (auto it = tmpDirArr.begin(); it != tmpDirArr.end(); it++)
  642. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_BROWSER_CACHE_CLEAER, CSimpleStringA::Format("clear chromium browser cache %s %s", it->c_str(),
  643. RemoveDirRecursive(it->c_str()) ? "success" : "fail"));
  644. #endif
  645. boost::this_thread::sleep_for(boost::chrono::seconds(3));
  646. #ifdef RVC_OS_LINUX
  647. auto srcPids = getUosBrowserPIDs(CModTools::get_mutable_instance().getUosBrowser());
  648. #endif // RVC_OS_LINUX
  649. startWithCfg();//it will open install page
  650. std::this_thread::sleep_for(std::chrono::seconds(3));
  651. LogWarn(Severity_Low, Error_Debug, LOG_SLV_CHROMIUM_URLOPEN, "正在启动业务界面");
  652. #if defined(RVC_OS_LINUX)
  653. for (auto it : srcPids)
  654. {
  655. CSimpleStringA cmd = CSimpleStringA::Format("sudo kill -9 %d", it);
  656. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CloseCommonPage %s", cmd.GetData());
  657. system(cmd.GetData());
  658. }
  659. #else
  660. CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::startup);
  661. #endif
  662. return;
  663. }
  664. CSimpleStringA t_terminalState;
  665. if (ErrorCodeEnum::Error_Succeed == GetFunction()->GetSysVar("TerminalStage", t_terminalState))
  666. {
  667. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnPreStart TerminalStage:%s", t_terminalState.GetData());
  668. CAutoArray<CSimpleStringA> strErrorCodeArr;
  669. CAutoArray<CSimpleStringA> strDescriptionArr;
  670. CAutoArray<CSimpleStringA> strRemarkArr;
  671. auto ret = GetFunction()->GetPrivilegeFunction()->GetVTMErrMsgArr(strErrorCodeArr, strDescriptionArr, strRemarkArr);
  672. if (Error_Succeed == ret)
  673. InitUserCodeToMsgTip(strErrorCodeArr, strDescriptionArr, strRemarkArr);
  674. if (m_withSpecialTest)
  675. {
  676. CSimpleStringA strDescription, strVTMCode;
  677. GetFunction()->GetVTMErrMsg(123456, strDescription, strVTMCode);
  678. }
  679. //should not open startup page, since it is already run before.
  680. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("startWithCfg:open normal page");
  681. startWithCfg();//属于chromium重启或者其他情况,已经初始化好配置, open main, ad and other page
  682. }
  683. else
  684. {
  685. openStartupPage();//open startup page in normal mode
  686. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("subscribe VtmLoader %s",
  687. (Error_Succeed == GetFunction()->SubscribeLog(m_uuidVTMLoader, this, Log_Event, Severity_None, Error_IgnoreAll, -1, "VtmLoader")) ? "success" : "failed");
  688. }
  689. };
  690. boost::thread t(startFun);
  691. // 等待线程 3 秒,如果超时则 detach 线程
  692. if (!t.timed_join(boost::chrono::seconds(3))) {
  693. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Timed out, detaching thread.");
  694. t.detach();
  695. }
  696. m_strArgs = strArgs;
  697. m_pTransactionContext = pTransactionContext;
  698. pTransactionContext->SendAnswer(Error_Succeed);
  699. #ifdef TEST_FUNCTION
  700. boost::thread(boost::bind(&CChromiumEntity::testLogError, this)).detach();
  701. #endif // #ifdef TEST_FUNCTION
  702. }
  703. bool CChromiumEntity::CheckIsCardStore() {
  704. return m_sysInfo.strMachineType.IsEndWith("CardStore", true) || m_sysInfo.strMachineType.IsEndWith("CardPrinter", true);
  705. }
  706. void CChromiumEntity::DoWithSysVarEvent()
  707. {
  708. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create thread:%s", __FUNCTION__);
  709. while (true)
  710. {
  711. if (m_eventArr.size() == 0)
  712. {
  713. boost::this_thread::sleep_for(boost::chrono::microseconds(100));
  714. continue;
  715. }
  716. m_eventContorl.lock();
  717. SYS_EVENT_PARAM curEvent = m_eventArr.front();
  718. m_eventArr.pop_front();
  719. m_eventContorl.unlock();
  720. if ((strnicmp(curEvent.key.c_str(), "UIState", strlen("UIState")) == 0))
  721. {
  722. if (strnicmp(curEvent.value.c_str(), "M", strlen("M")) == 0)
  723. {
  724. static bool firstEnter = true;
  725. if (firstEnter)
  726. {
  727. firstEnter = false;
  728. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("first Enter main page");
  729. m_firstStartMain.unlock();
  730. LogWarn(Severity_Low, Error_Debug, LOG_SLV_CHROMIUM_OPENSUCCESS,
  731. CSimpleStringA::Format("Chromium Enter main page success, %s", CModTools::get_mutable_instance().getFultureUrl().GetData()));
  732. }
  733. GetFunction()->UnregistSysVarEvent("UIState");
  734. }
  735. }
  736. /** 该事件有变化才会触发错误页 [Gifur@2022324]*/
  737. else if (0 == CSimpleStringA("TerminalStage").Compare(curEvent.key.c_str(), true))
  738. {
  739. if (0 == CSimpleStringA("A").Compare(curEvent.value.c_str(), true))
  740. {
  741. try
  742. {
  743. if (CModTools::get_mutable_instance().IsConfigWork())//url正常时才关闭
  744. {
  745. #if defined(RVC_OS_LINUX)
  746. auto srcPids = getUosBrowserPIDs(CModTools::get_mutable_instance().getUosBrowser());
  747. #endif // RVC_OS_UOS
  748. if (m_runAd) openAdPage();
  749. openMainPage();
  750. CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::breakdown);
  751. std::this_thread::sleep_for(std::chrono::seconds(3));
  752. LogWarn(Severity_Low, Error_Debug, LOG_SLV_CHROMIUM_URLOPEN, "正在启动业务界面");
  753. #if defined(RVC_OS_LINUX)
  754. for (auto it : srcPids)
  755. {
  756. CSimpleStringA cmd = CSimpleStringA::Format("sudo kill -9 %d", it);
  757. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CloseCommonPage %s", cmd.GetData());
  758. system(cmd.GetData());
  759. }
  760. #else
  761. CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::startup);
  762. #endif
  763. //DbgEx("UnregistSysVarEvent TerminalStage %s", Error_Succeed == GetFunction()->UnregistSysVarEvent("TerminalStage") ? "success" : "fail");
  764. }
  765. }
  766. catch (const std::exception& e)
  767. {
  768. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminalStage:A run exception, %s", e.what());
  769. }
  770. }
  771. else if (0 == CSimpleStringA("X").Compare(curEvent.value.c_str(), true))
  772. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminalStage X, do nothing.");
  773. else
  774. {
  775. try
  776. {
  777. if (!m_withBrowser)
  778. {
  779. #if defined(RVC_OS_LINUX)
  780. auto srcPids = getUosBrowserPIDs(CModTools::get_mutable_instance().getUosBrowser());
  781. #endif // RVC_OS_UOS
  782. #if defined(RVC_OS_LINUX)
  783. for (auto it : srcPids)
  784. {
  785. CSimpleStringA cmd = CSimpleStringA::Format("sudo kill -9 %d", it);
  786. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CloseCommonPage %s", cmd.GetData());
  787. system(cmd.GetData());
  788. }
  789. #else
  790. CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::startup);
  791. #endif
  792. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(
  793. 0 == CSimpleStringA("S").Compare(curEvent.value.c_str(), true) ? ERR_PAGE_REASON::warnPrompt : ERR_PAGE_REASON::breakdown,
  794. std::tuple < std::string, std::string>(m_sysInfo.strTerminalID.GetData(), generateTimeStr()));
  795. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("access failed, open err page %s, %d", Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  796. CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::main);
  797. }
  798. }
  799. catch (const std::exception& e)
  800. {
  801. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminalStage:other run exception, %s", e.what());
  802. }
  803. }
  804. }
  805. else if (0 == CSimpleStringA("CardStoreInUse").Compare(curEvent.key.c_str(), true) && CheckIsCardStore())
  806. {
  807. try
  808. {
  809. if (0 == CSimpleStringA("Y").Compare(curEvent.value.c_str(), true))
  810. {
  811. auto openRet = CModTools::get_mutable_instance().StartChromiumBrowser(ERR_PAGE_REASON::CardStoreIsBusy,
  812. std::tuple <std::string, std::string>(m_sysInfo.strTerminalID.GetData(), generateTimeStr()));
  813. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CardStoreIsBusy, open page CardStoreIsBusy %s, %d", Error_Succeed == openRet.first ? "success" : "fail", openRet.second);
  814. }
  815. else
  816. {
  817. CModTools::get_mutable_instance().StopChromiumBrowser_security(ERR_PAGE_REASON::CardStoreIsBusy, 2);
  818. }
  819. }
  820. catch (const std::exception& e)
  821. {
  822. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CardStoreInUse run exception, %s", e.what());
  823. }
  824. }
  825. }
  826. }
  827. #ifdef TEST_FUNCTION
  828. void CChromiumEntity::testLogError()
  829. {
  830. while(true)
  831. {
  832. LogError(SeverityLevelEnum::Severity_High, Error_Debug, LOG_WARN_CHROMIUM_VTMUSERMSG_ERR, "test log Error!");
  833. boost::this_thread::sleep_for(boost::chrono::seconds(1));
  834. }
  835. }
  836. #endif
  837. void CChromiumEntity::OnSysVarEvent(const char* pszKey, const char* pszValue, const char* pszOldValue, const char* pszEntityName)
  838. {
  839. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnSysVarEvent %s, old->new:%s->%s", pszKey, pszOldValue, pszValue);
  840. SYS_EVENT_PARAM curEvent;
  841. curEvent.key = std::string(pszKey);
  842. curEvent.value = std::string(pszValue);
  843. curEvent.oldValue = std::string(pszOldValue);
  844. curEvent.entityName = std::string(pszEntityName);
  845. boost::unique_lock<boost::mutex> eventArrLock(m_eventContorl);
  846. m_eventArr.push_back(curEvent);
  847. }
  848. void CChromiumEntity::OnPreClose(EntityCloseCauseEnum eCloseCause, CSmartPointer<ITransactionContext> pTransactionContext)
  849. {
  850. exitClean();
  851. pTransactionContext->SendAnswer(Error_Succeed);
  852. }
  853. void CChromiumEntity::exitClean()
  854. {
  855. static bool isExit = false;
  856. if (!isExit)
  857. {
  858. isExit = true;
  859. CModTools::get_mutable_instance().killAllChromiumByThread(3);
  860. delete m_pWsServer;
  861. if (m_pTimerListener != NULL)
  862. {
  863. GetFunction()->KillTimer(CHROMIUM_TIMER_ID);
  864. delete m_pTimerListener;
  865. m_pTimerListener = NULL;
  866. }
  867. GetFunction()->UnsubscribeBroadcast("IEBrowser");
  868. }
  869. }
  870. /** 查看启动顺序发现集中配置实体启动在本实体之前,无法调用集中配置的接口,随将实现搬到这里来 [Gifur@2021124]*/
  871. void CChromiumEntity::FetchCustomMainUrl(CAutoArray<CSimpleStringA>& strArgs)
  872. {
  873. #if (defined _WIN32 || defined _WIN64)
  874. #else
  875. const int ArgsCount = strArgs.GetCount();
  876. LOG_TRACE("strArgs.GetCount() = %d", ArgsCount);
  877. for (int i = 0; i < ArgsCount; ++i) {
  878. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("strArgs[%d] = %s", i, strArgs[i].GetData());
  879. }
  880. if (ArgsCount == 1) {
  881. m_strCustomMainUrl = strArgs[0];
  882. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Get custom main url: %s", m_strCustomMainUrl.GetData());
  883. if (!m_strCustomMainUrl.IsNullOrEmpty()) {
  884. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_DETECT_CUSTOM_FULTURE_URL_FROM_START,
  885. CSimpleStringA::Format("从模块入参获取自定义链接:%s", m_strCustomMainUrl.GetData()));
  886. }
  887. } else {
  888. CSmartPointer<IConfigInfo> pConfig;
  889. GetFunction()->OpenConfig(Config_Cache, pConfig);
  890. int cnt(0), currentUsing(0);
  891. pConfig->ReadConfigValueInt("CustomWebUrl", "Count", cnt);
  892. pConfig->ReadConfigValueInt("CustomWebUrl", "Current", currentUsing);
  893. if (cnt > 0 && currentUsing > 0) {
  894. CSimpleStringA strAdUrl(true);
  895. CSimpleStringA strSection = CSimpleStringA::Format("CustomWebUrl%d", currentUsing);
  896. pConfig->ReadConfigValue(strSection, "FultureUrl", m_strCustomMainUrl);
  897. pConfig->ReadConfigValue(strSection, "AdUrl", strAdUrl);
  898. if (!m_strCustomMainUrl.IsNullOrEmpty()) {
  899. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_DETECT_CUSTOM_FULTURE_URL_FROM_CONFIG,
  900. CSimpleStringA::Format("从本地维护桌面获取自定义链接:%s", m_strCustomMainUrl.GetData()));
  901. }
  902. }
  903. }
  904. #endif
  905. }
  906. void CChromiumEntity::OnLog(const CAutoArray<CUUID>& SubIDs, const CUUID nLogID, const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
  907. const DWORD dwSysError, const DWORD dwUserCode, const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
  908. const CAutoArray<DWORD>& Param, const char* pszEntityName, const char* pszModuleName, const char* pszMessage, const linkContext& pLinkInfo)
  909. {
  910. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnLog %x from entity %s, msg : %s", dwUserCode, NULL == pszEntityName ? "" : pszEntityName, NULL == pszMessage ? "" : pszMessage);
  911. switch (dwUserCode)
  912. {
  913. case Event_VtmLoader_GetConfig_Suc:
  914. g_hasInitCfg = true;
  915. case Event_VtmLoader_GetConfig_Fail:
  916. refreshLogLevel();//后置后需要刷新log level,因为chromium是先启动的实体
  917. if (m_installMode)//Do not init Entity again in install mode
  918. break;
  919. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("startWithCfg:open error or normal page");
  920. startWithCfg();//open errPage or normal page
  921. break;
  922. case Event_VtmLoader_GetVTMERRMSG_Suc:
  923. /*
  924. CSimpleString translatePath;
  925. GetFunction()->GetPath("Cfg", translatePath);
  926. translatePath.Append(CSimpleStringA(SPLIT_SLASH_STR) + "UserCodeToMsgTip.ini");
  927. InitTranslateFile(translatePath.GetData());
  928. */
  929. if (!GetFunction()->HasPrivilege())
  930. {
  931. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("no privilege");
  932. break;
  933. }
  934. {
  935. CAutoArray<CSimpleStringA> strErrorCodeArr;
  936. CAutoArray<CSimpleStringA> strDescriptionArr;
  937. CAutoArray<CSimpleStringA> strRemarkArr;
  938. auto ret = GetFunction()->GetPrivilegeFunction()->GetVTMErrMsgArr(strErrorCodeArr, strDescriptionArr, strRemarkArr);
  939. if (Error_Succeed == ret)
  940. InitUserCodeToMsgTip(strErrorCodeArr, strDescriptionArr, strRemarkArr);
  941. else
  942. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHROMIUM_VTMUSERMSG_ERR, CSimpleStringA::Format("GetVTMErrMsgArr err:%d", ret));
  943. if (m_withSpecialTest)
  944. {
  945. CSimpleStringA strDescription, strVTMCode;
  946. GetFunction()->GetVTMErrMsg(123456, strDescription, strVTMCode);
  947. }
  948. }
  949. break;
  950. default:
  951. break;
  952. }
  953. }
  954. void CChromiumEntity::OnBrowserCacheClean(const char* pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, ResourceWatcher::BrowserCacheClean& evt)
  955. {
  956. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnOnBrowserCacheClean, needClean:%d", evt.needClean);
  957. ErrorCodeEnum error = Error_Succeed;
  958. if (!evt.needClean)
  959. return;
  960. CSimpleString tmpCacheDir;
  961. if (Error_Succeed != (error = GetFunction()->GetPath("Temp", tmpCacheDir)) || tmpCacheDir.GetLength() == 0)
  962. {
  963. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnBrowserCacheClean get cache path err, %d", error);
  964. return;
  965. }
  966. #if (defined _WIN32 || defined _WIN64)
  967. CModTools::get_mutable_instance().lockGuard();
  968. auto tmpArr = find_files(tmpCacheDir.GetData(), "cefCache*", true);
  969. std::shared_ptr<std::vector<std::string>> tmpDirArr(new std::vector<std::string>());
  970. for each (auto it in tmpArr)
  971. tmpDirArr.get()->push_back(it);
  972. auto runCacheClean = [](std::shared_ptr<std::vector<std::string>> p) ->void {
  973. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create thread:%s", __FUNCTION__);
  974. CModTools::get_mutable_instance().StopChromiumBrowser(ERR_PAGE_REASON::breakdown, true);//close all tab
  975. for each (auto it in *p.get())
  976. {
  977. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_BROWSER_CACHE_CLEAER, CSimpleStringA::Format("clear chromium browser cache %s %s", it.c_str(),
  978. RemoveDirRecursive(it.c_str()) ? "success" : "fail"));
  979. }
  980. };
  981. boost::thread CacheCleanThread(runCacheClean, tmpDirArr);
  982. CacheCleanThread.timed_join(boost::posix_time::microseconds(10000));
  983. CModTools::get_mutable_instance().unlockGuard();
  984. /*
  985. if (m_runAd)
  986. {
  987. CModTools::get_mutable_instance().m_isAdOpen = false;
  988. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnBrowserCacheClean open add page");
  989. openAdPage();
  990. }
  991. */
  992. #else
  993. //uos 由于无guard,需要重启整个chromium实体
  994. CModTools::get_mutable_instance().killAllChromium();
  995. auto tmpDirArr = find_files(tmpCacheDir.GetData(), "cefCache*", true);
  996. auto uosTmpDirArr = find_files(tmpCacheDir.GetData(), "UOSBrowser*", true);
  997. std::for_each(uosTmpDirArr.begin(), uosTmpDirArr.end(), [&](std::string tmp) {
  998. tmpDirArr.push_back(tmp);
  999. });//insert uosTmpDirArr into tmpDirArr
  1000. for (auto it = tmpDirArr.begin(); it != tmpDirArr.end(); it++)
  1001. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_BROWSER_CACHE_CLEAER, CSimpleStringA::Format("clear chromium browser cache %s %s", it->c_str(),
  1002. RemoveDirRecursive(it->c_str()) ? "success" : "fail"));
  1003. if (m_pTimerListener != NULL)
  1004. {
  1005. GetFunction()->KillTimer(CHROMIUM_TIMER_ID);
  1006. delete m_pTimerListener;
  1007. m_pTimerListener = NULL;
  1008. }
  1009. if(!m_installMode)
  1010. OnPreStart_openWeb();//重新调用open web
  1011. #endif
  1012. }
  1013. void CChromiumEntity::generateCefclientTimer()
  1014. {
  1015. if (nullptr == m_pTimerListener)
  1016. {
  1017. m_pTimerListener = new TimerOutHelper<CChromiumEntity>(this, &CChromiumEntity::OnTaskTimerListener, NULL, false);
  1018. GetFunction()->SetTimer(CHROMIUM_TIMER_ID, m_pTimerListener, 2000); //间隔执行时间
  1019. }
  1020. }
  1021. int CChromiumEntity::getBrowserStartTimes() {
  1022. CAutoArray<CSimpleStringA> t_names;
  1023. CAutoArray<int> t_Idx;
  1024. CAutoArray<CEntityStartInfo> t_Infos;
  1025. GetFunction()->GetAllEntityStartInfo(t_names, t_Idx, t_Infos);
  1026. for (int i = 0; i < t_names.GetCount(); i++)
  1027. {
  1028. if (t_names[i] == GetEntityName())
  1029. return t_Infos[i].startTimes;
  1030. }
  1031. return -1;
  1032. }
  1033. void CChromiumEntity::checkUrlStartTime() {
  1034. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create thread:%s", __FUNCTION__);
  1035. std::string startTimeStr = boost::posix_time::to_iso_extended_string(boost::posix_time::microsec_clock::local_time());
  1036. int pos = startTimeStr.find('T');
  1037. startTimeStr.replace(pos, 1, std::string(" "));
  1038. pos = startTimeStr.find('.');
  1039. startTimeStr.replace(pos, 1, std::string(":"));
  1040. auto urlStartTime = boost::posix_time::microsec_clock::universal_time();
  1041. while (!m_firstStartMain.try_lock_for(boost::chrono::seconds(30)))
  1042. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("wait 30s, but slv did not start");
  1043. auto urlEndTime = boost::posix_time::microsec_clock::universal_time();
  1044. auto timeDuration = urlEndTime - urlStartTime;
  1045. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("slv start at %s, used %d ms", startTimeStr.c_str(), timeDuration.total_milliseconds());
  1046. if (1 == getBrowserStartTimes())
  1047. {
  1048. auto generateAlarmJson = [](CSimpleString entityName, CSimpleString startTime, int cost) ->CSimpleString {
  1049. return CSimpleString::Format("[{\"name\":\"%s\",\"time\":\"%s\",\"cost\":%d}]", entityName.GetData(), startTime.GetData(), cost);
  1050. };
  1051. LogWarn(Severity_Low, Error_Debug, LOG_TRACE_ENTITY_START_TIME, generateAlarmJson("slv", startTimeStr.c_str(), timeDuration.total_milliseconds()).GetData());
  1052. }
  1053. m_firstStartMain.unlock();
  1054. };
  1055. void CChromiumEntity::DoBrowserCacheClearJob()
  1056. {
  1057. #if (defined _WIN32 || defined _WIN64)
  1058. #else
  1059. LOG_FUNCTION();
  1060. CSmartPointer<IConfigInfo> spConfig;
  1061. ErrorCodeEnum err = GetFunction()->OpenConfig(Config_Cache, spConfig);
  1062. CSimpleStringA str(true);
  1063. err = spConfig->ReadConfigValue("Browser", "CacheClear", str);
  1064. if (str.Compare("true", true) == 0) {
  1065. BOOL bSucc(FALSE);
  1066. CSimpleStringA strCachePath;
  1067. GetFunction()->GetPath("Temp", strCachePath);
  1068. if (!strCachePath.IsNullOrEmpty()) {
  1069. bSucc = TRUE;
  1070. const char* cacheDirs[] = { "cefCache", "cefCache_Ad", "cefCache_breakdown","cefCache_ErrNotify", "cefCache_main"
  1071. , "UOSBrowser_Ad", "UOSBrowser_main"
  1072. , "UOSBrowserConfig_Ad", "UOSBrowserConfig_main"
  1073. , "UOSBrowser2_Ad", "UOSBrowser2_main"
  1074. , "UOSBrowserConfig2_Ad", "UOSBrowserConfig2_main" };
  1075. const int cacheDirsLength = (5 + 4 + 4);
  1076. for (int i = 0; i < cacheDirsLength; ++i) {
  1077. CSimpleStringA strcefCachePath(strCachePath);
  1078. strcefCachePath += SPLIT_SLASH_STR;
  1079. strcefCachePath += cacheDirs[i];
  1080. if (ExistsDirA(strcefCachePath)) {
  1081. RemoveDirRecursiveA(strcefCachePath);
  1082. LogWarn(Severity_Low, Error_Debug, LOG_EVT_CHROMIUM_BROWSER_CACHE_CLEAER,
  1083. CSimpleStringA::Format("clear chromium browser cache: %s", strcefCachePath.GetData()));
  1084. }
  1085. }
  1086. }
  1087. if (bSucc) {
  1088. spConfig->WriteConfigValue("Browser", "CacheClear", NULL);
  1089. }
  1090. }
  1091. #endif
  1092. }
  1093. void CChromiumEntity::OnTaskTimerListener(void* pData)
  1094. {
  1095. static int max_restartTime = 3;
  1096. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnTaskTimerListener");
  1097. if (max_restartTime == 0)
  1098. {
  1099. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("max_restartTime == 0, do not restart chromium");
  1100. GetFunction()->KillTimer(CHROMIUM_TIMER_ID);
  1101. return;
  1102. }
  1103. static bool t_firstStartMain = true;
  1104. if (t_firstStartMain)
  1105. {
  1106. t_firstStartMain = false;
  1107. m_firstStartMain.lock();
  1108. boost::thread(boost::bind(&CChromiumEntity::checkUrlStartTime, this)).detach();
  1109. }
  1110. auto rc = CModTools::get_mutable_instance().StartChromiumBrowser();
  1111. max_restartTime--;
  1112. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TaskTimerListen, startChromiumBrowser, rc:%d, pid:%d", rc.first, rc.second);
  1113. if (0 == rc.first)
  1114. GetFunction()->KillTimer(CHROMIUM_TIMER_ID);
  1115. #if (defined _WIN32 || defined _WIN64)
  1116. if (rc.first == Error_Succeed && rc.second != 0)
  1117. {
  1118. HANDLE defaultProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, rc.second);
  1119. if (defaultProcess == nullptr)
  1120. {
  1121. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnTaskTimerListener, openProcess failed");
  1122. return;
  1123. }
  1124. auto ret = assigntoJob(defaultProcess, rc.second);
  1125. if (!ret.first)
  1126. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnTaskTimerListener, assigntoJob failed");
  1127. else
  1128. {
  1129. auto monitorThread = [&](HANDLE job, HANDLE process) {
  1130. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create thread:%s", __FUNCTION__);
  1131. while (1)
  1132. {
  1133. if (WaitForSingleObject(process, 10) != WAIT_OBJECT_0) //process end
  1134. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("default cefclient.exe job:%d, process:%d checkOpen", job, process);
  1135. else
  1136. {
  1137. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("default cefclient.exe job:%d, process:%d check Closed, try to restart", job, process);
  1138. TerminateJobObject(job, 0);
  1139. max_restartTime--;
  1140. generateCefclientTimer();
  1141. break;
  1142. }
  1143. boost::this_thread::sleep_for(boost::chrono::seconds(10));
  1144. }
  1145. };
  1146. if (ret.second != nullptr && defaultProcess != nullptr)
  1147. boost::thread(monitorThread, ret.second, defaultProcess).detach();
  1148. }
  1149. }
  1150. if (Error_Succeed != rc.first)
  1151. {
  1152. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnTaskTimerListener will be called after %d secs, rest restart time %d", 15, max_restartTime);
  1153. if (max_restartTime)
  1154. GetFunction()->ResetTimer(CHROMIUM_TIMER_ID, 15000);
  1155. }
  1156. else {
  1157. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("OnTaskTimerListener rc = succeed");
  1158. GetFunction()->KillTimer(CHROMIUM_TIMER_ID);
  1159. }
  1160. #endif
  1161. }
  1162. SP_BEGIN_ENTITY_MAP()
  1163. SP_ENTITY(CChromiumEntity)
  1164. SP_END_ENTITY_MAP()
  1165. }