hmain.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. #include "hmain.h"
  2. #include "hplatform.h"
  3. #include "hlog.h"
  4. #include "htime.h"
  5. main_ctx_t g_main_ctx;
  6. int g_worker_processes_num = 0;
  7. proc_ctx_t* g_worker_processes = NULL;
  8. int main_ctx_init(int argc, char** argv) {
  9. g_main_ctx.pid = getpid();
  10. char* cwd = getcwd(g_main_ctx.run_path, sizeof(g_main_ctx.run_path));
  11. if (cwd == NULL) {
  12. printf("getcwd error\n");
  13. }
  14. //printf("run_path=%s\n", g_main_ctx.run_path);
  15. const char* b = argv[0];
  16. const char* e = b;
  17. while (*e) ++e;
  18. --e;
  19. while (e >= b) {
  20. if (*e == '/' || *e == '\\') {
  21. break;
  22. }
  23. --e;
  24. }
  25. strncpy(g_main_ctx.program_name, e+1, sizeof(g_main_ctx.program_name));
  26. #ifdef OS_WIN
  27. if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) {
  28. *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0';
  29. }
  30. #endif
  31. //printf("program_name=%s\n", g_main_ctx.program_name);
  32. // save arg
  33. int i = 0;
  34. g_main_ctx.os_argv = argv;
  35. g_main_ctx.argc = 0;
  36. g_main_ctx.arg_len = 0;
  37. for (i = 0; argv[i]; ++i) {
  38. g_main_ctx.arg_len += strlen(argv[i]) + 1;
  39. }
  40. g_main_ctx.argc = i;
  41. char* argp = (char*)malloc(g_main_ctx.arg_len);
  42. memset(argp, 0, g_main_ctx.arg_len);
  43. g_main_ctx.save_argv = (char**)malloc((g_main_ctx.argc+1) * sizeof(char*));
  44. char* cmdline = (char*)malloc(g_main_ctx.arg_len);
  45. g_main_ctx.cmdline = cmdline;
  46. for (i = 0; argv[i]; ++i) {
  47. g_main_ctx.save_argv[i] = argp;
  48. strcpy(g_main_ctx.save_argv[i], argv[i]);
  49. argp += strlen(argv[i]) + 1;
  50. strcpy(cmdline, argv[i]);
  51. cmdline += strlen(argv[i]);
  52. *cmdline = ' ';
  53. ++cmdline;
  54. }
  55. g_main_ctx.save_argv[g_main_ctx.argc] = NULL;
  56. g_main_ctx.cmdline[g_main_ctx.arg_len-1] = '\0';
  57. #if defined(OS_WIN) || defined(OS_LINUX)
  58. // save env
  59. g_main_ctx.os_envp = environ;
  60. g_main_ctx.envc = 0;
  61. g_main_ctx.env_len = 0;
  62. for (i = 0; environ[i]; ++i) {
  63. g_main_ctx.env_len += strlen(environ[i]) + 1;
  64. }
  65. g_main_ctx.envc = i;
  66. char* envp = (char*)malloc(g_main_ctx.env_len);
  67. memset(envp, 0, g_main_ctx.env_len);
  68. g_main_ctx.save_envp = (char**)malloc((g_main_ctx.envc+1) * sizeof(char*));
  69. for (i = 0; environ[i]; ++i) {
  70. g_main_ctx.save_envp[i] = envp;
  71. strcpy(g_main_ctx.save_envp[i], environ[i]);
  72. envp += strlen(environ[i]) + 1;
  73. }
  74. g_main_ctx.save_envp[g_main_ctx.envc] = NULL;
  75. // parse env
  76. for (i = 0; environ[i]; ++i) {
  77. char* b = environ[i];
  78. char* delim = strchr(b, '=');
  79. if (delim == NULL) {
  80. continue;
  81. }
  82. g_main_ctx.env_kv[std::string(b, delim-b)] = std::string(delim+1);
  83. }
  84. #endif
  85. char logpath[MAX_PATH] = {0};
  86. snprintf(logpath, sizeof(logpath), "%s/logs", g_main_ctx.run_path);
  87. MKDIR(logpath);
  88. snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_path, g_main_ctx.program_name);
  89. snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_path, g_main_ctx.program_name);
  90. snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.confile), "%s/logs/%s.log", g_main_ctx.run_path, g_main_ctx.program_name);
  91. hlog_set_file(g_main_ctx.logfile);
  92. g_main_ctx.oldpid = getpid_from_pidfile();
  93. #ifdef OS_UNIX
  94. if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) {
  95. g_main_ctx.oldpid = -1;
  96. }
  97. #else
  98. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, g_main_ctx.oldpid);
  99. if (hproc == NULL) {
  100. g_main_ctx.oldpid = -1;
  101. }
  102. else {
  103. CloseHandle(hproc);
  104. }
  105. #endif
  106. return 0;
  107. }
  108. #define UNDEFINED_OPTION -1
  109. static int get_arg_type(int short_opt, const char* options) {
  110. if (options == NULL) return UNDEFINED_OPTION;
  111. const char* p = options;
  112. while (*p && *p != short_opt) ++p;
  113. if (*p == '\0') return UNDEFINED_OPTION;
  114. if (*(p+1) == ':') return REQUIRED_ARGUMENT;
  115. return NO_ARGUMENT;
  116. }
  117. int parse_opt(int argc, char** argv, const char* options) {
  118. for (int i = 1; argv[i]; ++i) {
  119. char* p = argv[i];
  120. if (*p != '-') {
  121. g_main_ctx.arg_list.push_back(argv[i]);
  122. continue;
  123. }
  124. while (*++p) {
  125. int arg_type = get_arg_type(*p, options);
  126. if (arg_type == UNDEFINED_OPTION) {
  127. printf("Invalid option '%c'\n", *p);
  128. return -20;
  129. } else if (arg_type == NO_ARGUMENT) {
  130. g_main_ctx.arg_kv[std::string(p, 1)] = OPTION_ENABLE;
  131. continue;
  132. } else if (arg_type == REQUIRED_ARGUMENT) {
  133. if (*(p+1) != '\0') {
  134. g_main_ctx.arg_kv[std::string(p, 1)] = p+1;
  135. break;
  136. } else if (argv[i+1] != NULL) {
  137. g_main_ctx.arg_kv[std::string(p, 1)] = argv[++i];
  138. break;
  139. } else {
  140. printf("Option '%c' requires param\n", *p);
  141. return -30;
  142. }
  143. }
  144. }
  145. }
  146. return 0;
  147. }
  148. static const option_t* get_option(const char* opt, const option_t* long_options, int size) {
  149. if (opt == NULL || long_options == NULL) return NULL;
  150. int len = strlen(opt);
  151. if (len == 0) return NULL;
  152. if (len == 1) {
  153. for (int i = 0; i < size; ++i) {
  154. if (long_options[i].short_opt == *opt) {
  155. return &long_options[i];
  156. }
  157. }
  158. } else {
  159. for (int i = 0; i < size; ++i) {
  160. if (strcmp(long_options[i].long_opt, opt) == 0) {
  161. return &long_options[i];
  162. }
  163. }
  164. }
  165. return NULL;
  166. }
  167. #define MAX_OPTION 32
  168. // opt type
  169. #define NOPREFIX_OPTION 0
  170. #define SHORT_OPTION -1
  171. #define LONG_OPTION -2
  172. int parse_opt_long(int argc, char** argv, const option_t* long_options, int size) {
  173. char opt[MAX_OPTION+1] = {0};
  174. for (int i = 1; argv[i]; ++i) {
  175. char* arg = argv[i];
  176. int opt_type = NOPREFIX_OPTION;
  177. // prefix
  178. if (*arg == OPTION_PREFIX) {
  179. ++arg;
  180. opt_type = SHORT_OPTION;
  181. if (*arg == OPTION_PREFIX) {
  182. ++arg;
  183. opt_type = LONG_OPTION;
  184. }
  185. }
  186. int arg_len = strlen(arg);
  187. // delim
  188. char* delim = strchr(arg, OPTION_DELIM);
  189. if (delim == arg || delim == arg+arg_len-1 || delim-arg > MAX_OPTION) {
  190. printf("Invalid option '%s'\n", argv[i]);
  191. return -10;
  192. }
  193. if (delim) {
  194. memcpy(opt, arg, delim-arg);
  195. opt[delim-arg] = '\0';
  196. } else {
  197. if (opt_type == SHORT_OPTION) {
  198. *opt = *arg;
  199. opt[1] = '\0';
  200. } else {
  201. strncpy(opt, arg, MAX_OPTION);
  202. }
  203. }
  204. // get_option
  205. const option_t* pOption = get_option(opt, long_options, size);
  206. if (pOption == NULL) {
  207. if (delim == NULL && opt_type == NOPREFIX_OPTION) {
  208. g_main_ctx.arg_list.push_back(arg);
  209. continue;
  210. } else {
  211. printf("Invalid option: '%s'\n", argv[i]);
  212. return -10;
  213. }
  214. }
  215. const char* value = NULL;
  216. if (pOption->arg_type == NO_ARGUMENT) {
  217. // -h
  218. value = OPTION_ENABLE;
  219. } else if (pOption->arg_type == REQUIRED_ARGUMENT) {
  220. if (delim) {
  221. // --port=80
  222. value = delim+1;
  223. } else {
  224. if (opt_type == SHORT_OPTION && *(arg+1) != '\0') {
  225. // p80
  226. value = arg+1;
  227. } else if (argv[i+1] != NULL) {
  228. // --port 80
  229. value = argv[++i];
  230. } else {
  231. printf("Option '%s' requires parament\n", opt);
  232. return -20;
  233. }
  234. }
  235. }
  236. // preferred to use short_opt as key
  237. if (pOption->short_opt > 0) {
  238. g_main_ctx.arg_kv[std::string(1, pOption->short_opt)] = value;
  239. } else if (pOption->long_opt) {
  240. g_main_ctx.arg_kv[pOption->long_opt] = value;
  241. }
  242. }
  243. return 0;
  244. }
  245. const char* get_arg(const char* key) {
  246. auto iter = g_main_ctx.arg_kv.find(key);
  247. if (iter == g_main_ctx.arg_kv.end()) {
  248. return NULL;
  249. }
  250. return iter->second.c_str();
  251. }
  252. const char* get_env(const char* key) {
  253. auto iter = g_main_ctx.env_kv.find(key);
  254. if (iter == g_main_ctx.env_kv.end()) {
  255. return NULL;
  256. }
  257. return iter->second.c_str();
  258. }
  259. #ifdef OS_UNIX
  260. /*
  261. * memory layout
  262. * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0
  263. */
  264. void setproctitle(const char* title) {
  265. //printf("proctitle=%s\n", title);
  266. int len = g_main_ctx.arg_len + g_main_ctx.env_len;
  267. if (strlen(title) >= len) return;
  268. memset(g_main_ctx.os_argv[0], 0, len);
  269. strcpy(g_main_ctx.os_argv[0], title);
  270. }
  271. #endif
  272. int create_pidfile() {
  273. FILE* fp = fopen(g_main_ctx.pidfile, "w");
  274. if (fp == NULL) {
  275. printf("fopen [%s] error: %d\n", g_main_ctx.pidfile, errno);
  276. return -10;
  277. }
  278. char pid[16] = {0};
  279. snprintf(pid, sizeof(pid), "%d\n", g_main_ctx.pid);
  280. fwrite(pid, 1, strlen(pid), fp);
  281. fclose(fp);
  282. hlogi("create_pidfile [%s] pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  283. atexit(delete_pidfile);
  284. return 0;
  285. }
  286. void delete_pidfile() {
  287. remove(g_main_ctx.pidfile);
  288. hlogi("delete_pidfile [%s]", g_main_ctx.pidfile);
  289. }
  290. pid_t getpid_from_pidfile() {
  291. FILE* fp = fopen(g_main_ctx.pidfile, "r");
  292. if (fp == NULL) {
  293. //printf("fopen [%s] error: %d\n", g_conf_ctx.pidfile, errno);
  294. return -1;
  295. }
  296. char pid[64];
  297. int readbytes = fread(pid, 1, sizeof(pid), fp);
  298. fclose(fp);
  299. if (readbytes <= 0) {
  300. //printf("fread [%s] bytes=%d\n", g_main_ctx.pidfile, readbytes);
  301. return -1;
  302. }
  303. return atoi(pid);
  304. }
  305. static procedure_t s_reload_fn = NULL;
  306. static void* s_reload_userdata = NULL;
  307. #ifdef OS_UNIX
  308. // unix use signal
  309. #include <sys/wait.h>
  310. void signal_handler(int signo) {
  311. hlogi("pid=%d recv signo=%d", getpid(), signo);
  312. switch (signo) {
  313. case SIGINT:
  314. case SIGNAL_TERMINATE:
  315. hlogi("killall processes");
  316. signal(SIGCHLD, SIG_IGN);
  317. // master send SIGKILL => workers
  318. for (int i = 0; i < g_worker_processes_num; ++i) {
  319. if (g_worker_processes[i].pid <= 0) break;
  320. kill(g_worker_processes[i].pid, SIGKILL);
  321. g_worker_processes[i].pid = -1;
  322. }
  323. exit(0);
  324. break;
  325. case SIGNAL_RELOAD:
  326. if (s_reload_fn) {
  327. s_reload_fn(s_reload_userdata);
  328. if (getpid_from_pidfile() == getpid()) {
  329. // master send SIGNAL_RELOAD => workers
  330. for (int i = 0; i < g_worker_processes_num; ++i) {
  331. if (g_worker_processes[i].pid <= 0) break;
  332. kill(g_worker_processes[i].pid, SIGNAL_RELOAD);
  333. }
  334. }
  335. }
  336. break;
  337. case SIGCHLD:
  338. {
  339. pid_t pid = 0;
  340. int status = 0;
  341. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  342. hlogw("proc stop/waiting, pid=%d status=%d", pid, status);
  343. for (int i = 0; i < g_worker_processes_num; ++i) {
  344. if (g_worker_processes[i].pid == pid) {
  345. g_worker_processes[i].pid = -1;
  346. spawn_proc(&g_worker_processes[i]);
  347. break;
  348. }
  349. }
  350. }
  351. }
  352. break;
  353. default:
  354. break;
  355. }
  356. }
  357. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  358. s_reload_fn = reload_fn;
  359. s_reload_userdata = reload_userdata;
  360. signal(SIGINT, signal_handler);
  361. signal(SIGCHLD, signal_handler);
  362. signal(SIGNAL_TERMINATE, signal_handler);
  363. signal(SIGNAL_RELOAD, signal_handler);
  364. return 0;
  365. }
  366. #elif defined(OS_WIN)
  367. // win32 use Event
  368. //static HANDLE s_hEventTerm = NULL;
  369. static HANDLE s_hEventReload = NULL;
  370. #include <mmsystem.h>
  371. #ifdef _MSC_VER
  372. #pragma comment(lib, "winmm.lib")
  373. #endif
  374. void WINAPI on_timer(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) {
  375. DWORD ret;
  376. /*
  377. ret = WaitForSingleObject(s_hEventTerm, 0);
  378. if (ret == WAIT_OBJECT_0) {
  379. hlogi("pid=%d recv event [TERM]", getpid());
  380. if (getpid_from_pidfile() == getpid()) {
  381. timeKillEvent(uTimerID);
  382. exit(0);
  383. }
  384. }
  385. */
  386. ret = WaitForSingleObject(s_hEventReload, 0);
  387. if (ret == WAIT_OBJECT_0) {
  388. hlogi("pid=%d recv event [RELOAD]", getpid());
  389. if (s_reload_fn) {
  390. s_reload_fn(s_reload_userdata);
  391. }
  392. }
  393. }
  394. void signal_cleanup() {
  395. //CloseHandle(s_hEventTerm);
  396. //s_hEventTerm = NULL;
  397. CloseHandle(s_hEventReload);
  398. s_hEventReload = NULL;
  399. }
  400. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  401. s_reload_fn = reload_fn;
  402. s_reload_userdata = reload_userdata;
  403. char eventname[MAX_PATH] = {0};
  404. //snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  405. //s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  406. //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname);
  407. snprintf(eventname, sizeof(eventname), "%s_reload_event", g_main_ctx.program_name);
  408. s_hEventReload = CreateEvent(NULL, FALSE, FALSE, eventname);
  409. timeSetEvent(1000, 1000, on_timer, 0, TIME_PERIODIC);
  410. atexit(signal_cleanup);
  411. return 0;
  412. }
  413. #endif
  414. static void kill_proc(int pid) {
  415. #ifdef OS_UNIX
  416. kill(pid, SIGNAL_TERMINATE);
  417. #else
  418. //SetEvent(s_hEventTerm);
  419. //sleep(1);
  420. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
  421. if (hproc) {
  422. TerminateProcess(hproc, 0);
  423. CloseHandle(hproc);
  424. }
  425. #endif
  426. }
  427. void handle_signal(const char* signal) {
  428. if (strcmp(signal, "start") == 0) {
  429. if (g_main_ctx.oldpid > 0) {
  430. printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  431. exit(0);
  432. }
  433. } else if (strcmp(signal, "stop") == 0) {
  434. if (g_main_ctx.oldpid > 0) {
  435. kill_proc(g_main_ctx.oldpid);
  436. printf("%s stop/waiting\n", g_main_ctx.program_name);
  437. } else {
  438. printf("%s is already stopped\n", g_main_ctx.program_name);
  439. }
  440. exit(0);
  441. } else if (strcmp(signal, "restart") == 0) {
  442. if (g_main_ctx.oldpid > 0) {
  443. kill_proc(g_main_ctx.oldpid);
  444. printf("%s stop/waiting\n", g_main_ctx.program_name);
  445. msleep(1000);
  446. }
  447. } else if (strcmp(signal, "status") == 0) {
  448. if (g_main_ctx.oldpid > 0) {
  449. printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  450. } else {
  451. printf("%s stop/waiting\n", g_main_ctx.program_name);
  452. }
  453. exit(0);
  454. } else if (strcmp(signal, "reload") == 0) {
  455. if (g_main_ctx.oldpid > 0) {
  456. printf("reload confile [%s]\n", g_main_ctx.confile);
  457. #ifdef OS_UNIX
  458. kill(g_main_ctx.oldpid, SIGNAL_RELOAD);
  459. #else
  460. SetEvent(s_hEventReload);
  461. #endif
  462. }
  463. sleep(1);
  464. exit(0);
  465. } else {
  466. printf("Invalid signal: '%s'\n", signal);
  467. exit(0);
  468. }
  469. printf("%s start/running\n", g_main_ctx.program_name);
  470. }