hmain.cpp 15 KB

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