hmain.c 23 KB

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