guardian.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. // guardian.cpp : Defines the entry point for the console application.
  2. //
  3. #include "StdAfx.h"
  4. #ifdef linux
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <sys/socket.h>
  8. #include <sys/epoll.h>
  9. #include <netinet/in.h>
  10. #include <arpa/inet.h>
  11. #include <assert.h>
  12. #include <dirent.h>
  13. #include <fcntl.h>
  14. #include <unistd.h>
  15. #include <stdio.h>
  16. #include <errno.h>
  17. #include <string.h>
  18. #include <syslog.h>
  19. #include <signal.h>
  20. #include <pthread.h>
  21. #include <pwd.h>
  22. #include <signal.h>
  23. #include <sys/types.h>
  24. #include <sys/wait.h>
  25. #include "toolkit.h"
  26. #include "osutil.h"
  27. #include "memutil.h"
  28. #include <winpr/library.h>
  29. #include <winpr/synch.h>
  30. #include <winpr/environment.h>
  31. int epfd;
  32. struct epoll_event ev;
  33. #define MAXLINE 128
  34. #define OPEN_MAX 100
  35. #define LISTENQ 20
  36. #define INFTIM 1000
  37. #else
  38. #undef UNICODE
  39. #pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
  40. #define WIN32_LEAN_AND_MEAN
  41. #include <windows.h>
  42. #include <winsock2.h>
  43. #include <ws2tcpip.h>
  44. #include <TlHelp32.h>
  45. #include <direct.h>
  46. #include <ctime>
  47. #endif //linux
  48. #include <iostream>
  49. #include <fstream>
  50. #include <string>
  51. #include <vector>
  52. #include "GuardianBase.h"
  53. #include "guardian.h"
  54. #ifndef MAX_PATH
  55. #define MAX_PATH 260
  56. #endif
  57. #define GUARDIAN_VERSION_STR "0.0.1"
  58. #ifdef RVC_OS_WIN
  59. static char spshell_execute_name[] = "SpShell.exe";
  60. static char sphost_execute_name[] = "SpHost.exe";
  61. static char guardian_execute_name[] = "Guardian.exe";
  62. static char cefclient_execute_name[] = "cefclient.exe";
  63. #else
  64. static char spshell_execute_name[] = "spshell";
  65. static char sphost_execute_name[] = "sphost";
  66. static char guardian_execute_name[] = "guardian";
  67. static char cefclient_execute_name[] = "cefclient";
  68. #endif //_WIN32
  69. char* relate_processes[] = { spshell_execute_name };
  70. char* relate_processes_ex[] = { spshell_execute_name, sphost_execute_name, cefclient_execute_name };
  71. using namespace std;
  72. #define NET_TYPE_WIRELESS 1
  73. #define NET_TYPE_ETHERNET 2
  74. #define NET_TYPE_3G 3
  75. #define NET_TYPE_4G 4
  76. #define NET_TYPE_BLUETOOTH 5
  77. #define DLL_PATH "C:\\RVC\\SystemInit\\CmbPadDll.dll"
  78. typedef DWORD(*pWlanConnect)(BOOL bConnect, int nType);
  79. typedef DWORD (*pDisableBluetooth)(BOOL bDisable);
  80. #ifdef linux
  81. int g_sListen;
  82. pthread_mutex_t g_cs, g_cs_event, g_cs_log;
  83. #define EnterCriticalSectionRVC(xType) pthread_mutex_lock(&xType)
  84. #define LeaveCriticalSectionRVC(xType) pthread_mutex_unlock(&xType)
  85. static int GetProcID()
  86. {
  87. return getpid();
  88. }
  89. #else
  90. SOCKET g_sListen = INVALID_SOCKET;
  91. #pragma comment (lib, "Ws2_32.lib")
  92. unsigned int __stdcall DoNetControl(void* pData);
  93. CRITICAL_SECTION g_cs, g_cs_event, g_cs_log;
  94. #define EnterCriticalSectionRVC(xType) EnterCriticalSection(&xType)
  95. #define LeaveCriticalSectionRVC(xType) LeaveCriticalSection(&xType)
  96. static int GetProcID()
  97. {
  98. return GetCurrentProcessId();
  99. }
  100. #endif //linux
  101. //unsigned int __stdcall DoLog(void *pData);
  102. const int DEFAULT_BUFLEN = 512;
  103. const int SHAKEHAND_BUFZIE = 32;
  104. #define DEFAULT_PORT "30005"
  105. const int default_port = 30005;
  106. int g_needToRollBack = 0;
  107. bool g_needUpgradeGuardianOnly = false;
  108. bool g_bFrameQuit = false,g_bFrameOnline = false,g_bLogFileOpen = false,g_bAuthSuc = false,g_bInUpgrade = false;
  109. ULONGLONG g_dwTimeBegin = 0;
  110. ULONGLONG g_dwUpgradeRestartTimeBegin = 0;
  111. int cnt = 0;
  112. ofstream logFile;
  113. char currDirBuf[256];
  114. char chDisk[2];
  115. void NetControl();
  116. const int MAX_WAIT_TIME_TO_RESTART = 600000;
  117. //oilyang@20211208 change value from 110000 to 180000
  118. const int MAX_WAIT_TIME_TO_RESTART_UPGRADE = 180000;
  119. int g_startDay = 0;
  120. //HANDLE g_logHandle;
  121. char g_allMsg[1024];
  122. static int g_SpShellPID = 0;
  123. #ifdef linux
  124. extern "C"
  125. {
  126. void* DoWorkLinux(void* arg);
  127. void* DoNetControlLinux(void* arg);
  128. }
  129. #define FUNCTION_STDCALL
  130. typedef unsigned short WORD;
  131. typedef struct _SYSTEMTIME {
  132. WORD wYear;
  133. WORD wMonth;
  134. WORD wDayOfWeek;
  135. WORD wDay;
  136. WORD wHour;
  137. WORD wMinute;
  138. WORD wSecond;
  139. WORD wMilliseconds;
  140. } SYSTEMTIME;
  141. #else
  142. typedef struct
  143. {
  144. OVERLAPPED Overlapped;
  145. WSABUF DataBuf;
  146. CHAR Buffer[DATA_BUFSIZE];
  147. } PER_IO_OPERATION_DATA, * LPPER_IO_OPERATION_DATA;
  148. typedef struct
  149. {
  150. SOCKET Socket;
  151. } PER_HANDLE_DATA, * LPPER_HANDLE_DATA;
  152. unsigned int __stdcall DoWork(void* pData);
  153. #define FUNCTION_STDCALL __stdcall
  154. #endif
  155. unsigned long long GetTickCountRVC() {
  156. #ifdef linux
  157. struct timespec ts;
  158. clock_gettime(CLOCK_MONOTONIC, &ts);
  159. return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
  160. #else
  161. return GetTickCount64();
  162. #endif //RVC_OS_WIN
  163. }
  164. void GetLocalTimeRVC(SYSTEMTIME& stTime)
  165. {
  166. #ifdef linux
  167. time_t ct = 0;
  168. struct tm* ltm = NULL;
  169. WORD wMilliseconds = 0;
  170. DWORD ticks = 0;
  171. struct timespec ts;
  172. ct = time(NULL);
  173. ltm = localtime(&ct);
  174. if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts)) {
  175. ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
  176. wMilliseconds = (WORD)(ticks % 1000);
  177. }
  178. memset(&stTime, 0, sizeof(SYSTEMTIME));
  179. if (ltm) {
  180. stTime.wYear = (WORD)(ltm->tm_year + 1900);
  181. stTime.wMonth = (WORD)(ltm->tm_mon + 1);
  182. stTime.wDayOfWeek = (WORD)ltm->tm_wday;
  183. stTime.wDay = (WORD)ltm->tm_mday;
  184. stTime.wHour = (WORD)ltm->tm_hour;
  185. stTime.wMinute = (WORD)ltm->tm_min;
  186. stTime.wSecond = (WORD)ltm->tm_sec;
  187. stTime.wMilliseconds = wMilliseconds;
  188. }
  189. #else
  190. GetLocalTime(&stTime);
  191. #endif
  192. }
  193. int BeginThreadRVC(void* (*pFuncLinux)(void*), unsigned int(FUNCTION_STDCALL* pFuncWin)(void*))
  194. {
  195. #ifdef linux
  196. pthread_t tidp;
  197. if ((pthread_create(&tidp, NULL, pFuncLinux, NULL) == -1))
  198. {
  199. //printf("create error!\n");
  200. return 1;
  201. }
  202. cout << "after pthread_create of linux thread" << endl;
  203. return 0;
  204. #else
  205. _beginthreadex(NULL, 0, pFuncWin, NULL, 0, NULL);
  206. return 0;
  207. #endif //linux
  208. }
  209. void EndThreadRVC()
  210. {
  211. #ifdef linux
  212. cout << "thread to exit" << endl;
  213. pthread_exit(0);
  214. cout << "return of EndThreadRVC" << endl;
  215. #else
  216. _endthreadex(0);
  217. #endif //linux
  218. }
  219. void StartDoNetControlRVC()
  220. {
  221. #ifdef linux
  222. BeginThreadRVC(DoNetControlLinux, NULL);
  223. cout << "after DoNetControlLinux thread created." << endl;
  224. #else
  225. BeginThreadRVC(NULL, DoNetControl);
  226. #endif //linux
  227. }
  228. void StartDoWorkRVC()
  229. {
  230. #ifdef linux
  231. BeginThreadRVC(DoWorkLinux, NULL);
  232. #else
  233. BeginThreadRVC(NULL, DoWork);
  234. #endif //linux
  235. }
  236. void ServerReportEvent(const char* szFunction,const char* szName="guardian")
  237. {
  238. #ifdef linux
  239. return;//oiltest
  240. cout << "oiltest(SPE):" << szFunction << endl;
  241. openlog("guardian", LOG_CONS | LOG_PID, LOG_LOCAL0);
  242. syslog(LOG_ERR, szFunction);
  243. closelog();
  244. #else
  245. //LogToFile(false,false,false,szFunction);
  246. HANDLE hEventSource;
  247. LPCTSTR lpszStrings[2];
  248. int len = sizeof(szFunction);
  249. char Buffer[1024] = {0};
  250. hEventSource = RegisterEventSource(NULL, szName);
  251. if( NULL != hEventSource )
  252. {
  253. strcpy_s(Buffer,1024,szFunction);
  254. lpszStrings[0] = szName;
  255. lpszStrings[1] = Buffer;
  256. ReportEvent(hEventSource, // event log handle
  257. EVENTLOG_ERROR_TYPE, // event type
  258. 0, // event category
  259. 0xe0000001, // event identifier
  260. NULL, // no security identifier
  261. 2, // size of lpszStrings array
  262. 0, // no binary data
  263. lpszStrings, // array of strings
  264. NULL); // no binary data
  265. DeregisterEventSource(hEventSource);
  266. }
  267. #endif //linux
  268. }
  269. bool VersionRollback()
  270. {
  271. const int VersionLenMax = 64;
  272. fstream verFile,verBak;//to confirm
  273. string strActiveTxtPath, strVersionDatPath;
  274. #ifdef linux
  275. char tmp[MAX_PATH];
  276. char* pos = NULL;
  277. GetModuleFileNameA(NULL, tmp, MAX_PATH);
  278. LogSingleMsg(tmp);
  279. if ((pos = strstr(tmp, "/Run/")) != NULL) {
  280. pos[strlen("/Run/")] = '\0';
  281. strActiveTxtPath = string(tmp) + "version/active.txt";
  282. strVersionDatPath = string(tmp) + "runinfo/runcfg/version.dat";
  283. }
  284. else {
  285. strActiveTxtPath = "/opt/Run/version/active.txt";
  286. strVersionDatPath = "/opt/Run/runinfo/runcfg/version.dat";
  287. }
  288. #else
  289. string strDisk(chDisk);
  290. strActiveTxtPath = strDisk + ":\\Run\\version\\active.txt";
  291. strVersionDatPath = strDisk + ":\\Run\\runinfo\\runcfg\\version.dat";
  292. #endif //linux
  293. verFile.open(strActiveTxtPath,std::fstream::in|std::fstream::out|std::fstream::binary);
  294. verBak.open(strVersionDatPath,std::fstream::in|std::fstream::out|std::fstream::binary);
  295. if (!verFile.is_open() || !verBak.is_open())
  296. return false;
  297. char *pVerBak,*pNULL,*pCurrVer;
  298. pVerBak = new char[VersionLenMax];
  299. pNULL = new char[VersionLenMax];
  300. pCurrVer = new char[VersionLenMax];
  301. memset(pVerBak,0,VersionLenMax);
  302. memset(pNULL,0,VersionLenMax);
  303. memset(pCurrVer,0,VersionLenMax);
  304. verBak.seekg(0,verBak.end);
  305. int lenBak = verBak.tellg();
  306. verBak.seekg(0,verBak.beg);
  307. verBak.read(pVerBak,lenBak);
  308. //need to consider atomic op? oilyang
  309. verFile.seekg(0,verFile.end);
  310. int len = verFile.tellg();
  311. verFile.seekg(0,verFile.beg);
  312. verFile.read(pCurrVer,len);
  313. LogSingleMsg(pVerBak);
  314. LogSingleMsg(pCurrVer);
  315. LogSingleMsg(pNULL);
  316. if (strcmp(pVerBak,pCurrVer) == 0)
  317. {
  318. ServerReportEvent(pVerBak);
  319. verFile.close();
  320. verBak.close();
  321. delete []pVerBak;
  322. delete []pNULL;
  323. return false;
  324. }
  325. //verBak.write(pNULL,len);
  326. //verFile.write(pNULL,len);
  327. //how foolish?
  328. verFile.close();
  329. verFile.open(strActiveTxtPath,std::fstream::in|std::fstream::out|std::fstream::binary|std::fstream::trunc);
  330. verFile.seekg(0,verFile.beg);
  331. verFile.write(pVerBak,lenBak);
  332. LogSingleMsg("version will rollback to ");
  333. LogSingleMsg(pVerBak);
  334. verFile.close();
  335. verBak.close();
  336. delete []pVerBak;
  337. delete []pNULL;
  338. return true;
  339. }
  340. #ifndef _WIN32
  341. static int GetSpshellProcID()
  342. {
  343. int result(0);
  344. char* spshell[] = { spshell_execute_name };
  345. alive_process_info processes[1];
  346. memset(processes, 0, sizeof(processes));
  347. int count = 1;
  348. if (!osutil_detect_unique_app(spshell, array_size(spshell), &count, processes)) {
  349. result = processes[0].pid;
  350. }
  351. return result;
  352. }
  353. static void ComfirmSpShellDead()
  354. {
  355. char* spshell[] = { spshell_execute_name };
  356. alive_process_info processes[1];
  357. memset(processes, 0, sizeof(processes));
  358. int count = 1;
  359. if (!osutil_detect_unique_app(spshell, array_size(spshell), &count, processes)) {
  360. if(g_SpShellPID == 0) g_SpShellPID = processes[0].pid;
  361. LogSingleMsg("has spshell process alive! and to kill it", 0);
  362. assert(count > 0);
  363. if (kill(processes[0].pid, SIGTERM) != 0) {
  364. LogToFile(false, true, true, "kill with term for spshell failed", NULL, processes[0].pid, errno, 0);
  365. if (errno != 3 /**not exist */) {
  366. LogSingleMsg("to kill stronglely!");
  367. kill(processes[0].pid, SIGKILL);
  368. }
  369. } else {
  370. LogToFile(false, true, false, "kill with term for spshell succ.", NULL, processes[0].pid);
  371. }
  372. const int waitTimes = 100;
  373. const int eachTime = 300;
  374. int curTimes = 0;
  375. while (g_SpShellPID != 0 && curTimes < waitTimes) {
  376. if (osutil_detect_unique_app(spshell, array_size(spshell), NULL, NULL)) {
  377. g_SpShellPID = 0;
  378. break;
  379. }
  380. Sleep(eachTime);
  381. curTimes++;
  382. }
  383. if (g_SpShellPID == 0) {
  384. LogSingleMsg("spshell has gone!");
  385. }
  386. } else {
  387. LogSingleMsg("There are no any spshell process existed!", 0);
  388. }
  389. //////////////////////////////////////////////////////////////////////////
  390. count = MAX_ALIVE_PROCESS_COUNT;
  391. alive_process_info processes2[MAX_ALIVE_PROCESS_COUNT];
  392. memset(processes2, 0, sizeof(processes2));
  393. if (!osutil_detect_unique_app(relate_processes_ex, array_size(relate_processes_ex), &count, processes2)) {
  394. for (int i = 0; i < count; ++i) {
  395. LogToFile(true, true, false, processes2[i].name, processes2[i].path, processes2[i].pid);
  396. }
  397. osutil_terminate_related_process(relate_processes_ex, array_size(relate_processes_ex));
  398. Sleep(1000);
  399. }
  400. }
  401. inline static std::vector<std::string> Split(std::string str, char splitElem)
  402. {
  403. std::vector<std::string> strs;
  404. std::string::size_type pos1, pos2;
  405. pos2 = str.find(splitElem);
  406. pos1 = 0;
  407. while (std::string::npos != pos2) {
  408. strs.push_back(str.substr(pos1, pos2 - pos1));
  409. pos1 = pos2 + 1;
  410. pos2 = str.find(splitElem, pos1);
  411. }
  412. strs.push_back(str.substr(pos1));
  413. return strs;
  414. }
  415. static bool IsSpPathType(const std::string& value)
  416. {
  417. #if defined(RVC_OS_WIN)
  418. const int leastLength = strlen("C:\\version\\1.0.0.0\\");
  419. #else
  420. const int leastLength = strlen("Run/version/1.0.0.0/");
  421. #endif //RVC_OS_WIN
  422. std::string path(value.c_str());
  423. if (path.empty() || path.size() < leastLength) return false;
  424. const std::size_t sionPos = path.find("version");
  425. const std::size_t verPos = sionPos + strlen("version\\");
  426. if (sionPos == std::string::npos) return false;
  427. std::size_t suffixPos = std::string::npos, i;
  428. std::size_t dotCnt = 0;
  429. bool lastIsNum = false;
  430. for (i = verPos; i < path.size() && (path[i] >= '0' && path[i] <= '9' || path[i] == '.'); ++i) {
  431. lastIsNum = !(path[i] == '.');
  432. if (!lastIsNum) dotCnt++;
  433. }
  434. if (i >= path.size() || dotCnt != 3 || !lastIsNum)
  435. return false;
  436. return true;
  437. }
  438. /** 移除跟版本目录相关的环境变量信息*/
  439. static std::string CutSpPathFromPathValue(const char* value)
  440. {
  441. std::string path(value);
  442. std::string result("");
  443. std::vector<std::string> values = Split(path, ':');
  444. if (values.size() <= 0) {
  445. return path;
  446. }
  447. for (auto i = values.cbegin(); i != values.cend(); i++) {
  448. if (!IsSpPathType(*i)) {
  449. if (!result.empty()) result += ":";
  450. result += (*i);
  451. }
  452. }
  453. if (!result.empty() && path[path.size() - 1] == ':') {
  454. result += ":";
  455. }
  456. return result;
  457. }
  458. static void ResetEnviromentVars(const char* env)
  459. {
  460. DWORD size;
  461. char* buf;
  462. int len = 0;
  463. size = GetEnvironmentVariableA(env, NULL, 0);
  464. if (size == 0) {
  465. return;
  466. }
  467. len = size + MAX_PATH * 3;
  468. buf = (char*)malloc(len);
  469. memset(buf, 0, sizeof(buf));
  470. size = GetEnvironmentVariableA(env, buf, len);
  471. std::string newValue = CutSpPathFromPathValue(buf);
  472. if (newValue.empty()) {
  473. SetEnvironmentVariableA(env, NULL);
  474. } else if (newValue.size() < size) {
  475. strcpy(buf, newValue.c_str());
  476. SetEnvironmentVariableA(env, buf);
  477. }
  478. #if 1
  479. memset(buf, 0, sizeof(buf));
  480. size = GetEnvironmentVariableA(env, buf, len);
  481. LogToFile(true, true, false, buf, env, size);
  482. #endif
  483. FREE(buf);
  484. }
  485. static void ResetRelateEnviromentVars( const char* prefix)
  486. {
  487. LogSingleMsg(prefix);
  488. ResetEnviromentVars("LD_LIBRARY_PATH");
  489. ResetEnviromentVars("PATH");
  490. }
  491. #endif //NOT _WIN32
  492. int FrameworkShutdown(bool bUpgrade=false,bool bRestart = true)
  493. {
  494. cout << "in FrameworkShutdown,bUpgrade:" << bUpgrade << ",bRestart:" << bRestart << endl;
  495. if (!bUpgrade)
  496. g_dwTimeBegin = GetTickCountRVC();
  497. NetControl();
  498. #ifdef linux
  499. //todo oiltestlinux
  500. LogSingleMsg("to kill spshell", 0);
  501. ServerReportEvent("FrameworkShutdown linux");
  502. ComfirmSpShellDead();
  503. char tmp[MAX_PATH];
  504. char* pos = NULL;
  505. GetModuleFileNameA(NULL, tmp, MAX_PATH);
  506. LogSingleMsg(tmp);
  507. if ((pos = strstr(tmp, "/version")) != NULL) {
  508. pos[strlen("/version")+1] = '\0';
  509. ResetRelateEnviromentVars(tmp);
  510. char path[MAX_PATH] = { '\0' };
  511. bool toResetCWD(false);
  512. LogSingleMsg("to get current directory...");
  513. GetCurrentDirectoryA(MAX_PATH, path);
  514. LogSingleMsg(path);
  515. if (strlen(path) <= 0 || strcmp(path, tmp) != 0) {
  516. LogSingleMsg("to set current directory...");
  517. SetCurrentDirectoryA(tmp);
  518. toResetCWD = true;
  519. }
  520. strcat(tmp, "spexplorer.sh --restart");
  521. LogSingleMsg(tmp);
  522. tk_process_t* process = NULL;
  523. tk_process_option_t option;
  524. option.exit_cb = NULL;
  525. option.file = NULL;
  526. option.flags = 0;
  527. option.params = tmp;
  528. if (0 == process_spawn(&option, &process)) {
  529. FREE(process);
  530. LogSingleMsg("run spexplorer.sh scripts succ.");
  531. Sleep(1000);
  532. g_SpShellPID = GetSpshellProcID();
  533. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  534. if (toResetCWD) {
  535. SetCurrentDirectoryA(path);
  536. }
  537. return 0;
  538. } else {
  539. FREE(process);
  540. LogSingleMsg("run spexplorer.sh scripts failed!");
  541. if (toResetCWD) {
  542. SetCurrentDirectoryA(path);
  543. }
  544. return -1;
  545. }
  546. }
  547. LogSingleMsg("get regular version path failed!");
  548. return 0;
  549. #else
  550. STARTUPINFO si;
  551. PROCESS_INFORMATION pi;
  552. ZeroMemory( &si, sizeof(si) );
  553. si.cb = sizeof(si);
  554. ZeroMemory( &pi, sizeof(pi) );
  555. // Start the child process.
  556. CSimpleStringA csRestart,csVerPath,csAll,csSep("\""),csBlank(" "),csScript("wscript.exe"),csReFlag("r");
  557. csRestart = "sprestart.exe ";
  558. csVerPath = chDisk;
  559. csVerPath += ":\\Run\\version";
  560. //csVerPath +="\\spexplorerfast.vbs";
  561. csVerPath +="\\VTM.exe";
  562. if (!bRestart)
  563. csReFlag = "n";
  564. //csAll = csSep + csRestart + csSep + csBlank + csSep + csScript+csBlank + csVerPath + csSep
  565. // + csBlank + csSep + csReFlag + csSep;
  566. csAll = csSep + csRestart + csSep + csBlank + csSep + csVerPath + csSep
  567. + csBlank + csSep + csReFlag + csSep;
  568. LPTSTR szCmdline = _strdup(csAll);
  569. LogSingleMsg(szCmdline);
  570. //MessageBoxA(0,0,0,0);
  571. if( !CreateProcess( NULL,szCmdline,NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi))
  572. {
  573. //Dbg("CreateProcess failed (%d).\n", GetLastError());
  574. return -1;
  575. }
  576. DWORD dwErr = GetLastError();
  577. // Wait until child process exits.
  578. WaitForSingleObject( pi.hProcess, INFINITE );
  579. // Close process and thread handles.
  580. CloseHandle( pi.hProcess );
  581. CloseHandle( pi.hThread );
  582. return 0;
  583. #endif //linux
  584. }
  585. bool FrameworkRollBack()
  586. {
  587. bool bVerRollback = VersionRollback();
  588. LogToFile(false,false,false,"version rollback ");
  589. if (true)
  590. FrameworkShutdown();
  591. return true;
  592. }
  593. bool ReadRuninfoContent(string &strData)
  594. {
  595. fstream runinfo;
  596. string strGdRuninfoPath;
  597. #ifdef linux
  598. //todo oiltestlinux
  599. char tmp[MAX_PATH];
  600. char* pos = NULL;
  601. GetModuleFileNameA(NULL, tmp, MAX_PATH);
  602. if ((pos = strstr(tmp, "/Run/")) != NULL) {
  603. pos[strlen("/Run/")] = '\0';
  604. strGdRuninfoPath = string(tmp) + "runinfo/runcfg/gdruninfo";
  605. }
  606. else {
  607. strGdRuninfoPath = "/opt/Run/runinfo/runcfg/gdruninfo";
  608. }
  609. #else
  610. string strDisk(chDisk);
  611. strGdRuninfoPath = strDisk + ":\\Run\\runinfo\\runcfg\\gdruninfo";
  612. #endif //linux
  613. LogSingleMsg(strGdRuninfoPath.c_str());
  614. runinfo.open(strGdRuninfoPath,std::fstream::in|std::fstream::out|std::fstream::binary);
  615. if (!runinfo.is_open())
  616. {
  617. LogToFile(false, false,false, "open gdruninfo(read) failed.");
  618. return false;
  619. }
  620. runinfo.seekg(0,ios::end);
  621. int size = runinfo.tellg();
  622. if (size <= 0)
  623. return false;
  624. char *pData = new char[size+1];
  625. memset(pData,0,size+1);
  626. runinfo.seekg(0,ios::beg);
  627. runinfo.read(pData,size);
  628. strData = string(pData);
  629. LogToFile(true, false,false, "read runinfo ", strData.c_str());
  630. return true;
  631. }
  632. bool WriteRunInfoContent(const char* pData)
  633. {
  634. ofstream runinfo;
  635. string strGdRuninfoPath;
  636. #ifdef linux
  637. //todo oiltestlinux
  638. char tmp[MAX_PATH];
  639. char* pos = NULL;
  640. GetModuleFileNameA(NULL, tmp, MAX_PATH);
  641. LogSingleMsg(tmp);
  642. if ((pos = strstr(tmp, "/Run/")) != NULL) {
  643. pos[strlen("/Run/")] = '\0';
  644. strGdRuninfoPath = string(tmp) + "runinfo/runcfg/gdruninfo";
  645. }
  646. else {
  647. strGdRuninfoPath = "/opt/Run/runinfo/runcfg/gdruninfo";
  648. }
  649. LogSingleMsg(strGdRuninfoPath.c_str());
  650. #else
  651. string strDisk(chDisk);
  652. strGdRuninfoPath = strDisk + ":\\Run\\runinfo\\runcfg\\gdruninfo";
  653. #endif //linux
  654. runinfo.open(strGdRuninfoPath,std::ofstream::in|std::ofstream::binary|std::ofstream::trunc);
  655. if (!runinfo.is_open())
  656. {
  657. LogSingleMsg("open gdruninfo(write) failed.");
  658. ServerReportEvent("open gdruninfo(write) failed.");
  659. return false;
  660. }
  661. runinfo.write(pData,strlen(pData));
  662. runinfo.close();
  663. std::string logcontent("write ");
  664. logcontent += strGdRuninfoPath;
  665. logcontent += " done";
  666. LogSingleMsg(logcontent.c_str());
  667. return true;
  668. }
  669. bool IsStartTimeFileExist()
  670. {
  671. ofstream runinfo;
  672. string strStartTimePath;
  673. #ifdef linux
  674. //todo oiltestlinux
  675. char tmp[MAX_PATH];
  676. char* pos = NULL;
  677. GetModuleFileNameA(NULL, tmp, MAX_PATH);
  678. LogSingleMsg(tmp);
  679. if ((pos = strstr(tmp, "/Run/")) != NULL) {
  680. pos[strlen("/Run/")] = '\0';
  681. strStartTimePath = string(tmp) + "runinfo/runcfg/starttime.dat";
  682. }
  683. else {
  684. strStartTimePath = "/opt/Run/runinfo/runcfg/starttime.dat";
  685. }
  686. #else
  687. string strDisk(chDisk);
  688. strStartTimePath = strDisk + ":\\Run\\runinfo\\runcfg\\starttime.dat";
  689. #endif //linux
  690. runinfo.open(strStartTimePath, std::fstream::in | std::fstream::out | std::fstream::binary);
  691. if (!runinfo.is_open()) {
  692. LogSingleMsg("open starttime.dat failed");
  693. return false;
  694. }
  695. else
  696. {
  697. runinfo.close();
  698. LogSingleMsg("open starttime.dat succ");
  699. return true;
  700. }
  701. }
  702. #ifdef linux
  703. void CheckDoWork(int sig)
  704. {
  705. cout << "CheckDoWork" << endl;
  706. if (SIGALRM == sig)
  707. {
  708. LogSingleMsg("to check value(linux)");
  709. EnterCriticalSectionRVC(g_cs);
  710. if (!g_bFrameQuit)
  711. {
  712. ULONGLONG dwTmpBegin = g_dwTimeBegin;
  713. ULONGLONG dwUpgradeTmpBegin = g_dwUpgradeRestartTimeBegin;
  714. LeaveCriticalSectionRVC(g_cs);
  715. ULONGLONG dwTimeEnd = GetTickCountRVC();
  716. //oilyang@20190828 add
  717. //升级重启后,在10分钟内,只要离最后一次交互时间大于2分钟,重启框架
  718. if ((g_bInUpgrade && ((dwTimeEnd - dwUpgradeTmpBegin) < MAX_WAIT_TIME_TO_RESTART))
  719. && (!g_bAuthSuc && ((dwTimeEnd - dwTmpBegin) > MAX_WAIT_TIME_TO_RESTART_UPGRADE)))
  720. {
  721. LogSingleMsg("**in upgrade restart**,to restart framework(linux).");
  722. FrameworkShutdown(true, true);
  723. }
  724. if ((dwTimeEnd - dwTmpBegin) > MAX_WAIT_TIME_TO_RESTART)
  725. {
  726. LogSingleMsg("framework maybe down.");
  727. string strRunInfo;
  728. if (ReadRuninfoContent(strRunInfo))
  729. {
  730. LogSingleMsg("to check if need rollback.");
  731. LogSingleMsg((char*)strRunInfo.c_str());
  732. if (strRunInfo.compare("111") == 0 && IsStartTimeFileExist())
  733. {
  734. EnterCriticalSectionRVC(g_cs);
  735. g_needToRollBack = 1;
  736. LeaveCriticalSectionRVC(g_cs);
  737. }
  738. }
  739. else
  740. LogSingleMsg("read run info failed.");
  741. if (g_needToRollBack)
  742. {
  743. LogSingleMsg("after upgrade,time elapse,but can't wait the shake hands,so rollback.");
  744. FrameworkRollBack();
  745. }
  746. else
  747. {
  748. //framework is down,to restart it! oilyang 20150413
  749. FrameworkShutdown();
  750. }
  751. }
  752. }
  753. else
  754. LeaveCriticalSectionRVC(g_cs);
  755. alarm(2 * 60); //we contimue set the timer
  756. }
  757. return;
  758. }
  759. void* DoWorkLinux(void* arg)
  760. {
  761. //LogSingleMsg("to wait.");
  762. cout << "DoWorkLinux" << endl;
  763. signal(SIGALRM, CheckDoWork); //relate the signal and function
  764. alarm(2 * 60); //trigger the timer
  765. EndThreadRVC();
  766. //return 0;
  767. }
  768. void* DoNetControlLinux(void* arg)
  769. {
  770. cout << "to end DoNetControlLinux" << endl;
  771. EndThreadRVC();
  772. cout << "after end DoNetControlLinux" << endl;
  773. }
  774. void DataProcessLinux(int socket,const char*data)
  775. {
  776. GuardianInfo* pInfo = (GuardianInfo*)data;
  777. LogToFile(false, true, false, "eType:", "", pInfo->eType);
  778. LogToFile(false, true, false, "dwParam1:", "", pInfo->dwParam1);
  779. cout << "eType:" << pInfo->eType << ",p1:" << pInfo->dwParam1 << ",p2:" << pInfo->dwParam2 << ",dwSize:" << pInfo->dwSize << endl;
  780. //LogToFile(false,true,false,"clientsocket:", "", pPerHandleData->Socket);
  781. switch (pInfo->eType)
  782. {
  783. case GdOpShakeHand:
  784. {
  785. LogToFile(false, false, false, "Shake hand.");
  786. if (!g_bFrameOnline)
  787. {
  788. g_bFrameOnline = true;
  789. g_SpShellPID = GetSpshellProcID();
  790. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  791. StartDoNetControlRVC();
  792. }
  793. int rc, err;
  794. EnterCriticalSectionRVC(g_cs);
  795. g_bFrameQuit = false;
  796. g_dwTimeBegin = GetTickCountRVC();
  797. LeaveCriticalSectionRVC(g_cs);
  798. char* pBuf = new char[8];
  799. memset(pBuf, 0, 8);
  800. //get guardian state
  801. //ex:u(update),g(guardian),r(reboot),b(rollback)
  802. if (cnt % 2 == 0)
  803. memcpy(pBuf, "g", 1);
  804. else
  805. memcpy(pBuf, "u", 1);
  806. cnt++;
  807. rc = send(socket, pBuf, 8, 0);
  808. delete[]pBuf;
  809. close(socket);
  810. }
  811. break;
  812. case GdOpUpdateTask:
  813. {
  814. if (!g_bFrameOnline)
  815. {
  816. g_bFrameOnline = true;
  817. g_SpShellPID = GetSpshellProcID();
  818. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  819. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  820. StartDoNetControlRVC();
  821. }
  822. }
  823. break;
  824. case GdOpQueryInstall:
  825. {
  826. if (!g_bFrameOnline)
  827. {
  828. g_bFrameOnline = true;
  829. g_SpShellPID = GetSpshellProcID();
  830. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  831. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  832. StartDoNetControlRVC();
  833. }
  834. int rc, err;
  835. char* pBuf = new char[8];
  836. memset(pBuf, 0, 8);
  837. if (cnt % 2 == 0)
  838. memcpy(pBuf, "y", 1);
  839. else
  840. memcpy(pBuf, "n", 1);
  841. cnt++;
  842. rc = send(socket, pBuf, 8, 0);
  843. delete[]pBuf;
  844. close(socket);
  845. }
  846. break;
  847. case GdOpUpgradeRestart:
  848. {
  849. if (pInfo->dwParam1 == 6)//HealthManager call guardian to quit
  850. {
  851. LogSingleMsg("HealthManager call guardian to quit");
  852. close(socket);
  853. close(g_sListen);
  854. exit(0);//baoli?
  855. break;
  856. }
  857. if (pInfo->dwParam1 == 4)//just know framework is starting...
  858. {
  859. LogSingleMsg("framework is starting...");
  860. cout << "framework is starting..." << endl;
  861. g_bFrameOnline = true;
  862. g_SpShellPID = GetSpshellProcID();
  863. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  864. g_bAuthSuc = false;
  865. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  866. StartDoNetControlRVC();
  867. cout << "to break upgrade..." << endl;
  868. close(socket);
  869. break;
  870. }
  871. if (pInfo->dwParam1 == 5)
  872. {
  873. LogSingleMsg("framework auth ok.");
  874. g_bInUpgrade = false;
  875. g_bAuthSuc = true;
  876. }
  877. if (!g_bFrameOnline)
  878. {
  879. g_bFrameOnline = true;
  880. g_SpShellPID = GetSpshellProcID();
  881. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  882. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  883. StartDoNetControlRVC();
  884. }
  885. if (pInfo->dwParam1 == 1 || pInfo->dwParam1 == 3)
  886. g_dwTimeBegin = GetTickCountRVC();
  887. ServerReportEvent("upgrade restart");
  888. LogToFile(false, true, false, "upgrade restart ", "", pInfo->dwParam1);
  889. if (pInfo->dwParam1 == 1)//framework to restart after upgrade
  890. {
  891. g_bInUpgrade = true;
  892. WriteRunInfoContent("111");
  893. g_dwUpgradeRestartTimeBegin = GetTickCountRVC();
  894. }
  895. else if (pInfo->dwParam1 == 2)//need rollback after upgrade
  896. {
  897. LogSingleMsg("upgrade restart 222");
  898. WriteRunInfoContent("222");
  899. //rollback
  900. EnterCriticalSectionRVC(g_cs);
  901. g_needToRollBack = 0;
  902. LeaveCriticalSectionRVC(g_cs);
  903. LogSingleMsg("healthmanager said to rollback");
  904. FrameworkRollBack();
  905. }
  906. else if (pInfo->dwParam1 == 3)//upgrade succeeded
  907. {
  908. LogSingleMsg("upgrade restart ok");
  909. WriteRunInfoContent("333");
  910. EnterCriticalSectionRVC(g_cs);
  911. g_needToRollBack = 0;
  912. LeaveCriticalSectionRVC(g_cs);
  913. }
  914. //runinfo.close();
  915. close(socket);
  916. }
  917. break;
  918. case GdOpFrameQuit:
  919. if (!g_bFrameOnline)
  920. {
  921. g_bFrameOnline = true;
  922. g_SpShellPID = GetSpshellProcID();
  923. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  924. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  925. StartDoNetControlRVC();
  926. }
  927. EnterCriticalSectionRVC(g_cs);
  928. g_bFrameQuit = true;
  929. LeaveCriticalSectionRVC(g_cs);
  930. close(socket);
  931. break;
  932. default:
  933. break;
  934. }
  935. LogSingleMsg("quit of DataProcessLinux");
  936. }
  937. #else
  938. void DataProcess(LPPER_HANDLE_DATA pPerHandleData,LPPER_IO_OPERATION_DATA pPerIoData)
  939. {
  940. GuardianInfo* pInfo = (GuardianInfo*)pPerIoData->Buffer;
  941. LogToFile(false, true, false,"eType:", "", pInfo->eType);
  942. //LogToFile(false,true,false,"clientsocket:", "", pPerHandleData->Socket);
  943. switch(pInfo->eType)
  944. {
  945. case GdOpShakeHand:
  946. {
  947. LogToFile(false, false,false, "Shake hand.");
  948. if (!g_bFrameOnline)
  949. {
  950. g_bFrameOnline = true;
  951. StartDoNetControlRVC();
  952. }
  953. int rc,err;
  954. EnterCriticalSectionRVC(g_cs);
  955. g_bFrameQuit = false;
  956. g_dwTimeBegin = GetTickCountRVC();
  957. LeaveCriticalSectionRVC(g_cs);
  958. char* pBuf = new char[8];
  959. memset(pBuf,0,8);
  960. //get guardian state
  961. //ex:u(update),g(guardian),r(reboot),b(rollback)
  962. if (cnt%2 == 0)
  963. memcpy(pBuf,"g",1);
  964. else
  965. memcpy(pBuf,"u",1);
  966. cnt++;
  967. rc = send(pPerHandleData->Socket,pBuf,8,0);
  968. delete []pBuf;
  969. closesocket(pPerHandleData->Socket);
  970. }
  971. break;
  972. case GdOpUpdateTask:
  973. {
  974. if (!g_bFrameOnline)
  975. {
  976. g_bFrameOnline = true;
  977. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  978. StartDoNetControlRVC();
  979. }
  980. }
  981. break;
  982. case GdOpQueryInstall:
  983. {
  984. if (!g_bFrameOnline)
  985. {
  986. g_bFrameOnline = true;
  987. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  988. StartDoNetControlRVC();
  989. }
  990. int rc,err;
  991. char* pBuf = new char[8];
  992. memset(pBuf,0,8);
  993. if (cnt%2 == 0)
  994. memcpy(pBuf,"y",1);
  995. else
  996. memcpy(pBuf,"n",1);
  997. cnt++;
  998. rc = send(pPerHandleData->Socket,pBuf,8,0);
  999. delete []pBuf;
  1000. closesocket(pPerHandleData->Socket);
  1001. }
  1002. break;
  1003. case GdOpUpgradeRestart:
  1004. {
  1005. if (pInfo->dwParam1 == 6)//need Upgrade guardian !!!Only!!!
  1006. {
  1007. g_needUpgradeGuardianOnly = true;
  1008. }
  1009. if (pInfo->dwParam1 == 4)//just know framework is starting...
  1010. {
  1011. LogSingleMsg("framework is starting...");
  1012. //oilyang@20211208 add the following if receive framework is starting ,reset g_dwUpgradeRestartTimeBegin
  1013. //in order to skip the cost time of "kill spshell"
  1014. g_dwUpgradeRestartTimeBegin = GetTickCountRVC();
  1015. g_bFrameOnline = true;
  1016. g_bAuthSuc = false;
  1017. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  1018. StartDoNetControlRVC();
  1019. break;
  1020. }
  1021. if (pInfo->dwParam1 == 5)
  1022. {
  1023. LogSingleMsg("framework auth ok.");
  1024. g_bInUpgrade = false;
  1025. g_bAuthSuc = true;
  1026. }
  1027. if (!g_bFrameOnline)
  1028. {
  1029. g_bFrameOnline = true;
  1030. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  1031. StartDoNetControlRVC();
  1032. }
  1033. if (pInfo->dwParam1 == 1 || pInfo->dwParam1 == 3)
  1034. g_dwTimeBegin = GetTickCountRVC();
  1035. ServerReportEvent("upgrade restart");
  1036. LogToFile(false, true,false, "upgrade restart ", "", pInfo->dwParam1);
  1037. if (pInfo->dwParam1 == 1)//framework to restart after upgrade
  1038. {
  1039. g_bInUpgrade = true;
  1040. WriteRunInfoContent("111");
  1041. g_dwUpgradeRestartTimeBegin = GetTickCountRVC();
  1042. }
  1043. else if (pInfo->dwParam1 == 2)//need rollback after upgrade
  1044. {
  1045. LogSingleMsg("upgrade restart 222");
  1046. WriteRunInfoContent("222");
  1047. //rollback
  1048. EnterCriticalSectionRVC(g_cs);
  1049. g_needToRollBack = 0;
  1050. LeaveCriticalSectionRVC(g_cs);
  1051. LogSingleMsg("healthmanager said to rollback");
  1052. FrameworkRollBack();
  1053. }else if (pInfo->dwParam1 == 3)//upgrade succeeded
  1054. {
  1055. LogSingleMsg("upgrade restart ok");
  1056. WriteRunInfoContent("333");
  1057. EnterCriticalSectionRVC(g_cs);
  1058. g_needToRollBack = 0;
  1059. LeaveCriticalSectionRVC(g_cs);
  1060. }
  1061. //runinfo.close();
  1062. closesocket(pPerHandleData->Socket);
  1063. }
  1064. break;
  1065. case GdOpFrameQuit:
  1066. if (!g_bFrameOnline)
  1067. {
  1068. g_bFrameOnline = true;
  1069. //_beginthreadex(NULL,0,DoNetControl,NULL,0,NULL);
  1070. StartDoNetControlRVC();
  1071. }
  1072. EnterCriticalSectionRVC(g_cs);
  1073. g_bFrameQuit = true;
  1074. LeaveCriticalSectionRVC(g_cs);
  1075. closesocket(pPerHandleData->Socket);
  1076. break;
  1077. default:
  1078. break;
  1079. }
  1080. }
  1081. DWORD WINAPI ProcessIO(LPVOID lpParam)
  1082. {
  1083. HANDLE CompletionPort = (HANDLE)lpParam;
  1084. DWORD BytesTransferred;
  1085. LPPER_HANDLE_DATA PerHandleData;
  1086. LPPER_IO_OPERATION_DATA PerIoData;
  1087. while(true)
  1088. {
  1089. if(0 == GetQueuedCompletionStatus(CompletionPort, &BytesTransferred, (LPDWORD)&PerHandleData, (LPOVERLAPPED*)&PerIoData, INFINITE))
  1090. {
  1091. if( (GetLastError() == WAIT_TIMEOUT) || (GetLastError() == ERROR_NETNAME_DELETED) )
  1092. {
  1093. LogToFile(false, true,false, "closing socket(1)", "", PerHandleData->Socket);
  1094. closesocket(PerHandleData->Socket);
  1095. delete PerIoData;
  1096. delete PerHandleData;
  1097. continue;
  1098. }
  1099. else
  1100. {
  1101. //OutErr("GetQueuedCompletionStatus failed!");
  1102. }
  1103. return 0;
  1104. }
  1105. // client quit
  1106. if(BytesTransferred == 0)
  1107. {
  1108. LogToFile(false, true,false, "closing socket(2)", "", PerHandleData->Socket);
  1109. closesocket(PerHandleData->Socket);
  1110. delete PerIoData;
  1111. delete PerHandleData;
  1112. continue;
  1113. }
  1114. //MessageBoxA(0,0,0,0);
  1115. //LogToFile(false, true,false, "socket", "", PerHandleData->Socket);
  1116. // receiving data process
  1117. DataProcess(PerHandleData,PerIoData);
  1118. // socket WSARecv
  1119. DWORD Flags = 0;
  1120. DWORD dwRecv = 0;
  1121. ZeroMemory(PerIoData, sizeof(PER_IO_OPERATION_DATA));
  1122. PerIoData->DataBuf.buf = PerIoData->Buffer;
  1123. PerIoData->DataBuf.len = DATA_BUFSIZE;
  1124. WSARecv(PerHandleData->Socket, &PerIoData->DataBuf, 1, &dwRecv, &Flags, &PerIoData->Overlapped, NULL);
  1125. }
  1126. return 0;
  1127. }
  1128. unsigned int __stdcall DoWork(void* pData)
  1129. {
  1130. LogSingleMsg("to wait.");
  1131. HANDLE hTimer;
  1132. LARGE_INTEGER li;
  1133. hTimer = CreateWaitableTimer(NULL,FALSE,NULL);
  1134. const int nTimerUnitsPerSecond = 10000000;
  1135. li.QuadPart = -(1*60*nTimerUnitsPerSecond);//oiltmp 1 minute
  1136. SetWaitableTimer(hTimer,&li,2*60*1000,NULL,NULL,FALSE);
  1137. while(1)
  1138. {
  1139. WaitForSingleObject(hTimer,INFINITE);
  1140. LogSingleMsg("to check value");
  1141. EnterCriticalSectionRVC(g_cs);
  1142. if (!g_bFrameQuit)
  1143. {
  1144. ULONGLONG dwTmpBegin = g_dwTimeBegin;
  1145. ULONGLONG dwUpgradeTmpBegin = g_dwUpgradeRestartTimeBegin;
  1146. LeaveCriticalSectionRVC(g_cs);
  1147. ULONGLONG dwTimeEnd = GetTickCountRVC();
  1148. //oilyang@20190828 add
  1149. //升级重启后,在10分钟内,只要离最后一次交互时间大于MAX_WAIT_TIME_TO_RESTART_UPGRADE,重启框架
  1150. if (g_bInUpgrade && ((dwTimeEnd - dwTmpBegin) < MAX_WAIT_TIME_TO_RESTART)
  1151. && (!g_bAuthSuc && ((dwTimeEnd - dwUpgradeTmpBegin) > MAX_WAIT_TIME_TO_RESTART_UPGRADE)))
  1152. {
  1153. LogSingleMsg("**in upgrade restart**,to restart framework.");
  1154. FrameworkShutdown(true,true);
  1155. }
  1156. if ((dwTimeEnd-dwTmpBegin) > MAX_WAIT_TIME_TO_RESTART)
  1157. {
  1158. LogSingleMsg("framework maybe down.");
  1159. string strRunInfo;
  1160. if (ReadRuninfoContent(strRunInfo))
  1161. {
  1162. LogSingleMsg("to check if need rollback.");
  1163. LogSingleMsg((char*)strRunInfo.c_str());
  1164. if (strRunInfo.compare("111") == 0 && IsStartTimeFileExist())
  1165. {
  1166. EnterCriticalSectionRVC(g_cs);
  1167. g_needToRollBack = 1;
  1168. LeaveCriticalSectionRVC(g_cs);
  1169. }
  1170. }
  1171. else
  1172. LogSingleMsg("read run info failed.");
  1173. if (g_needToRollBack)
  1174. {
  1175. LogSingleMsg("after upgrade,time elapse,but can't wait the shake hands,so rollback.");
  1176. FrameworkRollBack();
  1177. }
  1178. else
  1179. {
  1180. //framework is down,to restart it! oilyang 20150413
  1181. //oilyang@20211221 if Upgrade guardian !!!Only!!! ,just reset dwTmpBegin
  1182. if (!g_needUpgradeGuardianOnly)
  1183. FrameworkShutdown();
  1184. else
  1185. dwTmpBegin = GetTickCountRVC();
  1186. }
  1187. }
  1188. }
  1189. else
  1190. LeaveCriticalSectionRVC(g_cs);
  1191. }
  1192. //_endthreadex(0);
  1193. EndThreadRVC();
  1194. return 0;
  1195. }
  1196. unsigned int __stdcall DoNetControl(void *pData)
  1197. {
  1198. ServerReportEvent("DoNetControl start");
  1199. HANDLE hSnapshot;
  1200. //find spshell.exe
  1201. hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  1202. if (hSnapshot)
  1203. {
  1204. PROCESSENTRY32 pe;
  1205. pe.dwSize = sizeof(pe);
  1206. if (Process32First(hSnapshot, &pe))
  1207. {
  1208. do {
  1209. if (_stricmp(&pe.szExeFile[0], "spshell.exe") == 0)
  1210. {
  1211. //ServerReportEvent("find spshell.exe");
  1212. LogToFile(false, false, false, "find spshell.exe");
  1213. //DWORD dwExit = 0;
  1214. //do
  1215. //{
  1216. // GetExitCodeProcess(&pe.th32ProcessID,&dwExit);
  1217. // if (dwExit != STILL_ACTIVE)
  1218. // break;
  1219. //}while(1);
  1220. HANDLE hP = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID );
  1221. WaitForSingleObject(hP, INFINITE );
  1222. LogToFile(false, false, false, "spshell.exe quit");
  1223. //ServerReportEvent("spshell.exe quit");
  1224. NetControl();
  1225. break;
  1226. }
  1227. } while (Process32Next(hSnapshot, &pe));
  1228. }
  1229. CloseHandle(hSnapshot);
  1230. }
  1231. else
  1232. ServerReportEvent("create snapshot failed.");
  1233. //_endthreadex(0);
  1234. EndThreadRVC();
  1235. return 0;
  1236. }
  1237. #endif //linux
  1238. int InitListenSocketRVC()
  1239. {
  1240. #ifdef linux
  1241. socklen_t clilen;
  1242. epfd = epoll_create(256);
  1243. struct sockaddr_in clientaddr;
  1244. struct sockaddr_in serveraddr;
  1245. g_sListen = socket(AF_INET, SOCK_STREAM, 0);
  1246. //setnonblocking(listenfd);
  1247. ev.data.fd = g_sListen;
  1248. ev.events = EPOLLIN | EPOLLET;
  1249. epoll_ctl(epfd, EPOLL_CTL_ADD, g_sListen, &ev);
  1250. memset(&serveraddr, 0, sizeof(serveraddr));
  1251. serveraddr.sin_family = AF_INET;
  1252. char* local_addr = "127.0.0.1";
  1253. inet_aton(local_addr, &(serveraddr.sin_addr));
  1254. serveraddr.sin_port = htons(default_port);
  1255. int tmpuse = 1;
  1256. if (setsockopt(g_sListen, SOL_SOCKET, SO_REUSEPORT, (char*)&tmpuse, sizeof(tmpuse)) < 0)
  1257. {
  1258. LogSingleMsg("setsockopt failed.", errno);
  1259. LogSingleMsg(strerror(errno));
  1260. close(g_sListen);
  1261. return -1;
  1262. }
  1263. int ret = bind(g_sListen, (sockaddr*)& serveraddr, sizeof(serveraddr));
  1264. if (ret != 0)
  1265. {
  1266. LogSingleMsg("bind failed.", errno);
  1267. LogSingleMsg(strerror(errno));
  1268. close(g_sListen);
  1269. return -1;
  1270. }
  1271. ret= listen(g_sListen, LISTENQ);
  1272. if (ret != 0)
  1273. {
  1274. LogSingleMsg("listen failed.", errno);
  1275. LogSingleMsg(strerror(errno));
  1276. close(g_sListen);
  1277. return -1;
  1278. }
  1279. LogSingleMsg("(linux)listen ok.", g_sListen);
  1280. cout << "listen on:" << g_sListen << endl;
  1281. return g_sListen;
  1282. #else
  1283. WSADATA wsaData;
  1284. int iResult;
  1285. struct addrinfo* result = NULL;
  1286. struct addrinfo hints;
  1287. int iSendResult;
  1288. char recvbuf[DEFAULT_BUFLEN];
  1289. int recvbuflen = DEFAULT_BUFLEN;
  1290. // Initialize Winsock
  1291. iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  1292. if (iResult != 0) {
  1293. LogToFile(false, true, false, "WSAStartup failed with error:", "", iResult);
  1294. return 1;
  1295. }
  1296. ZeroMemory(&hints, sizeof(hints));
  1297. hints.ai_family = AF_INET;
  1298. hints.ai_socktype = SOCK_STREAM;
  1299. hints.ai_protocol = IPPROTO_TCP;
  1300. hints.ai_flags = AI_PASSIVE;
  1301. // Resolve the server address and port
  1302. iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
  1303. if (iResult != 0) {
  1304. LogToFile(false, true, false, "getaddrinfo failed with error:", "", iResult);
  1305. WSACleanup();
  1306. return 1;
  1307. }
  1308. // get system info to create work thread
  1309. SYSTEM_INFO SystemInfo;
  1310. GetSystemInfo(&SystemInfo);
  1311. // Create a SOCKET for connecting to server
  1312. g_sListen = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  1313. if (g_sListen == INVALID_SOCKET) {
  1314. LogToFile(false, true, false, "socket failed with error:", "", WSAGetLastError());
  1315. freeaddrinfo(result);
  1316. WSACleanup();
  1317. return 1;
  1318. }
  1319. // Setup the TCP listening socket
  1320. struct sockaddr_in* sockaddr_ipv4 = (struct sockaddr_in*) result->ai_addr;
  1321. LogToFile(true, false, false, "ip:", inet_ntoa(sockaddr_ipv4->sin_addr));
  1322. iResult = bind(g_sListen, result->ai_addr, (int)result->ai_addrlen);
  1323. if (iResult == SOCKET_ERROR) {
  1324. printf("bind failed with error: %d\n", WSAGetLastError());
  1325. freeaddrinfo(result);
  1326. closesocket(g_sListen);
  1327. WSACleanup();
  1328. return 1;
  1329. }
  1330. freeaddrinfo(result);
  1331. LogToFile(false, false, false, "to listen.");
  1332. iResult = listen(g_sListen, SOMAXCONN);
  1333. if (iResult == SOCKET_ERROR) {
  1334. printf("listen failed with error: %d\n", WSAGetLastError());
  1335. closesocket(g_sListen);
  1336. WSACleanup();
  1337. return 1;
  1338. }
  1339. LogToFile(false, false, false, "listen ok.");
  1340. return g_sListen;
  1341. #endif //linux
  1342. }
  1343. void AcceptReqRVC()
  1344. {
  1345. #ifdef linux
  1346. StartDoWorkRVC();
  1347. cout << "AcceptReqRVC:after StartDoWorkRVC" << endl;
  1348. int maxi, connfd, sockfd, nfds;
  1349. struct epoll_event events[20];
  1350. struct sockaddr_in clientaddr;
  1351. socklen_t clilen = sizeof(struct sockaddr);
  1352. ssize_t n;
  1353. maxi = 0;
  1354. char line[MAXLINE];
  1355. for (; ; ) {
  1356. //等待epoll事件的发生
  1357. nfds = epoll_wait(epfd, events, 20, 500);
  1358. //处理所发生的所有事件
  1359. for (int i = 0; i < nfds; ++i)
  1360. {
  1361. LogToFile(false, true, false, "nfds: ", "", nfds);
  1362. if (events[i].data.fd == g_sListen)//new connection
  1363. {
  1364. connfd = accept(g_sListen, (sockaddr*)& clientaddr, &clilen);
  1365. if (connfd < 0) {
  1366. LogSingleMsg("connfd<0");
  1367. perror("connfd<0");
  1368. exit(1);
  1369. }
  1370. //setnonblocking(connfd);
  1371. char* str = inet_ntoa(clientaddr.sin_addr);
  1372. cout << "accapt a connection from " << str << endl;
  1373. ev.data.fd = connfd;
  1374. ev.events = EPOLLIN | EPOLLET;
  1375. //ev.events=EPOLLIN;
  1376. epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev);
  1377. }
  1378. else if (events[i].events & EPOLLIN)
  1379. {
  1380. cout << "EPOLLIN,i:" << i << ",sock:" << events[i].data.fd << endl;
  1381. if ((sockfd = events[i].data.fd) < 0)
  1382. continue;
  1383. if ((n = read(sockfd, line, MAXLINE)) < 0) {
  1384. if (errno == ECONNRESET) {
  1385. close(sockfd);
  1386. events[i].data.fd = -1;
  1387. }
  1388. else
  1389. std::cout << "readline error" << strerror(errno) << std::endl;
  1390. }
  1391. else if (n == 0) {
  1392. close(sockfd);
  1393. events[i].data.fd = -1;
  1394. }
  1395. DataProcessLinux(sockfd,line);
  1396. line[n] = '\0';
  1397. ev.data.fd = sockfd;
  1398. ev.events = EPOLLOUT | EPOLLET;
  1399. epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev);
  1400. LogSingleMsg("out DataProcessLinux");
  1401. }
  1402. else if (events[i].events & EPOLLOUT)
  1403. {
  1404. cout << "epoll out" << endl;
  1405. sockfd = events[i].data.fd;
  1406. write(sockfd, line, n);
  1407. ev.data.fd = sockfd;
  1408. ev.events = EPOLLIN | EPOLLET;
  1409. epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev);
  1410. }
  1411. }
  1412. }
  1413. #else
  1414. HANDLE hCompletionPort;
  1415. hCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
  1416. // get system info to create work thread
  1417. SYSTEM_INFO SystemInfo;
  1418. GetSystemInfo(&SystemInfo);
  1419. for (int i = 0; i < SystemInfo.dwNumberOfProcessors * 2; i++)
  1420. {
  1421. HANDLE hProcessIO = CreateThread(NULL, 0, ProcessIO, hCompletionPort, 0, NULL);
  1422. if (hProcessIO)
  1423. CloseHandle(hProcessIO);
  1424. }
  1425. //waiting thread
  1426. //_beginthreadex(NULL,0,DoWork,NULL,0,NULL);
  1427. StartDoWorkRVC();
  1428. SOCKET sClient;
  1429. LPPER_HANDLE_DATA PerHandleData;
  1430. LPPER_IO_OPERATION_DATA PerIoData;
  1431. while (true)
  1432. {
  1433. //sClient = WSAAccept(sListen, NULL, NULL, NULL, 0);
  1434. sClient = accept(g_sListen, NULL, NULL);
  1435. //cout << "Socket " << sClient << "connect" << endl;
  1436. PerHandleData = new PER_HANDLE_DATA();
  1437. PerHandleData->Socket = sClient;
  1438. // client completion port
  1439. CreateIoCompletionPort((HANDLE)sClient, hCompletionPort, (DWORD)PerHandleData, 0);
  1440. //
  1441. PerIoData = new PER_IO_OPERATION_DATA();
  1442. ZeroMemory(PerIoData, sizeof(PER_IO_OPERATION_DATA));
  1443. PerIoData->DataBuf.buf = PerIoData->Buffer;
  1444. PerIoData->DataBuf.len = DATA_BUFSIZE;
  1445. // WSARecv
  1446. DWORD Flags = 0;
  1447. DWORD dwRecv = 0;
  1448. WSARecv(sClient, &PerIoData->DataBuf, 1, &dwRecv, &Flags, &PerIoData->Overlapped, NULL);
  1449. LogToFile(false, false, false, "hold");
  1450. }
  1451. DWORD dwByteTrans;
  1452. PostQueuedCompletionStatus(hCompletionPort, dwByteTrans, 0, 0);
  1453. closesocket(g_sListen);
  1454. #endif //linux
  1455. }
  1456. void CheckGuardianDbgDirAndCreateDbgFile(bool bChangeDay = false)
  1457. {
  1458. #ifdef linux
  1459. //todo oiltestlinux
  1460. string guardianLogDir("/opt/rvc/dbg/guardian");
  1461. if (opendir(guardianLogDir.c_str()) == NULL)
  1462. {
  1463. ServerReportEvent("Can't find guardian dbg dir,to create it.");
  1464. mkdir(guardianLogDir.c_str(), 0775);
  1465. }
  1466. #else
  1467. ZeroMemory(currDirBuf, sizeof(currDirBuf));
  1468. ZeroMemory(chDisk, sizeof(chDisk));
  1469. GetCurrentDirectory(256, currDirBuf);
  1470. chDisk[0] = currDirBuf[0];
  1471. // C:\Run\version\1.7.0.1
  1472. string strDir(chDisk), guardianLogDir(""), strGuardian("\\rvc\\dbg\\guardian");
  1473. guardianLogDir = strDir + ":" + strGuardian;
  1474. WIN32_FIND_DATA wfd;
  1475. bool rValue = false;
  1476. HANDLE hFind = FindFirstFile(guardianLogDir.c_str(), &wfd);
  1477. if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
  1478. {
  1479. ServerReportEvent("find guardian log dir.");
  1480. }
  1481. else
  1482. {
  1483. ServerReportEvent("can't find guardian log dir:");
  1484. int ret = _mkdir(guardianLogDir.c_str());
  1485. if (ret != 0)
  1486. {
  1487. ServerReportEvent("Create guardian log dir failed.");
  1488. ServerReportEvent(guardianLogDir.c_str());
  1489. return;
  1490. }
  1491. else
  1492. ServerReportEvent("Create guardian log dir suc.");
  1493. }
  1494. FindClose(hFind);
  1495. #endif //linux
  1496. SYSTEMTIME st;
  1497. GetLocalTimeRVC(st);
  1498. g_startDay = st.wDay;
  1499. char date[12];
  1500. memset(date,0,12);
  1501. sprintf(date, "%.4d%.2d%.2d", st.wYear, st.wMonth, st.wDay);
  1502. string strLogFile(""), strDate(date);
  1503. strLogFile = guardianLogDir + "/" + date + ".log";
  1504. if (!bChangeDay)
  1505. LogSingleMsg(strLogFile.c_str());
  1506. logFile.open(strLogFile.c_str(), std::ofstream::binary | ios::app);
  1507. if (logFile.is_open())
  1508. {
  1509. if (!bChangeDay)
  1510. LogSingleMsg("open guardian dbg file suc.");
  1511. g_bLogFileOpen = true;
  1512. if (!bChangeDay){
  1513. LogToFile(false, false, false, "==============guardian start==============");
  1514. LogToFile(false, false, false, strLogFile.c_str());
  1515. }
  1516. }
  1517. else
  1518. {
  1519. if (!bChangeDay){
  1520. LogSingleMsg("open guardian dbg file failed.",errno);
  1521. LogSingleMsg(strerror(errno));
  1522. }
  1523. }
  1524. }
  1525. #if linux
  1526. static void sig_handle(int signo)
  1527. {
  1528. switch (signo) {
  1529. case SIGSEGV:
  1530. {
  1531. LogSingleMsg("=========>>> capture signal SIGSEGV <<<=========");
  1532. break;
  1533. }
  1534. case SIGTERM:
  1535. LogSingleMsg("=========>>> capture signal SIGTERM <<<=========");
  1536. break;
  1537. case SIGCHLD:
  1538. {
  1539. LogSingleMsg("=========>>> capture signal SIGCHLD <<<=========");
  1540. if (signal(SIGCHLD, sig_handle) == SIG_ERR)
  1541. LogSingleMsg("signal error.");
  1542. int status;
  1543. pid_t pid;
  1544. while ((pid = waitpid(0, &status, WNOHANG)) > 0) {
  1545. char szMsg[256] = { '\0' };
  1546. bool excep(false);
  1547. if (WIFEXITED(status)) {
  1548. sprintf(szMsg, "child process %d terminated normal with exit code: %d", pid, WEXITSTATUS(status));
  1549. } else {
  1550. const int signum = WTERMSIG(status);
  1551. sprintf(szMsg, "child process %d has been terminated unexpectly by signal %d", pid, signum);
  1552. //if(signum != SIGKILL)
  1553. excep = true;
  1554. }
  1555. LogSingleMsg(szMsg);
  1556. if (g_SpShellPID != 0 && g_SpShellPID == pid) {
  1557. LogSingleMsg("Specified spshell process has exited!");
  1558. g_SpShellPID = 0;
  1559. if (excep) {
  1560. LogSingleMsg("Confirm other relate process has been terminated.");
  1561. int count = 60;
  1562. alive_process_info processes[60];
  1563. memset(processes, 0, sizeof(processes));
  1564. if (!osutil_detect_unique_app(relate_processes_ex, array_size(relate_processes_ex), &count, processes)) {
  1565. bool spshell_exist(false);
  1566. for (int i = 0; i < count; ++i) {
  1567. if (strcmp(processes[i].name, spshell_execute_name) == 0) {
  1568. spshell_exist = true;
  1569. break;
  1570. }
  1571. }
  1572. for (int i = 0; !spshell_exist && i < count; ++i) {
  1573. kill(processes[i].pid, SIGKILL);
  1574. LogToFile(true, true, true, "kill", processes[i].name, processes[i].pid, errno);
  1575. }
  1576. }
  1577. }
  1578. }
  1579. }
  1580. break;
  1581. }
  1582. default:
  1583. char szMsg[256] = { '\0' };
  1584. sprintf(szMsg, "=========>>> capture signal %d <<<=========", signo);
  1585. LogSingleMsg(szMsg);
  1586. break;
  1587. }
  1588. return;
  1589. }
  1590. #endif
  1591. int main()
  1592. {
  1593. //attach file descriptors 0,1,2 to /dev/null(for deamon app)
  1594. int fd0, fd1, fd2;
  1595. g_bFrameOnline = true;
  1596. #ifdef linux
  1597. fd0 = open("/dev/null", O_RDWR);
  1598. fd1 = dup(0);
  1599. fd2 = dup(0);
  1600. pthread_mutex_init(&g_cs_event,NULL);
  1601. pthread_mutex_init(&g_cs_log,NULL);
  1602. pthread_mutex_init(&g_cs,NULL);
  1603. #else
  1604. InitializeCriticalSectionAndSpinCount(&g_cs_event, 100);
  1605. InitializeCriticalSectionAndSpinCount(&g_cs_log, 100);
  1606. InitializeCriticalSectionAndSpinCount(&g_cs, 100);
  1607. // g_logHandle = CreateEventA(NULL, FALSE, FALSE, NULL);
  1608. #endif
  1609. g_dwTimeBegin = GetTickCountRVC();
  1610. int i=1000;
  1611. CheckGuardianDbgDirAndCreateDbgFile();
  1612. LogSingleMsg("version: " GUARDIAN_VERSION_STR);
  1613. #if linux
  1614. g_SpShellPID = GetSpshellProcID();
  1615. LogToFile(false, true, false, "get spshell proc id", NULL, g_SpShellPID);
  1616. if (signal(SIGCHLD, sig_handle) == SIG_ERR) {
  1617. LogToFile(false, false, false, "register for SIGCHLD failed", "", errno, 0, 0);
  1618. } else {
  1619. LogSingleMsg("register for SIGCHLD succ.");
  1620. }
  1621. #endif
  1622. StartDoNetControlRVC();
  1623. LogSingleMsg(currDirBuf);
  1624. InitListenSocketRVC();
  1625. AcceptReqRVC();
  1626. }
  1627. void NetControl()
  1628. {
  1629. return;//oiltmp 20150724 for zl don't forbid net for now
  1630. #ifdef linux
  1631. //todo oiltestlinux
  1632. #else
  1633. HINSTANCE hmod = ::LoadLibrary(DLL_PATH);
  1634. if(hmod != NULL)
  1635. {
  1636. LogSingleMsg("NetControl start");
  1637. pWlanConnect WlanConnect = (pWlanConnect)GetProcAddress(hmod, "WlanConnect");
  1638. pDisableBluetooth BluetoothConnect = (pDisableBluetooth)GetProcAddress(hmod, "DisableBluetooth");
  1639. if (WlanConnect != NULL && BluetoothConnect != NULL)
  1640. {
  1641. DWORD dwRetWire,dwRetEther,dwRet3G,dwRet4G,dwRetBT;
  1642. dwRetWire = dwRetEther = dwRet3G = dwRet4G = dwRetBT = 0;
  1643. dwRetWire = WlanConnect(FALSE, NET_TYPE_WIRELESS);
  1644. LogSingleMsg("after wireless");
  1645. dwRetEther = WlanConnect(FALSE, NET_TYPE_ETHERNET);
  1646. LogSingleMsg("after ether");
  1647. dwRet3G = WlanConnect(FALSE, NET_TYPE_3G);
  1648. LogSingleMsg("after 3g");
  1649. dwRet4G = WlanConnect(FALSE, NET_TYPE_4G);
  1650. LogSingleMsg("after 4g");
  1651. dwRetBT = BluetoothConnect(TRUE);
  1652. LogSingleMsg("after bluetooth");
  1653. char buf[128];
  1654. ZeroMemory(buf,sizeof(buf));
  1655. sprintf(buf,"Wire Net open state:Wireless[%d],Ethernet[%d],3G[%d],4G[%d],Blue tooth[%d]",dwRetWire,dwRetEther,dwRet3G,dwRet4G,dwRetBT);
  1656. LogSingleMsg(buf);
  1657. }
  1658. else
  1659. LogSingleMsg("Get function from CmbPadDll failed!");
  1660. }
  1661. else
  1662. LogSingleMsg("load CmbPadDll failed!");
  1663. #endif //linux
  1664. }
  1665. void LogDebug(bool bRevMsg, bool bCode1,bool bCode2,const char *msg, const char *revmsg, int code1, int code2)
  1666. {
  1667. SYSTEMTIME st;
  1668. GetLocalTimeRVC(st);
  1669. memset(g_allMsg,0,1024);
  1670. if (bRevMsg)
  1671. {
  1672. if (bCode1)
  1673. {
  1674. if (bCode2)
  1675. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s,%s,%d,%d\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1676. GetProcID(),
  1677. msg, revmsg, code1, code2);
  1678. else
  1679. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s,%s %d\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1680. GetProcID(),
  1681. msg, revmsg, code1);
  1682. }
  1683. else
  1684. {
  1685. if (bCode2)
  1686. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s,%s %d\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1687. GetProcID(),
  1688. msg, revmsg,code2);
  1689. else
  1690. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s,%s\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1691. GetProcID(),
  1692. msg, revmsg);
  1693. }
  1694. }
  1695. else
  1696. {
  1697. if (bCode1)
  1698. {
  1699. if (bCode2)
  1700. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s,%d,%d\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1701. GetProcID(),
  1702. msg, code1, code2);
  1703. else
  1704. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s %d\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1705. GetProcID(),
  1706. msg, code1);
  1707. }
  1708. else
  1709. {
  1710. if (bCode2)
  1711. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s %d\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
  1712. GetProcID(),
  1713. msg, code2);
  1714. else
  1715. sprintf(g_allMsg, "[%.2d:%.2d:%.2d.%.3d][%d][DEBUG]%s\r\n", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, GetProcID(), msg);
  1716. }
  1717. }
  1718. if (g_bLogFileOpen)
  1719. {
  1720. logFile.write(g_allMsg, strlen(g_allMsg));
  1721. logFile.flush();
  1722. }
  1723. }
  1724. void LogSingleMsg(const char *msg, int type)
  1725. {
  1726. #ifdef linux
  1727. SYSTEMTIME st;
  1728. GetLocalTimeRVC(st);
  1729. #endif
  1730. LogToFile(false, false, false, msg,"",0,0,type);
  1731. }
  1732. void LogToFile(bool bRevMsg, bool bCode1,bool bCode2,const char *msg, const char *revmsg, int code1, int code2, int type)
  1733. {
  1734. SYSTEMTIME st;
  1735. GetLocalTimeRVC(st);
  1736. EnterCriticalSectionRVC(g_cs_event);
  1737. //LogDebug(true, true, true, "oil", "test", g_startDay, st.wDay);
  1738. if (g_startDay != st.wDay)//switch to new day log
  1739. {
  1740. ServerReportEvent("change date");
  1741. logFile.close();
  1742. CheckGuardianDbgDirAndCreateDbgFile(true);
  1743. }
  1744. switch (type)
  1745. {
  1746. case 0:
  1747. default:
  1748. LogDebug(bRevMsg, bCode1,bCode2,msg, revmsg, code1, code2);
  1749. break;
  1750. }
  1751. LeaveCriticalSectionRVC(g_cs_event);
  1752. }