hmain.cpp.tmpl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. hlogi("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. hlogi("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. // unix use multi-processes
  236. // we use SIGTERM to quit process
  237. #define SIGNAL_TERMINATE SIGTERM
  238. #include <sys/wait.h>
  239. #define MAXNUM_WORKER_PROCESSES 1024
  240. #define DEFAULT_WORKER_PROCESSES 4
  241. static pid_t s_worker_processes[MAXNUM_WORKER_PROCESSES];
  242. void worker_process_cycle() {
  243. while(1) {
  244. msleep(1);
  245. }
  246. }
  247. int create_worker_process(int worker_processes) {
  248. for (int i = 0; i < worker_processes; ++i) {
  249. pid_t pid = fork();
  250. if (pid < 0) {
  251. hloge("fork error: %d", errno);
  252. return errno;
  253. }
  254. if (pid == 0) {
  255. hlogi("worker process start/running, pid=%d", getpid());
  256. char proctitle[256] = {0};
  257. snprintf(proctitle, sizeof(proctitle), "%s: worker process", g_main_ctx.program_name);
  258. setproctitle(proctitle);
  259. worker_process_cycle();
  260. exit(0);
  261. }
  262. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  263. if (s_worker_processes[i] <= 0) {
  264. s_worker_processes[i] = pid;
  265. break;
  266. }
  267. }
  268. }
  269. return 0;
  270. }
  271. void master_process_signal_handler(int signo) {
  272. hlogi("pid=%d recv signo=%d", getpid(), signo);
  273. switch (signo) {
  274. case SIGINT:
  275. case SIGNAL_TERMINATE:
  276. hlogi("killall worker processes");
  277. signal(SIGCHLD, SIG_IGN);
  278. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  279. if (s_worker_processes[i] <= 0) break;
  280. kill(s_worker_processes[i], SIGKILL);
  281. s_worker_processes[i] = -1;
  282. }
  283. exit(0);
  284. break;
  285. case SIGCHLD:
  286. {
  287. pid_t pid = 0;
  288. int status = 0;
  289. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  290. hlogw("worker process stop/waiting, pid=%d status=%d", pid, status);
  291. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  292. if (s_worker_processes[i] == pid) {
  293. s_worker_processes[i] = -1;
  294. break;
  295. }
  296. }
  297. create_worker_process(1);
  298. }
  299. }
  300. break;
  301. default:
  302. break;
  303. }
  304. }
  305. void master_process_init() {
  306. char proctitle[256] = {0};
  307. snprintf(proctitle, sizeof(proctitle), "%s: master process", g_main_ctx.program_name);
  308. setproctitle(proctitle);
  309. signal(SIGINT, master_process_signal_handler);
  310. signal(SIGCHLD, master_process_signal_handler);
  311. signal(SIGNAL_TERMINATE, master_process_signal_handler);
  312. for (int i = 0; i < MAXNUM_WORKER_PROCESSES; ++i) {
  313. s_worker_processes[i] = -1;
  314. }
  315. }
  316. void master_process_cycle() {
  317. int worker_processes = 0;
  318. IniParser* ini = (IniParser*)g_main_ctx.confile_parser;
  319. if (ini) {
  320. worker_processes = atoi(ini->GetValue("worker_processes", "core").c_str());
  321. hlogd("core.worker_processes=%d", worker_processes);
  322. }
  323. if (worker_processes <= 0 || worker_processes > MAXNUM_WORKER_PROCESSES) {
  324. worker_processes = get_ncpu();
  325. hlogd("worker_processes=ncpu=%d", worker_processes);
  326. }
  327. if (worker_processes <= 0 || worker_processes > MAXNUM_WORKER_PROCESSES) {
  328. worker_processes = DEFAULT_WORKER_PROCESSES;
  329. }
  330. create_worker_process(worker_processes);
  331. while (1) {
  332. msleep(1);
  333. }
  334. }
  335. #elif defined(_WIN32)
  336. // win32 use Event
  337. // win32 use multi-threads
  338. static HANDLE s_hEventTerm = NULL;
  339. void master_process_exit() {
  340. CloseHandle(s_hEventTerm);
  341. s_hEventTerm = NULL;
  342. }
  343. void master_process_init() {
  344. char eventname[MAX_PATH] = {0};
  345. snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  346. s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  347. //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname);
  348. atexit(master_process_exit);
  349. }
  350. void master_process_cycle() {
  351. while (1) {
  352. DWORD ret = WaitForSingleObject(s_hEventTerm, 0);
  353. if (ret == WAIT_OBJECT_0) {
  354. hlogi("pid=%d recv event [TERM]", getpid());
  355. exit(0);
  356. }
  357. msleep(1);
  358. }
  359. }
  360. #endif
  361. int main(int argc, char** argv) {
  362. // g_main_ctx
  363. main_ctx_init(argc, argv);
  364. parse_cmdline(argc, argv);
  365. master_process_init();
  366. // help
  367. if (get_arg("h")) {
  368. print_help();
  369. exit(0);
  370. }
  371. // version
  372. if (get_arg("v")) {
  373. print_version();
  374. exit(0);
  375. }
  376. // confile
  377. const char* confile = get_arg("c");
  378. if (confile) {
  379. strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile));
  380. }
  381. IniParser* ini = new IniParser;
  382. int ret = ini->LoadFromFile(g_main_ctx.confile);
  383. if (ret != 0) {
  384. printf("Load confile [%s] failed: %d\n", g_main_ctx.confile, ret);
  385. exit(-40);
  386. } else {
  387. g_main_ctx.confile_parser = ini;
  388. }
  389. // logfile
  390. hlog_set_file(g_main_ctx.logfile);
  391. int loglevel = LOG_LEVEL_DEBUG;
  392. hlog_set_level(LOG_LEVEL_DEBUG);
  393. const char* szLoglevel = ini->GetValue("loglevel").c_str();
  394. if (stricmp(szLoglevel, "DEBUG") == 0) {
  395. loglevel = LOG_LEVEL_DEBUG;
  396. } else if (stricmp(szLoglevel, "INFO") == 0) {
  397. loglevel = LOG_LEVEL_INFO;
  398. } else if (stricmp(szLoglevel, "WARN") == 0) {
  399. loglevel = LOG_LEVEL_WARN;
  400. } else if (stricmp(szLoglevel, "ERROR") == 0) {
  401. loglevel = LOG_LEVEL_ERROR;
  402. } else {
  403. loglevel = LOG_LEVEL_DEBUG;
  404. }
  405. hlog_set_level(loglevel);
  406. hlogi("%s version: %s", g_main_ctx.program_name, get_compile_version());
  407. // test
  408. if (get_arg("t")) {
  409. printf("Test confile [%s] OK!\n", g_main_ctx.confile);
  410. exit(0);
  411. }
  412. const char* signal = get_arg("s");
  413. if (signal) {
  414. if (strcmp(signal, "start") == 0) {
  415. if (g_main_ctx.oldpid > 0) {
  416. printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  417. exit(0);
  418. }
  419. } else if (strcmp(signal, "stop") == 0) {
  420. if (g_main_ctx.oldpid > 0) {
  421. #ifdef __unix__
  422. kill(g_main_ctx.oldpid, SIGNAL_TERMINATE);
  423. #else
  424. SetEvent(s_hEventTerm);
  425. #endif
  426. printf("%s stop/waiting\n", g_main_ctx.program_name);
  427. } else {
  428. printf("%s is already stopped", g_main_ctx.program_name);
  429. }
  430. exit(0);
  431. } else if (strcmp(signal, "restart") == 0) {
  432. if (g_main_ctx.oldpid > 0) {
  433. #ifdef __unix__
  434. kill(g_main_ctx.oldpid, SIGNAL_TERMINATE);
  435. #else
  436. SetEvent(s_hEventTerm);
  437. #endif
  438. printf("%s stop/waiting\n", g_main_ctx.program_name);
  439. msleep(1000);
  440. }
  441. } else if (strcmp(signal, "status") == 0) {
  442. if (g_main_ctx.oldpid > 0) {
  443. printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  444. } else {
  445. printf("%s stop/waiting\n", g_main_ctx.program_name);
  446. }
  447. exit(0);
  448. } else {
  449. printf("Invalid signal: '%s'\n", signal);
  450. exit(0);
  451. }
  452. printf("%s start/running\n", g_main_ctx.program_name);
  453. }
  454. #ifdef __unix__
  455. // daemon
  456. if (get_arg("d")) {
  457. // nochdir, noclose
  458. int ret = daemon(1, 1);
  459. if (ret != 0) {
  460. printf("daemon error: %d\n", ret);
  461. exit(-10);
  462. }
  463. // parent process exit after daemon, so pid changed.
  464. g_main_ctx.pid = getpid();
  465. }
  466. #endif
  467. // pidfile
  468. hlogi("%s start/running, pid=%d", g_main_ctx.program_name, g_main_ctx.pid);
  469. create_pidfile();
  470. // main_process_cycle
  471. master_process_cycle();
  472. return 0;
  473. }