guardian.cpp 50 KB

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