hmain.cpp 15 KB

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