1
0

hmain.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. #include "hmain.h"
  2. #include "hbase.h"
  3. #include "hlog.h"
  4. #include "herr.h"
  5. #include "htime.h"
  6. #include "hthread.h"
  7. #ifdef OS_DARWIN
  8. #include <crt_externs.h>
  9. #define environ (*_NSGetEnviron())
  10. #endif
  11. main_ctx_t g_main_ctx;
  12. printf_t printf_fn = printf;
  13. static void init_arg_kv(int maxsize) {
  14. g_main_ctx.arg_kv_size = 0;
  15. SAFE_ALLOC(g_main_ctx.arg_kv, sizeof(char*) * maxsize);
  16. }
  17. static void save_arg_kv(const char* key, int key_len, const char* val, int val_len) {
  18. if (key_len <= 0) key_len = strlen(key);
  19. if (val_len <= 0) val_len = strlen(val);
  20. char* arg = NULL;
  21. SAFE_ALLOC(arg, key_len + val_len + 2);
  22. memcpy(arg, key, key_len);
  23. arg[key_len] = '=';
  24. memcpy(arg + key_len + 1, val, val_len);
  25. // printf("save_arg_kv: %s\n", arg);
  26. g_main_ctx.arg_kv[g_main_ctx.arg_kv_size++] = arg;
  27. }
  28. static void init_arg_list(int maxsize) {
  29. g_main_ctx.arg_list_size = 0;
  30. SAFE_ALLOC(g_main_ctx.arg_list, sizeof(char*) * maxsize);
  31. }
  32. static void save_arg_list(const char* arg) {
  33. // printf("save_arg_list: %s\n", arg);
  34. g_main_ctx.arg_list[g_main_ctx.arg_list_size++] = strdup(arg);
  35. }
  36. static const char* get_val(char** kvs, const char* key) {
  37. if (kvs == NULL) return NULL;
  38. int key_len = strlen(key);
  39. char* kv = NULL;
  40. int kv_len = 0;
  41. for (int i = 0; kvs[i]; ++i) {
  42. kv = kvs[i];
  43. kv_len = strlen(kv);
  44. if (kv_len <= key_len) continue;
  45. // key=val
  46. if (memcmp(kv, key, key_len) == 0 && kv[key_len] == '=') {
  47. return kv + key_len + 1;
  48. }
  49. }
  50. return NULL;
  51. }
  52. const char* get_arg(const char* key) {
  53. return get_val(g_main_ctx.arg_kv, key);
  54. }
  55. const char* get_env(const char* key) {
  56. return get_val(g_main_ctx.save_envp, key);
  57. }
  58. int main_ctx_init(int argc, char** argv) {
  59. if (argc == 0 || argv == NULL) {
  60. argc = 1;
  61. SAFE_ALLOC(argv, 2 * sizeof(char*));
  62. SAFE_ALLOC(argv[0], MAX_PATH);
  63. get_executable_path(argv[0], MAX_PATH);
  64. }
  65. get_run_dir(g_main_ctx.run_dir, sizeof(g_main_ctx.run_dir));
  66. //printf("run_dir=%s\n", g_main_ctx.run_dir);
  67. strncpy(g_main_ctx.program_name, hv_basename(argv[0]), sizeof(g_main_ctx.program_name));
  68. #ifdef OS_WIN
  69. if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) {
  70. *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0';
  71. }
  72. #endif
  73. //printf("program_name=%s\n", g_main_ctx.program_name);
  74. char logdir[MAX_PATH] = {0};
  75. snprintf(logdir, sizeof(logdir), "%s/logs", g_main_ctx.run_dir);
  76. hv_mkdir(logdir);
  77. snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_dir, g_main_ctx.program_name);
  78. snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_dir, g_main_ctx.program_name);
  79. snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.logfile), "%s/logs/%s.log", g_main_ctx.run_dir, g_main_ctx.program_name);
  80. hlog_set_file(g_main_ctx.logfile);
  81. g_main_ctx.pid = getpid();
  82. g_main_ctx.oldpid = getpid_from_pidfile();
  83. #ifdef OS_UNIX
  84. if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) {
  85. g_main_ctx.oldpid = -1;
  86. }
  87. #else
  88. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, g_main_ctx.oldpid);
  89. if (hproc == NULL) {
  90. g_main_ctx.oldpid = -1;
  91. }
  92. else {
  93. CloseHandle(hproc);
  94. }
  95. #endif
  96. // save arg
  97. int i = 0;
  98. g_main_ctx.os_argv = argv;
  99. g_main_ctx.argc = 0;
  100. g_main_ctx.arg_len = 0;
  101. for (i = 0; argv[i]; ++i) {
  102. g_main_ctx.arg_len += strlen(argv[i]) + 1;
  103. }
  104. g_main_ctx.argc = i;
  105. char* argp = NULL;
  106. SAFE_ALLOC(argp, g_main_ctx.arg_len);
  107. SAFE_ALLOC(g_main_ctx.save_argv, (g_main_ctx.argc + 1) * sizeof(char*));
  108. char* cmdline = NULL;
  109. SAFE_ALLOC(cmdline, g_main_ctx.arg_len);
  110. g_main_ctx.cmdline = cmdline;
  111. for (i = 0; argv[i]; ++i) {
  112. strcpy(argp, argv[i]);
  113. g_main_ctx.save_argv[i] = argp;
  114. argp += strlen(argv[i]) + 1;
  115. strcpy(cmdline, argv[i]);
  116. cmdline += strlen(argv[i]);
  117. *cmdline = ' ';
  118. ++cmdline;
  119. }
  120. g_main_ctx.save_argv[g_main_ctx.argc] = NULL;
  121. g_main_ctx.cmdline[g_main_ctx.arg_len-1] = '\0';
  122. #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_DARWIN)
  123. // save env
  124. g_main_ctx.os_envp = environ;
  125. g_main_ctx.envc = 0;
  126. g_main_ctx.env_len = 0;
  127. for (i = 0; environ[i]; ++i) {
  128. g_main_ctx.env_len += strlen(environ[i]) + 1;
  129. }
  130. g_main_ctx.envc = i;
  131. char* envp = NULL;
  132. SAFE_ALLOC(envp, g_main_ctx.env_len);
  133. SAFE_ALLOC(g_main_ctx.save_envp, (g_main_ctx.envc + 1) * sizeof(char*));
  134. for (i = 0; environ[i]; ++i) {
  135. g_main_ctx.save_envp[i] = envp;
  136. strcpy(g_main_ctx.save_envp[i], environ[i]);
  137. envp += strlen(environ[i]) + 1;
  138. }
  139. g_main_ctx.save_envp[g_main_ctx.envc] = NULL;
  140. #endif
  141. // signals
  142. g_main_ctx.reload_fn = NULL;
  143. g_main_ctx.reload_userdata = NULL;
  144. // master workers
  145. g_main_ctx.worker_processes = 0;
  146. g_main_ctx.worker_threads = 0;
  147. g_main_ctx.worker_fn = 0;
  148. g_main_ctx.worker_userdata = 0;
  149. g_main_ctx.proc_ctxs = NULL;
  150. atexit(main_ctx_free);
  151. return 0;
  152. }
  153. void main_ctx_free(void) {
  154. if (g_main_ctx.save_argv) {
  155. SAFE_FREE(g_main_ctx.save_argv[0]);
  156. SAFE_FREE(g_main_ctx.save_argv);
  157. }
  158. SAFE_FREE(g_main_ctx.cmdline);
  159. if (g_main_ctx.save_envp) {
  160. SAFE_FREE(g_main_ctx.save_envp[0]);
  161. SAFE_FREE(g_main_ctx.save_envp);
  162. }
  163. if (g_main_ctx.arg_kv) {
  164. for (int i = 0; i < g_main_ctx.arg_kv_size; ++i) {
  165. SAFE_FREE(g_main_ctx.arg_kv[i]);
  166. }
  167. SAFE_FREE(g_main_ctx.arg_kv);
  168. }
  169. if (g_main_ctx.arg_list) {
  170. for (int i = 0; i < g_main_ctx.arg_list_size; ++i) {
  171. SAFE_FREE(g_main_ctx.arg_list[i]);
  172. }
  173. SAFE_FREE(g_main_ctx.arg_list);
  174. }
  175. }
  176. #define UNDEFINED_OPTION -1
  177. static int get_arg_type(int short_opt, const char* options) {
  178. if (options == NULL) return UNDEFINED_OPTION;
  179. const char* p = options;
  180. while (*p && *p != short_opt) ++p;
  181. if (*p == '\0') return UNDEFINED_OPTION;
  182. if (*(p+1) == ':') return REQUIRED_ARGUMENT;
  183. return NO_ARGUMENT;
  184. }
  185. int parse_opt(int argc, char** argv, const char* options) {
  186. if (argc < 1) return 0;
  187. init_arg_kv(strlen(options) + 1);
  188. init_arg_list(argc);
  189. for (int i = 1; argv[i]; ++i) {
  190. char* p = argv[i];
  191. if (*p != '-') {
  192. save_arg_list(argv[i]);
  193. continue;
  194. }
  195. while (*++p) {
  196. int arg_type = get_arg_type(*p, options);
  197. if (arg_type == UNDEFINED_OPTION) {
  198. printf_fn("Invalid option '%c'\n", *p);
  199. return -20;
  200. } else if (arg_type == NO_ARGUMENT) {
  201. save_arg_kv(p, 1, OPTION_ENABLE, 0);
  202. continue;
  203. } else if (arg_type == REQUIRED_ARGUMENT) {
  204. if (*(p+1) != '\0') {
  205. save_arg_kv(p, 1, p+1, 0);
  206. break;
  207. } else if (argv[i+1] != NULL) {
  208. save_arg_kv(p, 1, argv[++i], 0);
  209. break;
  210. } else {
  211. printf_fn("Option '%c' requires param\n", *p);
  212. return -30;
  213. }
  214. }
  215. }
  216. }
  217. return 0;
  218. }
  219. static const option_t* get_option(const char* opt, const option_t* long_options, int size) {
  220. if (opt == NULL || long_options == NULL) return NULL;
  221. int len = strlen(opt);
  222. if (len == 0) return NULL;
  223. if (len == 1) {
  224. for (int i = 0; i < size; ++i) {
  225. if (long_options[i].short_opt == *opt) {
  226. return &long_options[i];
  227. }
  228. }
  229. } else {
  230. for (int i = 0; i < size; ++i) {
  231. if (strcmp(long_options[i].long_opt, opt) == 0) {
  232. return &long_options[i];
  233. }
  234. }
  235. }
  236. return NULL;
  237. }
  238. #define MAX_OPTION 32
  239. // opt type
  240. #define NOPREFIX_OPTION 0
  241. #define SHORT_OPTION -1
  242. #define LONG_OPTION -2
  243. int parse_opt_long(int argc, char** argv, const option_t* long_options, int size) {
  244. if (argc < 1) return 0;
  245. init_arg_kv(size + 1);
  246. init_arg_list(argc);
  247. char opt[MAX_OPTION+1] = {0};
  248. for (int i = 1; argv[i]; ++i) {
  249. char* arg = argv[i];
  250. int opt_type = NOPREFIX_OPTION;
  251. // prefix
  252. if (*arg == OPTION_PREFIX) {
  253. ++arg;
  254. opt_type = SHORT_OPTION;
  255. if (*arg == OPTION_PREFIX) {
  256. ++arg;
  257. opt_type = LONG_OPTION;
  258. }
  259. }
  260. int arg_len = strlen(arg);
  261. // delim
  262. char* delim = strchr(arg, OPTION_DELIM);
  263. if (delim) {
  264. if (delim == arg || delim == arg+arg_len-1 || delim-arg > MAX_OPTION) {
  265. printf_fn("Invalid option '%s'\n", argv[i]);
  266. return -10;
  267. }
  268. memcpy(opt, arg, delim-arg);
  269. opt[delim-arg] = '\0';
  270. } else {
  271. if (opt_type == SHORT_OPTION) {
  272. *opt = *arg;
  273. opt[1] = '\0';
  274. } else {
  275. strncpy(opt, arg, MAX_OPTION);
  276. }
  277. }
  278. // get_option
  279. const option_t* pOption = get_option(opt, long_options, size);
  280. if (pOption == NULL) {
  281. if (delim == NULL && opt_type == NOPREFIX_OPTION) {
  282. save_arg_list(arg);
  283. continue;
  284. } else {
  285. printf_fn("Invalid option: '%s'\n", argv[i]);
  286. return -10;
  287. }
  288. }
  289. const char* value = NULL;
  290. if (pOption->arg_type == NO_ARGUMENT) {
  291. // -h
  292. value = OPTION_ENABLE;
  293. } else {
  294. if (delim) {
  295. // --port=80
  296. value = delim+1;
  297. } else {
  298. if (opt_type == SHORT_OPTION && *(arg+1) != '\0') {
  299. // p80
  300. value = arg+1;
  301. } else if (argv[i+1] != NULL) {
  302. // --port 80
  303. value = argv[++i];
  304. } else if (pOption->arg_type == REQUIRED_ARGUMENT) {
  305. printf_fn("Option '%s' requires parament\n", opt);
  306. return -20;
  307. } else {
  308. // arg_type == OPTIONAL_ARGUMENT
  309. value = OPTION_ENABLE;
  310. }
  311. }
  312. }
  313. // preferred to use short_opt as key
  314. if (pOption->short_opt > 0) {
  315. save_arg_kv(&pOption->short_opt, 1, value, 0);
  316. } else if (pOption->long_opt) {
  317. save_arg_kv(pOption->long_opt, 0, value, 0);
  318. }
  319. }
  320. return 0;
  321. }
  322. int dump_opt_long(const option_t* long_options, int opt_size, char* out_str, int out_size) {
  323. /*
  324. * Usage: program_name [short_options]
  325. * Options:
  326. * -%c|--%s description
  327. * -%c|--%s <value> description
  328. * -%c|--%s [value] description
  329. */
  330. int align = 0, max_align = 0;
  331. char short_options[256] = {0};
  332. char* p = short_options;
  333. for (int i = 0; i < opt_size; ++i) {
  334. if (long_options[i].short_opt > 0) {
  335. *p++ = long_options[i].short_opt;
  336. }
  337. if (long_options[i].arg_type == NO_ARGUMENT) {
  338. // " -%c|--%s "
  339. align = 9 + strlen(long_options[i].long_opt);
  340. } else {
  341. // " -%c|--%s <value> "
  342. align = 17 + strlen(long_options[i].long_opt);
  343. if (long_options[i].short_opt > 0) {
  344. *p++ = ':';
  345. }
  346. }
  347. if (align > max_align) max_align = align;
  348. }
  349. int offset = 0;
  350. if (*g_main_ctx.program_name) {
  351. offset = snprintf(out_str, out_size, "Usage: %s [%s]\n", g_main_ctx.program_name, short_options);
  352. }
  353. offset += snprintf(out_str + offset, out_size - offset, "Options:\n");
  354. char short_opt_chars[4] = {0};
  355. for (int i = 0; i < opt_size; ++i) {
  356. if (long_options[i].short_opt > 0) {
  357. // -%c|
  358. short_opt_chars[0] = '-';
  359. short_opt_chars[1] = long_options[i].short_opt;
  360. short_opt_chars[2] = '|';
  361. } else {
  362. short_opt_chars[0] = ' ';
  363. short_opt_chars[1] = ' ';
  364. short_opt_chars[2] = ' ';
  365. }
  366. if (long_options[i].arg_type == NO_ARGUMENT) {
  367. // " -%c|--%s "
  368. align = 9 + strlen(long_options[i].long_opt);
  369. } else {
  370. // " -%c|--%s <value> "
  371. align = 17 + strlen(long_options[i].long_opt);
  372. }
  373. offset += snprintf(out_str + offset, out_size - offset, " %s--%s%s %*s%s\n",
  374. short_opt_chars,
  375. long_options[i].long_opt,
  376. long_options[i].arg_type == REQUIRED_ARGUMENT ? " <value>" :
  377. long_options[i].arg_type == OPTIONAL_ARGUMENT ? " [value]" : "",
  378. max_align - align, "",
  379. long_options[i].description ? long_options[i].description : "");
  380. }
  381. return offset;
  382. }
  383. #if defined(OS_UNIX) && !HAVE_SETPROCTITLE
  384. /*
  385. * memory layout
  386. * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0
  387. */
  388. void setproctitle(const char* fmt, ...) {
  389. char buf[256] = {0};
  390. va_list ap;
  391. va_start(ap, fmt);
  392. vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
  393. va_end(ap);
  394. int len = g_main_ctx.arg_len + g_main_ctx.env_len;
  395. if (g_main_ctx.os_argv && len) {
  396. strncpy(g_main_ctx.os_argv[0], buf, len-1);
  397. }
  398. }
  399. #endif
  400. int create_pidfile() {
  401. FILE* fp = fopen(g_main_ctx.pidfile, "w");
  402. if (fp == NULL) {
  403. hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno);
  404. return -1;
  405. }
  406. g_main_ctx.pid = hv_getpid();
  407. fprintf(fp, "%d\n", (int)g_main_ctx.pid);
  408. fclose(fp);
  409. hlogi("create_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  410. atexit(delete_pidfile);
  411. return 0;
  412. }
  413. void delete_pidfile(void) {
  414. hlogi("delete_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  415. remove(g_main_ctx.pidfile);
  416. }
  417. pid_t getpid_from_pidfile() {
  418. FILE* fp = fopen(g_main_ctx.pidfile, "r");
  419. if (fp == NULL) {
  420. // hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno);
  421. return -1;
  422. }
  423. int pid = -1;
  424. fscanf(fp, "%d", &pid);
  425. fclose(fp);
  426. return pid;
  427. }
  428. #ifdef OS_UNIX
  429. // unix use signal
  430. #include <sys/wait.h>
  431. void signal_handler(int signo) {
  432. hlogi("pid=%d recv signo=%d", getpid(), signo);
  433. switch (signo) {
  434. case SIGINT:
  435. case SIGNAL_TERMINATE:
  436. hlogi("killall processes");
  437. signal(SIGCHLD, SIG_IGN);
  438. // master send SIGKILL => workers
  439. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  440. if (g_main_ctx.proc_ctxs[i].pid <= 0) break;
  441. kill(g_main_ctx.proc_ctxs[i].pid, SIGKILL);
  442. g_main_ctx.proc_ctxs[i].pid = -1;
  443. }
  444. exit(0);
  445. break;
  446. case SIGCHLD:
  447. {
  448. pid_t pid = 0;
  449. int status = 0;
  450. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  451. hlogw("proc stop/waiting, pid=%d status=%d", pid, status);
  452. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  453. proc_ctx_t* ctx = g_main_ctx.proc_ctxs + i;
  454. if (ctx->pid == pid) {
  455. ctx->pid = -1;
  456. // NOTE: avoid frequent crash and restart
  457. time_t run_time = time(NULL) - ctx->start_time;
  458. if (ctx->spawn_cnt < 3 || run_time > 3600) {
  459. hproc_spawn(ctx);
  460. }
  461. else {
  462. hloge("proc crash, pid=%d spawn_cnt=%d run_time=%us",
  463. pid, ctx->spawn_cnt, (unsigned int)run_time);
  464. bool have_worker = false;
  465. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  466. if (g_main_ctx.proc_ctxs[i].pid > 0) {
  467. have_worker = true;
  468. break;
  469. }
  470. }
  471. if (!have_worker) {
  472. hlogw("No alive worker process, exit master process!");
  473. exit(0);
  474. }
  475. }
  476. break;
  477. }
  478. }
  479. }
  480. }
  481. break;
  482. case SIGNAL_RELOAD:
  483. if (g_main_ctx.reload_fn) {
  484. g_main_ctx.reload_fn(g_main_ctx.reload_userdata);
  485. if (getpid_from_pidfile() == getpid()) {
  486. // master send SIGNAL_RELOAD => workers
  487. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  488. if (g_main_ctx.proc_ctxs[i].pid <= 0) break;
  489. kill(g_main_ctx.proc_ctxs[i].pid, SIGNAL_RELOAD);
  490. }
  491. }
  492. }
  493. break;
  494. default:
  495. break;
  496. }
  497. }
  498. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  499. g_main_ctx.reload_fn = reload_fn;
  500. g_main_ctx.reload_userdata = reload_userdata;
  501. signal(SIGINT, signal_handler);
  502. signal(SIGCHLD, signal_handler);
  503. signal(SIGNAL_TERMINATE, signal_handler);
  504. signal(SIGNAL_RELOAD, signal_handler);
  505. return 0;
  506. }
  507. #elif defined(OS_WIN)
  508. #include <mmsystem.h> // for timeSetEvent
  509. // win32 use Event
  510. static HANDLE s_hEventTerm = NULL;
  511. static HANDLE s_hEventTermWait = NULL;
  512. static HANDLE s_hEventReload = NULL;
  513. static void WINAPI on_timer(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) {
  514. DWORD ret;
  515. ret = WaitForSingleObject(s_hEventTerm, 0);
  516. if (ret == WAIT_OBJECT_0) {
  517. hlogi("pid=%d recv event [TERM]", getpid());
  518. if (getpid_from_pidfile() == getpid()) {
  519. SetEvent(s_hEventTermWait);
  520. timeKillEvent(uTimerID);
  521. exit(0);
  522. }
  523. }
  524. ret = WaitForSingleObject(s_hEventReload, 0);
  525. if (ret == WAIT_OBJECT_0) {
  526. hlogi("pid=%d recv event [RELOAD]", getpid());
  527. if (g_main_ctx.reload_fn) {
  528. g_main_ctx.reload_fn(g_main_ctx.reload_userdata);
  529. }
  530. }
  531. }
  532. static void signal_cleanup(void) {
  533. CloseHandle(s_hEventTerm);
  534. s_hEventTerm = NULL;
  535. CloseHandle(s_hEventTermWait);
  536. s_hEventTermWait = NULL;
  537. CloseHandle(s_hEventReload);
  538. s_hEventReload = NULL;
  539. }
  540. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  541. g_main_ctx.reload_fn = reload_fn;
  542. g_main_ctx.reload_userdata = reload_userdata;
  543. char eventname[MAX_PATH] = {0};
  544. snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  545. s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  546. if(s_hEventTerm == NULL) return -1;
  547. snprintf(eventname, sizeof(eventname), "%s_term_wait_event", g_main_ctx.program_name);
  548. s_hEventTermWait = CreateEvent(NULL, FALSE, FALSE, eventname);
  549. if(s_hEventTermWait == NULL) return -2;
  550. snprintf(eventname, sizeof(eventname), "%s_reload_event", g_main_ctx.program_name);
  551. s_hEventReload = CreateEvent(NULL, FALSE, FALSE, eventname);
  552. if(s_hEventReload == NULL) return -3;
  553. timeSetEvent(1000, 1000, on_timer, 0, TIME_PERIODIC);
  554. atexit(signal_cleanup);
  555. return 0;
  556. }
  557. #endif
  558. static void kill_proc(int pid) {
  559. #ifdef OS_UNIX
  560. kill(pid, SIGNAL_TERMINATE);
  561. #else
  562. SetEvent(s_hEventTerm);
  563. if (WaitForSingleObject(s_hEventTermWait, 2000) == WAIT_OBJECT_0) return;
  564. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
  565. if (hproc) {
  566. TerminateProcess(hproc, 0);
  567. CloseHandle(hproc);
  568. }
  569. #endif
  570. }
  571. void signal_handle(const char* signal) {
  572. if (signal_handle_noexit(signal)) exit(0);
  573. }
  574. bool signal_handle_noexit(const char* signal) {
  575. if (strcmp(signal, "start") == 0) {
  576. if (g_main_ctx.oldpid > 0) {
  577. printf_fn("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  578. return true;
  579. }
  580. } else if (strcmp(signal, "stop") == 0) {
  581. if (g_main_ctx.oldpid > 0) {
  582. kill_proc(g_main_ctx.oldpid);
  583. printf_fn("%s stop/waiting\n", g_main_ctx.program_name);
  584. } else {
  585. printf_fn("%s is already stopped\n", g_main_ctx.program_name);
  586. }
  587. return true;
  588. } else if (strcmp(signal, "restart") == 0) {
  589. if (g_main_ctx.oldpid > 0) {
  590. kill_proc(g_main_ctx.oldpid);
  591. printf_fn("%s stop/waiting\n", g_main_ctx.program_name);
  592. hv_sleep(1);
  593. }
  594. } else if (strcmp(signal, "status") == 0) {
  595. if (g_main_ctx.oldpid > 0) {
  596. printf_fn("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  597. } else {
  598. printf_fn("%s is already stopped\n", g_main_ctx.program_name);
  599. }
  600. return true;
  601. } else if (strcmp(signal, "reload") == 0) {
  602. if (g_main_ctx.oldpid > 0) {
  603. printf_fn("reload confile [%s]\n", g_main_ctx.confile);
  604. #ifdef OS_UNIX
  605. kill(g_main_ctx.oldpid, SIGNAL_RELOAD);
  606. #else
  607. SetEvent(s_hEventReload);
  608. #endif
  609. hv_sleep(1);
  610. } else {
  611. printf_fn("%s is already stopped\n", g_main_ctx.program_name);
  612. }
  613. return true;
  614. } else {
  615. printf_fn("Invalid signal: '%s'\n", signal);
  616. return true;
  617. }
  618. printf_fn("%s start/running\n", g_main_ctx.program_name);
  619. return false;
  620. }
  621. // master-workers processes
  622. static HTHREAD_ROUTINE(worker_thread) {
  623. hlogi("worker_thread pid=%ld tid=%ld", hv_getpid(), hv_gettid());
  624. if (g_main_ctx.worker_fn) {
  625. g_main_ctx.worker_fn(g_main_ctx.worker_userdata);
  626. }
  627. return 0;
  628. }
  629. static void worker_init(void* userdata) {
  630. #ifdef OS_UNIX
  631. setproctitle("%s: worker process", g_main_ctx.program_name);
  632. signal(SIGNAL_RELOAD, signal_handler);
  633. #endif
  634. }
  635. static void worker_proc(void* userdata) {
  636. for (int i = 1; i < g_main_ctx.worker_threads; ++i) {
  637. hthread_create(worker_thread, NULL);
  638. }
  639. worker_thread(NULL);
  640. }
  641. int master_workers_run(procedure_t worker_fn, void* worker_userdata,
  642. int worker_processes, int worker_threads, bool wait) {
  643. #ifdef OS_WIN
  644. // NOTE: Windows not provide MultiProcesses
  645. if (worker_threads == 0) {
  646. // MultiProcesses => MultiThreads
  647. worker_threads = worker_processes;
  648. }
  649. worker_processes = 0;
  650. #endif
  651. if (worker_threads == 0) worker_threads = 1;
  652. g_main_ctx.worker_threads = worker_threads;
  653. g_main_ctx.worker_fn = worker_fn;
  654. g_main_ctx.worker_userdata = worker_userdata;
  655. if (worker_processes == 0) {
  656. // single process
  657. if (wait) {
  658. for (int i = 1; i < worker_threads; ++i) {
  659. hthread_create(worker_thread, NULL);
  660. }
  661. worker_thread(NULL);
  662. }
  663. else {
  664. for (int i = 0; i < worker_threads; ++i) {
  665. hthread_create(worker_thread, NULL);
  666. }
  667. }
  668. }
  669. else {
  670. if (g_main_ctx.worker_processes != 0) {
  671. return ERR_OVER_LIMIT;
  672. }
  673. // master-workers processes
  674. #ifdef OS_UNIX
  675. setproctitle("%s: master process", g_main_ctx.program_name);
  676. signal(SIGNAL_RELOAD, signal_handler);
  677. #endif
  678. g_main_ctx.worker_processes = worker_processes;
  679. int bytes = g_main_ctx.worker_processes * sizeof(proc_ctx_t);
  680. SAFE_ALLOC(g_main_ctx.proc_ctxs, bytes);
  681. proc_ctx_t* ctx = g_main_ctx.proc_ctxs;
  682. for (int i = 0; i < g_main_ctx.worker_processes; ++i, ++ctx) {
  683. ctx->init = worker_init;
  684. ctx->proc = worker_proc;
  685. hproc_spawn(ctx);
  686. hlogi("workers[%d] start/running, pid=%d", i, ctx->pid);
  687. }
  688. g_main_ctx.pid = getpid();
  689. hlogi("master start/running, pid=%d", g_main_ctx.pid);
  690. if (wait) {
  691. while (1) hv_sleep (1);
  692. }
  693. }
  694. return 0;
  695. }