hmain.cpp.tmpl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. #include <signal.h> // for signal,kill...
  2. #include "h.h"
  3. #include "hsysinfo.h"
  4. #include "hmain.h"
  5. main_ctx_t g_main_ctx;
  6. static int create_pidfile();
  7. static void delete_pidfile();
  8. static pid_t getpid_from_pidfile();
  9. int create_pidfile() {
  10. FILE* fp = fopen(g_main_ctx.pidfile, "w");
  11. if (fp == NULL) {
  12. printf("fopen [%s] error: %d\n", g_main_ctx.pidfile, errno);
  13. return -10;
  14. }
  15. char pid[16] = {0};
  16. snprintf(pid, sizeof(pid), "%d\n", g_main_ctx.pid);
  17. fwrite(pid, 1, strlen(pid), fp);
  18. fclose(fp); atexit(delete_pidfile);
  19. hlogd("create_pidfile [%s] pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  20. return 0;
  21. }
  22. void delete_pidfile() {
  23. remove(g_main_ctx.pidfile);
  24. hlogd("delete_pidfile [%s]", g_main_ctx.pidfile);
  25. }
  26. pid_t getpid_from_pidfile() {
  27. FILE* fp = fopen(g_main_ctx.pidfile, "r");
  28. if (fp == NULL) {
  29. //printf("fopen [%s] error: %d\n", g_conf_ctx.pidfile, errno);
  30. return -1;
  31. }
  32. char pid[64];
  33. int readbytes = fread(pid, 1, sizeof(pid), fp);
  34. fclose(fp);
  35. if (readbytes <= 0) {
  36. printf("fread [%s] bytes=%d\n", g_main_ctx.pidfile, readbytes);
  37. return -1;
  38. }
  39. return atoi(pid);
  40. }
  41. int main_ctx_init(int argc, char** argv) {
  42. g_main_ctx.pid = getpid();
  43. char* cwd = getcwd(g_main_ctx.run_path, sizeof(g_main_ctx.run_path));
  44. if (cwd == NULL) {
  45. printf("getcwd error\n");
  46. }
  47. //printf("run_path=%s\n", g_main_ctx.run_path);
  48. const char* b = argv[0];
  49. const char* e = b;
  50. while (*e) ++e;
  51. --e;
  52. while (e >= b) {
  53. if (*e == '/' || *e == '\\') {
  54. break;
  55. }
  56. --e;
  57. }
  58. strncpy(g_main_ctx.program_name, e+1, sizeof(g_main_ctx.program_name));
  59. #ifdef _WIN32
  60. if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) {
  61. *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0';
  62. }
  63. #endif
  64. //printf("program_name=%s\n", g_main_ctx.program_name);
  65. // save arg
  66. int i = 0;
  67. g_main_ctx.os_argv = argv;
  68. g_main_ctx.argc = 0;
  69. g_main_ctx.arg_len = 0;
  70. for (i = 0; argv[i]; ++i) {
  71. g_main_ctx.arg_len += strlen(argv[i]) + 1;
  72. }
  73. g_main_ctx.argc = i;
  74. char* argp = (char*)malloc(g_main_ctx.arg_len);
  75. memset(argp, 0, g_main_ctx.arg_len);
  76. g_main_ctx.save_argv = (char**)malloc((g_main_ctx.argc+1) * sizeof(char*));
  77. for (i = 0; argv[i]; ++i) {
  78. g_main_ctx.save_argv[i] = argp;
  79. strcpy(g_main_ctx.save_argv[i], argv[i]);
  80. argp += strlen(argv[i]) + 1;
  81. }
  82. g_main_ctx.save_argv[g_main_ctx.argc] = NULL;
  83. // save env
  84. g_main_ctx.os_envp = environ;
  85. g_main_ctx.envc = 0;
  86. g_main_ctx.env_len = 0;
  87. for (i = 0; environ[i]; ++i) {
  88. g_main_ctx.env_len += strlen(environ[i]) + 1;
  89. }
  90. g_main_ctx.envc = i;
  91. char* envp = (char*)malloc(g_main_ctx.env_len);
  92. memset(envp, 0, g_main_ctx.env_len);
  93. g_main_ctx.save_envp = (char**)malloc((g_main_ctx.envc+1) * sizeof(char*));
  94. for (i = 0; environ[i]; ++i) {
  95. g_main_ctx.save_envp[i] = envp;
  96. strcpy(g_main_ctx.save_envp[i], environ[i]);
  97. envp += strlen(environ[i]) + 1;
  98. }
  99. g_main_ctx.save_envp[g_main_ctx.envc] = NULL;
  100. // parse env
  101. for (i = 0; environ[i]; ++i) {
  102. char* b = environ[i];
  103. char* delim = strchr(b, '=');
  104. if (delim == NULL) {
  105. continue;
  106. }
  107. g_main_ctx.env_kv[std::string(b, delim-b)] = std::string(delim+1);
  108. }
  109. /*
  110. // print argv and envp
  111. printf("---------------arg------------------------------\n");
  112. for (auto& pair : g_main_ctx.arg_kv) {
  113. printf("%s=%s\n", pair.first.c_str(), pair.second.c_str());
  114. }
  115. printf("---------------env------------------------------\n");
  116. for (auto& pair : g_main_ctx.env_kv) {
  117. printf("%s=%s\n", pair.first.c_str(), pair.second.c_str());
  118. }
  119. printf("PWD=%s\n", get_env("PWD"));
  120. printf("USER=%s\n", get_env("USER"));
  121. printf("HOME=%s\n", get_env("HOME"));
  122. printf("LANG=%s\n", get_env("LANG"));
  123. printf("TERM=%s\n", get_env("TERM"));
  124. printf("SHELL=%s\n", get_env("SHELL"));
  125. printf("================================================\n");
  126. */
  127. char logpath[MAX_PATH] = {0};
  128. snprintf(logpath, sizeof(logpath), "%s/logs", g_main_ctx.run_path);
  129. MKDIR(logpath);
  130. snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_path, g_main_ctx.program_name);
  131. snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_path, g_main_ctx.program_name);
  132. snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.confile), "%s/logs/%s.log", g_main_ctx.run_path, g_main_ctx.program_name);
  133. g_main_ctx.confile_parser = NULL;
  134. g_main_ctx.oldpid = getpid_from_pidfile();
  135. #ifdef __unix__
  136. if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) {
  137. g_main_ctx.oldpid = -1;
  138. }
  139. #else
  140. #endif
  141. return 0;
  142. }
  143. const char* get_arg(const char* key) {
  144. auto iter = g_main_ctx.arg_kv.find(key);
  145. if (iter == g_main_ctx.arg_kv.end()) {
  146. return NULL;
  147. }
  148. return iter->second.c_str();
  149. }
  150. const char* get_env(const char* key) {
  151. auto iter = g_main_ctx.env_kv.find(key);
  152. if (iter == g_main_ctx.env_kv.end()) {
  153. return NULL;
  154. }
  155. return iter->second.c_str();
  156. }
  157. #ifdef __unix__
  158. /*
  159. * memory layout
  160. * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0
  161. */
  162. void setproctitle(const char* title) {
  163. //printf("proctitle=%s\n", title);
  164. memset(g_main_ctx.os_argv[0], 0, g_main_ctx.arg_len + g_main_ctx.env_len);
  165. strncpy(g_main_ctx.os_argv[0], title, g_main_ctx.arg_len + g_main_ctx.env_len);
  166. }
  167. #endif
  168. // unix short style
  169. static char options[] = "hvc:ts:d";
  170. static char detail_options[] = "\
  171. -h : print help\n\
  172. -v : print version\n\
  173. -c confile : set configure file, default etc/${program}.conf\n\
  174. -t : test configure file and exit\n\
  175. -s signal : send signal to process\n\
  176. signal=[start, stop, restart, status]\n\
  177. -d : daemon\n\
  178. ";
  179. void print_version() {
  180. printf("%s version %s\n", g_main_ctx.program_name, get_compile_version());
  181. }
  182. void print_help() {
  183. printf("Usage: %s [%s]\n", g_main_ctx.program_name, options);
  184. printf("Options:\n%s\n", detail_options);
  185. }
  186. #define INVALID_OPTION -1
  187. #define FLAG_OPTION 1
  188. #define PARMA_OPTION 2
  189. int get_option(char opt) {
  190. char* p = options;
  191. while (*p && *p != opt) ++p;
  192. if (*p == '\0') return INVALID_OPTION;
  193. if (*(p+1) == ':') return PARMA_OPTION;
  194. return FLAG_OPTION;
  195. }
  196. int parse_cmdline(int argc, char** argv) {
  197. int i = 1;
  198. while (argv[i]) {
  199. char* p = argv[i];
  200. if (*p != '-') {
  201. printf("Invalid argv[%d]: %s\n", i, argv[i]);
  202. exit(-10);
  203. }
  204. while (*++p) {
  205. switch (get_option(*p)) {
  206. case INVALID_OPTION:
  207. printf("Invalid option: '%c'\n", *p);
  208. exit(-20);
  209. case FLAG_OPTION:
  210. g_main_ctx.arg_kv[std::string(p, 1)] = "true";
  211. break;
  212. case PARMA_OPTION:
  213. if (*(p+1) != '\0') {
  214. g_main_ctx.arg_kv[std::string(p, 1)] = p+1;
  215. ++i;
  216. goto next_option;
  217. } else if (argv[i+1] != NULL) {
  218. g_main_ctx.arg_kv[std::string(p, 1)] = argv[i+1];
  219. i += 2;
  220. goto next_option;
  221. } else {
  222. printf("Option '%c' requires param\n", *p);
  223. exit(-30);
  224. }
  225. }
  226. }
  227. ++i;
  228. next_option:
  229. continue;
  230. }
  231. return 0;
  232. }
  233. #ifdef __unix__
  234. // unix use signal
  235. // we use SIGTERM to quit process
  236. #define SIGNAL_TERMINATE SIGTERM
  237. #include <sys/wait.h>
  238. #define MAXNUM_WORKER_PROCESSES 1024
  239. #define DEFAULT_WORKER_PROCESSES 4
  240. static pid_t s_worker_processes[MAXNUM_WORKER_PROCESSES];
  241. void worker_process_cycle() {
  242. char proctitle[256] = {0};
  243. snprintf(proctitle, sizeof(proctitle), "%s: worker process", g_main_ctx.program_name);
  244. setproctitle(proctitle);
  245. while(1) {
  246. msleep(1);
  247. }
  248. }
  249. int create_worker_process(int worker_processes) {
  250. for (int i = 0; i < worker_processes; ++i) {
  251. pid_t pid = fork();
  252. if (pid < 0) {
  253. hloge("fork error: %d", errno);
  254. return errno;
  255. }
  256. if (pid == 0) {
  257. hlogi("worker process start/running, pid=%d", getpid());
  258. worker_process_cycle();
  259. exit(0);
  260. }
  261. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  262. if (s_worker_processes[i] <= 0) {
  263. s_worker_processes[i] = pid;
  264. break;
  265. }
  266. }
  267. }
  268. return 0;
  269. }
  270. static int s_signo = 0;
  271. void master_process_signal_handler(int signo) {
  272. hlogd("pid=%d recv signo=%d", getpid(), signo);
  273. s_signo = signo;
  274. }
  275. void master_process_init() {
  276. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  277. s_worker_processes[i] = -1;
  278. }
  279. }
  280. void master_process_cycle() {
  281. char proctitle[256] = {0};
  282. snprintf(proctitle, sizeof(proctitle), "%s: master process", g_main_ctx.program_name);
  283. setproctitle(proctitle);
  284. signal(SIGINT, master_process_signal_handler);
  285. signal(SIGCHLD, master_process_signal_handler);
  286. signal(SIGNAL_TERMINATE, master_process_signal_handler);
  287. sigset_t sigset;
  288. sigemptyset(&sigset);
  289. sigaddset(&sigset, SIGINT);
  290. sigaddset(&sigset, SIGCHLD);
  291. sigaddset(&sigset, SIGNAL_TERMINATE);
  292. sigprocmask(SIG_BLOCK, &sigset, NULL);
  293. int worker_processes = 0;
  294. IniParser* ini = (IniParser*)g_main_ctx.confile_parser;
  295. if (ini) {
  296. worker_processes = atoi(ini->GetValue("worker_processes", "core").c_str());
  297. hlogd("core.worker_processes=%d", worker_processes);
  298. }
  299. if (worker_processes <= 0 || worker_processes > MAXNUM_WORKER_PROCESSES) {
  300. worker_processes = get_ncpu();
  301. hlogd("worker_processes=ncpu=%d", worker_processes);
  302. }
  303. if (worker_processes <= 0 || worker_processes > MAXNUM_WORKER_PROCESSES) {
  304. worker_processes = DEFAULT_WORKER_PROCESSES;
  305. }
  306. create_worker_process(worker_processes);
  307. sigemptyset(&sigset);
  308. while (1) {
  309. sigsuspend(&sigset);
  310. switch (s_signo) {
  311. case SIGINT:
  312. case SIGNAL_TERMINATE:
  313. hlogi("killall worker processes");
  314. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  315. if (s_worker_processes[i] <= 0) break;
  316. kill(s_worker_processes[i], SIGKILL);
  317. s_worker_processes[i] = -1;
  318. }
  319. msleep(1000);
  320. exit(0);
  321. break;
  322. case SIGCHLD:
  323. {
  324. pid_t pid = 0;
  325. int status = 0;
  326. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  327. hlogw("worker process stop/waiting, pid=%d status=%d", pid, status);
  328. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  329. if (s_worker_processes[i] == pid) {
  330. s_worker_processes[i] = -1;
  331. break;
  332. }
  333. }
  334. create_worker_process(1);
  335. }
  336. }
  337. break;
  338. default:
  339. break;
  340. }
  341. }
  342. }
  343. #else
  344. // win32 use Event
  345. static HANDLE s_hEventTerm = NULL;
  346. void master_process_exit() {
  347. CloseHandle(s_hEventTerm);
  348. s_hEventTerm = NULL;
  349. }
  350. void master_process_init() {
  351. char eventname[MAX_PATH] = {0};
  352. snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  353. s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  354. //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname);
  355. atexit(master_process_exit);
  356. }
  357. void master_process_cycle() {
  358. while (1) {
  359. DWORD ret = WaitForSingleObject(s_hEventTerm, INFINITE);
  360. exit(0);
  361. }
  362. }
  363. #endif
  364. int main(int argc, char** argv) {
  365. main_ctx_init(argc, argv);
  366. parse_cmdline(argc, argv);
  367. master_process_init();
  368. if (get_arg("h")) {
  369. print_help();
  370. exit(0);
  371. }
  372. if (get_arg("v")) {
  373. print_version();
  374. exit(0);
  375. }
  376. const char* confile = get_arg("c");
  377. if (confile) {
  378. strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile));
  379. }
  380. IniParser* ini = new IniParser;
  381. int ret = ini->LoadFromFile(g_main_ctx.confile);
  382. if (ret != 0) {
  383. printf("Load confile [%s] failed: %d\n", g_main_ctx.confile, ret);
  384. exit(-40);
  385. } else {
  386. g_main_ctx.confile_parser = ini;
  387. }
  388. if (get_arg("t")) {
  389. printf("Test confile [%s] OK!\n", g_main_ctx.confile);
  390. exit(0);
  391. }
  392. const char* signal = get_arg("s");
  393. if (signal) {
  394. if (strcmp(signal, "start") == 0) {
  395. if (g_main_ctx.oldpid > 0) {
  396. printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  397. exit(0);
  398. }
  399. } else if (strcmp(signal, "stop") == 0) {
  400. if (g_main_ctx.oldpid > 0) {
  401. #ifdef __unix__
  402. kill(g_main_ctx.oldpid, SIGNAL_TERMINATE);
  403. #else
  404. SetEvent(s_hEventTerm);
  405. #endif
  406. printf("%s stop/waiting\n", g_main_ctx.program_name);
  407. } else {
  408. printf("%s is already stopped", g_main_ctx.program_name);
  409. }
  410. exit(0);
  411. } else if (strcmp(signal, "restart") == 0) {
  412. if (g_main_ctx.oldpid > 0) {
  413. #ifdef __unix__
  414. kill(g_main_ctx.oldpid, SIGNAL_TERMINATE);
  415. #else
  416. SetEvent(s_hEventTerm);
  417. #endif
  418. printf("%s stop/waiting\n", g_main_ctx.program_name);
  419. msleep(1000);
  420. }
  421. } else if (strcmp(signal, "status") == 0) {
  422. if (g_main_ctx.oldpid > 0) {
  423. printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  424. } else {
  425. printf("%s stop/waiting\n", g_main_ctx.program_name);
  426. }
  427. exit(0);
  428. } else {
  429. printf("Invalid signal: '%s'\n", signal);
  430. exit(0);
  431. }
  432. printf("%s start/running\n", g_main_ctx.program_name);
  433. }
  434. #ifdef __unix__
  435. if (get_arg("d")) {
  436. // nochdir, noclose
  437. int ret = daemon(1, 1);
  438. if (ret != 0) {
  439. printf("daemon error: %d\n", ret);
  440. exit(-10);
  441. }
  442. // parent process exit after daemon, so pid changed.
  443. g_main_ctx.pid = getpid();
  444. }
  445. #endif
  446. hlog_set_file(g_main_ctx.logfile);
  447. hlog_set_level(LOG_LEVEL_DEBUG);
  448. hlogi("%s version: %s", g_main_ctx.program_name, get_compile_version());
  449. hlogi("%s start/running, pid=%d", g_main_ctx.program_name, g_main_ctx.pid);
  450. create_pidfile();
  451. master_process_cycle();
  452. return 0;
  453. }