guardian.cpp 49 KB

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