1
0

hmain.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 if (pOption->arg_type == REQUIRED_ARGUMENT) {
  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 {
  304. printf("Option '%s' requires parament\n", opt);
  305. return -20;
  306. }
  307. }
  308. }
  309. // preferred to use short_opt as key
  310. if (pOption->short_opt > 0) {
  311. save_arg_kv(&pOption->short_opt, 1, value, 0);
  312. } else if (pOption->long_opt) {
  313. save_arg_kv(pOption->long_opt, 0, value, 0);
  314. }
  315. }
  316. return 0;
  317. }
  318. int dump_opt_long(const option_t* long_options, int opt_size, char* out_str, int out_size) {
  319. /*
  320. * Usage: program_name [short_options]
  321. * Options:
  322. * -%c|--%s description
  323. * -%c|--%s <value> description
  324. * -%c|--%s [value] description
  325. */
  326. int align = 0, max_align = 0;
  327. char short_options[256] = {0};
  328. char* p = short_options;
  329. for (int i = 0; i < opt_size; ++i) {
  330. if (long_options[i].short_opt > 0) {
  331. *p++ = long_options[i].short_opt;
  332. }
  333. if (long_options[i].arg_type == NO_ARGUMENT) {
  334. // " -%c|--%s "
  335. align = 9 + strlen(long_options[i].long_opt);
  336. } else {
  337. // " -%c|--%s <value> "
  338. align = 17 + strlen(long_options[i].long_opt);
  339. if (long_options[i].short_opt > 0) {
  340. *p++ = ':';
  341. }
  342. }
  343. if (align > max_align) max_align = align;
  344. }
  345. int offset = 0;
  346. if (*g_main_ctx.program_name) {
  347. offset = snprintf(out_str, out_size, "Usage: %s [%s]\n", g_main_ctx.program_name, short_options);
  348. }
  349. offset += snprintf(out_str + offset, out_size - offset, "Options:\n");
  350. char short_opt_chars[4] = {0};
  351. for (int i = 0; i < opt_size; ++i) {
  352. if (long_options[i].short_opt > 0) {
  353. // -%c|
  354. short_opt_chars[0] = '-';
  355. short_opt_chars[1] = long_options[i].short_opt;
  356. short_opt_chars[2] = '|';
  357. } else {
  358. short_opt_chars[0] = ' ';
  359. short_opt_chars[1] = ' ';
  360. short_opt_chars[2] = ' ';
  361. }
  362. if (long_options[i].arg_type == NO_ARGUMENT) {
  363. // " -%c|--%s "
  364. align = 9 + strlen(long_options[i].long_opt);
  365. } else {
  366. // " -%c|--%s <value> "
  367. align = 17 + strlen(long_options[i].long_opt);
  368. }
  369. offset += snprintf(out_str + offset, out_size - offset, " %s--%s%s %*s%s\n",
  370. short_opt_chars,
  371. long_options[i].long_opt,
  372. long_options[i].arg_type == REQUIRED_ARGUMENT ? " <value>" :
  373. long_options[i].arg_type == OPTIONAL_ARGUMENT ? " [value]" : "",
  374. max_align - align, "",
  375. long_options[i].description ? long_options[i].description : "");
  376. }
  377. return offset;
  378. }
  379. #if defined(OS_UNIX) && !HAVE_SETPROCTITLE
  380. /*
  381. * memory layout
  382. * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0
  383. */
  384. void setproctitle(const char* fmt, ...) {
  385. char buf[256] = {0};
  386. va_list ap;
  387. va_start(ap, fmt);
  388. vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
  389. va_end(ap);
  390. int len = g_main_ctx.arg_len + g_main_ctx.env_len;
  391. if (g_main_ctx.os_argv && len) {
  392. strncpy(g_main_ctx.os_argv[0], buf, len-1);
  393. }
  394. }
  395. #endif
  396. int create_pidfile() {
  397. FILE* fp = fopen(g_main_ctx.pidfile, "w");
  398. if (fp == NULL) {
  399. hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno);
  400. return -1;
  401. }
  402. g_main_ctx.pid = hv_getpid();
  403. fprintf(fp, "%d\n", (int)g_main_ctx.pid);
  404. fclose(fp);
  405. hlogi("create_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  406. atexit(delete_pidfile);
  407. return 0;
  408. }
  409. void delete_pidfile(void) {
  410. hlogi("delete_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  411. remove(g_main_ctx.pidfile);
  412. }
  413. pid_t getpid_from_pidfile() {
  414. FILE* fp = fopen(g_main_ctx.pidfile, "r");
  415. if (fp == NULL) {
  416. // hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno);
  417. return -1;
  418. }
  419. int pid = -1;
  420. fscanf(fp, "%d", &pid);
  421. fclose(fp);
  422. return pid;
  423. }
  424. #ifdef OS_UNIX
  425. // unix use signal
  426. #include <sys/wait.h>
  427. void signal_handler(int signo) {
  428. hlogi("pid=%d recv signo=%d", getpid(), signo);
  429. switch (signo) {
  430. case SIGINT:
  431. case SIGNAL_TERMINATE:
  432. hlogi("killall processes");
  433. signal(SIGCHLD, SIG_IGN);
  434. // master send SIGKILL => workers
  435. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  436. if (g_main_ctx.proc_ctxs[i].pid <= 0) break;
  437. kill(g_main_ctx.proc_ctxs[i].pid, SIGKILL);
  438. g_main_ctx.proc_ctxs[i].pid = -1;
  439. }
  440. exit(0);
  441. break;
  442. case SIGCHLD:
  443. {
  444. pid_t pid = 0;
  445. int status = 0;
  446. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  447. hlogw("proc stop/waiting, pid=%d status=%d", pid, status);
  448. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  449. proc_ctx_t* ctx = g_main_ctx.proc_ctxs + i;
  450. if (ctx->pid == pid) {
  451. ctx->pid = -1;
  452. // NOTE: avoid frequent crash and restart
  453. time_t run_time = time(NULL) - ctx->start_time;
  454. if (ctx->spawn_cnt < 3 || run_time > 3600) {
  455. hproc_spawn(ctx);
  456. }
  457. else {
  458. hloge("proc crash, pid=%d spawn_cnt=%d run_time=%us",
  459. pid, ctx->spawn_cnt, (unsigned int)run_time);
  460. bool have_worker = false;
  461. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  462. if (g_main_ctx.proc_ctxs[i].pid > 0) {
  463. have_worker = true;
  464. break;
  465. }
  466. }
  467. if (!have_worker) {
  468. hlogw("No alive worker process, exit master process!");
  469. exit(0);
  470. }
  471. }
  472. break;
  473. }
  474. }
  475. }
  476. }
  477. break;
  478. case SIGNAL_RELOAD:
  479. if (g_main_ctx.reload_fn) {
  480. g_main_ctx.reload_fn(g_main_ctx.reload_userdata);
  481. if (getpid_from_pidfile() == getpid()) {
  482. // master send SIGNAL_RELOAD => workers
  483. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  484. if (g_main_ctx.proc_ctxs[i].pid <= 0) break;
  485. kill(g_main_ctx.proc_ctxs[i].pid, SIGNAL_RELOAD);
  486. }
  487. }
  488. }
  489. break;
  490. default:
  491. break;
  492. }
  493. }
  494. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  495. g_main_ctx.reload_fn = reload_fn;
  496. g_main_ctx.reload_userdata = reload_userdata;
  497. signal(SIGINT, signal_handler);
  498. signal(SIGCHLD, signal_handler);
  499. signal(SIGNAL_TERMINATE, signal_handler);
  500. signal(SIGNAL_RELOAD, signal_handler);
  501. return 0;
  502. }
  503. #elif defined(OS_WIN)
  504. #include <mmsystem.h> // for timeSetEvent
  505. // win32 use Event
  506. //static HANDLE s_hEventTerm = NULL;
  507. static HANDLE s_hEventReload = NULL;
  508. static void WINAPI on_timer(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) {
  509. DWORD ret;
  510. /*
  511. ret = WaitForSingleObject(s_hEventTerm, 0);
  512. if (ret == WAIT_OBJECT_0) {
  513. hlogi("pid=%d recv event [TERM]", getpid());
  514. if (getpid_from_pidfile() == getpid()) {
  515. timeKillEvent(uTimerID);
  516. exit(0);
  517. }
  518. }
  519. */
  520. ret = WaitForSingleObject(s_hEventReload, 0);
  521. if (ret == WAIT_OBJECT_0) {
  522. hlogi("pid=%d recv event [RELOAD]", getpid());
  523. if (g_main_ctx.reload_fn) {
  524. g_main_ctx.reload_fn(g_main_ctx.reload_userdata);
  525. }
  526. }
  527. }
  528. static void signal_cleanup(void) {
  529. //CloseHandle(s_hEventTerm);
  530. //s_hEventTerm = NULL;
  531. CloseHandle(s_hEventReload);
  532. s_hEventReload = NULL;
  533. }
  534. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  535. g_main_ctx.reload_fn = reload_fn;
  536. g_main_ctx.reload_userdata = reload_userdata;
  537. char eventname[MAX_PATH] = {0};
  538. //snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  539. //s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  540. //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname);
  541. snprintf(eventname, sizeof(eventname), "%s_reload_event", g_main_ctx.program_name);
  542. s_hEventReload = CreateEvent(NULL, FALSE, FALSE, eventname);
  543. timeSetEvent(1000, 1000, on_timer, 0, TIME_PERIODIC);
  544. atexit(signal_cleanup);
  545. return 0;
  546. }
  547. #endif
  548. static void kill_proc(int pid) {
  549. #ifdef OS_UNIX
  550. kill(pid, SIGNAL_TERMINATE);
  551. #else
  552. //SetEvent(s_hEventTerm);
  553. //hv_sleep(1);
  554. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
  555. if (hproc) {
  556. TerminateProcess(hproc, 0);
  557. CloseHandle(hproc);
  558. }
  559. #endif
  560. }
  561. void signal_handle(const char* signal) {
  562. if (strcmp(signal, "start") == 0) {
  563. if (g_main_ctx.oldpid > 0) {
  564. printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  565. exit(0);
  566. }
  567. } else if (strcmp(signal, "stop") == 0) {
  568. if (g_main_ctx.oldpid > 0) {
  569. kill_proc(g_main_ctx.oldpid);
  570. printf("%s stop/waiting\n", g_main_ctx.program_name);
  571. } else {
  572. printf("%s is already stopped\n", g_main_ctx.program_name);
  573. }
  574. exit(0);
  575. } else if (strcmp(signal, "restart") == 0) {
  576. if (g_main_ctx.oldpid > 0) {
  577. kill_proc(g_main_ctx.oldpid);
  578. printf("%s stop/waiting\n", g_main_ctx.program_name);
  579. hv_sleep(1);
  580. }
  581. } else if (strcmp(signal, "status") == 0) {
  582. if (g_main_ctx.oldpid > 0) {
  583. printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  584. } else {
  585. printf("%s stop/waiting\n", g_main_ctx.program_name);
  586. }
  587. exit(0);
  588. } else if (strcmp(signal, "reload") == 0) {
  589. if (g_main_ctx.oldpid > 0) {
  590. printf("reload confile [%s]\n", g_main_ctx.confile);
  591. #ifdef OS_UNIX
  592. kill(g_main_ctx.oldpid, SIGNAL_RELOAD);
  593. #else
  594. SetEvent(s_hEventReload);
  595. #endif
  596. }
  597. hv_sleep(1);
  598. exit(0);
  599. } else {
  600. printf("Invalid signal: '%s'\n", signal);
  601. exit(0);
  602. }
  603. printf("%s start/running\n", g_main_ctx.program_name);
  604. }
  605. // master-workers processes
  606. static HTHREAD_ROUTINE(worker_thread) {
  607. hlogi("worker_thread pid=%ld tid=%ld", hv_getpid(), hv_gettid());
  608. if (g_main_ctx.worker_fn) {
  609. g_main_ctx.worker_fn(g_main_ctx.worker_userdata);
  610. }
  611. return 0;
  612. }
  613. static void worker_init(void* userdata) {
  614. #ifdef OS_UNIX
  615. setproctitle("%s: worker process", g_main_ctx.program_name);
  616. signal(SIGNAL_RELOAD, signal_handler);
  617. #endif
  618. }
  619. static void worker_proc(void* userdata) {
  620. for (int i = 1; i < g_main_ctx.worker_threads; ++i) {
  621. hthread_create(worker_thread, NULL);
  622. }
  623. worker_thread(NULL);
  624. }
  625. int master_workers_run(procedure_t worker_fn, void* worker_userdata,
  626. int worker_processes, int worker_threads, bool wait) {
  627. #ifdef OS_WIN
  628. // NOTE: Windows not provide MultiProcesses
  629. if (worker_threads == 0) {
  630. // MultiProcesses => MultiThreads
  631. worker_threads = worker_processes;
  632. }
  633. worker_processes = 0;
  634. #endif
  635. if (worker_threads == 0) worker_threads = 1;
  636. g_main_ctx.worker_threads = worker_threads;
  637. g_main_ctx.worker_fn = worker_fn;
  638. g_main_ctx.worker_userdata = worker_userdata;
  639. if (worker_processes == 0) {
  640. // single process
  641. if (wait) {
  642. for (int i = 1; i < worker_threads; ++i) {
  643. hthread_create(worker_thread, NULL);
  644. }
  645. worker_thread(NULL);
  646. }
  647. else {
  648. for (int i = 0; i < worker_threads; ++i) {
  649. hthread_create(worker_thread, NULL);
  650. }
  651. }
  652. }
  653. else {
  654. if (g_main_ctx.worker_processes != 0) {
  655. return ERR_OVER_LIMIT;
  656. }
  657. // master-workers processes
  658. #ifdef OS_UNIX
  659. setproctitle("%s: master process", g_main_ctx.program_name);
  660. signal(SIGNAL_RELOAD, signal_handler);
  661. #endif
  662. g_main_ctx.worker_processes = worker_processes;
  663. int bytes = g_main_ctx.worker_processes * sizeof(proc_ctx_t);
  664. SAFE_ALLOC(g_main_ctx.proc_ctxs, bytes);
  665. proc_ctx_t* ctx = g_main_ctx.proc_ctxs;
  666. for (int i = 0; i < g_main_ctx.worker_processes; ++i, ++ctx) {
  667. ctx->init = worker_init;
  668. ctx->proc = worker_proc;
  669. hproc_spawn(ctx);
  670. hlogi("workers[%d] start/running, pid=%d", i, ctx->pid);
  671. }
  672. g_main_ctx.pid = getpid();
  673. hlogi("master start/running, pid=%d", g_main_ctx.pid);
  674. if (wait) {
  675. while (1) hv_sleep (1);
  676. }
  677. }
  678. return 0;
  679. }