Tests about a simple python3 fastcgi runner using libfcgi and the Python-C API.
python
c
wsgi
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

responder.c 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*
  2. * Copyright (C) 2019 Weber Yann
  3. *
  4. * This file is part of PyFCGI.
  5. *
  6. * PyFCGI is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * any later version.
  10. *
  11. * PyFCGI is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with PyFCGI. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "responder.h"
  20. /**@brief Exit after closing all stuff like semaphores
  21. * @ingroup work_master_proc */
  22. static void clean_exit(int status)
  23. {
  24. pyfcgi_IPC_close(IPC_WSTATE | IPC_WREQS | IPC_SEMST | IPC_SHMST);
  25. //temporarly destroy everything....
  26. pyfcgi_IPC_destroy(IPC_WSTATE | IPC_WREQS | IPC_SEMST | IPC_SHMST);
  27. //pyfcgi_IPC_destroy(IPC_WSTATE);
  28. exit(status);
  29. }
  30. pid_t spawn_pool_handler()
  31. {
  32. pid_t res;
  33. res = fork();
  34. if(res < 0)
  35. {
  36. pyfcgi_log(LOG_ALERT, "Failed to fork pool_handler : %s",
  37. strerror(errno));
  38. return -1;
  39. }
  40. if(!res)
  41. {
  42. responder_loop();
  43. exit((unsigned char)-1);
  44. }
  45. return res;
  46. }
  47. void init_context()
  48. {
  49. PyFCGI_conf.context.pid = getpid();
  50. PyFCGI_conf.context.ppid = getppid();
  51. if(pyfcgi_IPC_create(IPC_WSTATE | IPC_WREQS | IPC_SEMST) < 0)
  52. {
  53. pyfcgi_log(LOG_ALERT, "Pool handler process is unable to create WSTATE SEM");
  54. sleep(1);
  55. clean_exit(PYFCGI_FATAL);
  56. }
  57. /*
  58. if(pyfcgi_IPC_create(IPC_WSTATE) < 0)
  59. {
  60. pyfcgi_log(LOG_ALERT, "Pool handler process is unable to create WSTATE SEM");
  61. sleep(1);
  62. clean_exit(PYFCGI_FATAL);
  63. }
  64. if(pyfcgi_IPC_init(IPC_WREQS | IPC_SEMST) < 0)
  65. {
  66. pyfcgi_log(LOG_ALERT, "Pool handler process is unable to init IPC components");
  67. sleep(1);
  68. clean_exit(PYFCGI_FATAL);
  69. }
  70. */
  71. }
  72. int responder_loop()
  73. {
  74. unsigned int n_wrk, wanted_n, n;
  75. pid_t *wrk_pids;
  76. int err;
  77. int status;
  78. pid_t ret;
  79. /**@brief poll timeout */
  80. struct timespec timeout;
  81. /**@brief watchdog timeout */
  82. struct timespec pool_timeout;
  83. time_t idle_start, busy_start;
  84. short idle, busy;
  85. struct sigaction act;
  86. char *statusstr;
  87. act.sa_handler = pool_sighandler;
  88. sigemptyset(&act.sa_mask);
  89. sigaddset(&act.sa_mask, SIGTERM);
  90. act.sa_flags = 0;
  91. act.sa_restorer = NULL;
  92. if(sigaction(SIGINT, &act, NULL))
  93. {
  94. perror("Sigaction error for pool process");
  95. exit(PYFCGI_FATAL);
  96. }
  97. timeout.tv_sec = 0;
  98. timeout.tv_nsec = 100000000;
  99. idle = busy = 0;
  100. pyfcgi_logger_set_ident("Workpool");
  101. if(PyFCGI_conf.pool_timeout)
  102. {
  103. pool_timeout.tv_nsec = 0;
  104. pool_timeout.tv_sec = PyFCGI_conf.pool_timeout;
  105. pyfcgi_wd_init(pool_wd_sighandler, &pool_timeout);
  106. }
  107. pyfcgi_log(LOG_INFO, "Preparing workers");
  108. init_context();
  109. pyfcgi_wd_arm();
  110. PyFCGI_conf.context.wrk_pids = &wrk_pids;
  111. PyFCGI_conf.context.n_wrk = 0;
  112. wrk_pids = malloc(sizeof(int) * PyFCGI_conf.max_wrk);
  113. if(!wrk_pids)
  114. {
  115. err = errno;
  116. pyfcgi_log( LOG_ALERT,
  117. "Unable to allocate memory for childs PID : %s",
  118. strerror(err));
  119. clean_exit(err);
  120. }
  121. bzero(wrk_pids, sizeof(int) * PyFCGI_conf.max_wrk);
  122. wanted_n = PyFCGI_conf.min_wrk;
  123. n_wrk = 0;
  124. // prespawning minimum worker count
  125. for(n_wrk=0; n_wrk < wanted_n; n_wrk++)
  126. {
  127. wrk_pids[n_wrk] = spawn(n_wrk);
  128. PyFCGI_conf.context.n_wrk = n_wrk;
  129. }
  130. //Wait at least for a process to be ready
  131. while(!pyfcgi_pool_idle(&timeout));
  132. // main loop, taking care to restart terminated workers,
  133. // spawn new one if needed, etc.
  134. while(1)
  135. {
  136. pyfcgi_wd_arm();
  137. PyFCGI_conf.context.n_wrk = n_wrk;
  138. if( (ret = waitpid(0, &status, WNOHANG)) )
  139. {
  140. if(ret < 0)
  141. {
  142. //TODO : error
  143. }
  144. for(n=0; n<n_wrk; n++)
  145. {
  146. if(wrk_pids[n] == ret)
  147. {
  148. break;
  149. }
  150. }
  151. if(n == n_wrk)
  152. {
  153. pyfcgi_log(LOG_WARNING,
  154. "Child %d stopped but was notregistered",
  155. ret);
  156. continue;
  157. }
  158. if(WIFSIGNALED(status))
  159. {
  160. if(WTERMSIG(status) == 11)
  161. {
  162. pyfcgi_log(LOG_ALERT,
  163. "Worker[%d] segfault !",
  164. n);
  165. }
  166. else
  167. {
  168. pyfcgi_log(LOG_ALERT,
  169. "Worker[%d] terminated by signal %s(%d)",
  170. n, strsignal(WTERMSIG(status)),
  171. WTERMSIG(status));
  172. }
  173. }
  174. if(WEXITSTATUS(status))
  175. {
  176. statusstr = status2str(WEXITSTATUS(status));
  177. pyfcgi_log((WEXITSTATUS(status)&PYFCGI_FATAL)?
  178. LOG_ALERT:LOG_WARNING,
  179. "Worker[%d] exited with status %s",
  180. n, statusstr);
  181. free(statusstr);
  182. }
  183. if(!status)
  184. {
  185. pyfcgi_log(LOG_INFO,
  186. "Worker[%d] PID %d exited normally",
  187. n, wrk_pids[n]);
  188. }
  189. // respawn on same slot
  190. pyfcgi_log(LOG_DEBUG, "respawning worker #%d", n);
  191. wrk_pids[n] = spawn(n);
  192. continue;
  193. }
  194. // Check if the pool is idle or busy
  195. if(pyfcgi_pool_idle(&timeout))
  196. {
  197. // workers idle
  198. busy = 0;
  199. if(!idle)
  200. {
  201. idle = 1;
  202. idle_start = time(NULL);
  203. }
  204. else if((time(NULL) - idle_start) > PyFCGI_conf.worker_gc_timeout &&
  205. wanted_n > PyFCGI_conf.min_wrk
  206. && n_wrk - wanted_n < 2)
  207. {
  208. wanted_n--;
  209. idle = 0;
  210. }
  211. }
  212. else
  213. {
  214. idle = 0;
  215. if(!busy)
  216. {
  217. busy = 1;
  218. busy_start = time(NULL);
  219. }
  220. else if(time(NULL) - busy_start > 0 &&
  221. wanted_n < PyFCGI_conf.max_wrk)
  222. {
  223. pyfcgi_log( LOG_DEBUG,
  224. "All workers busy, spawning a new one");
  225. n = n_wrk;
  226. n_wrk++;
  227. wanted_n = n_wrk;
  228. wrk_pids[n] = spawn(n);
  229. if(!PyFCGI_conf.worker_fast_spawn)
  230. {
  231. busy_start = time(NULL);
  232. }
  233. }
  234. }
  235. // Stopping & deleting useless childs
  236. if(wanted_n < n_wrk && idle)
  237. { // need to shift the list and dec n_wrk
  238. busy = 0;
  239. n_wrk--;
  240. kill(wrk_pids[n_wrk], SIGTERM);
  241. nanosleep(&timeout, NULL);
  242. if( (ret = waitpid(wrk_pids[n_wrk], &status, WNOHANG)) < 0 )
  243. {
  244. pyfcgi_log(LOG_ERR, "Pool idle since %ds but unable to kill child %d (PID %d)",
  245. PyFCGI_conf.worker_gc_timeout,
  246. n_wrk, wrk_pids[n_wrk]);
  247. kill(wrk_pids[n_wrk], SIGKILL);
  248. }
  249. else
  250. {
  251. pyfcgi_log(LOG_INFO, "Pool idle since %ds : worker[%d](%d) killed",
  252. PyFCGI_conf.worker_gc_timeout,
  253. n_wrk, wrk_pids[n_wrk]);
  254. }
  255. idle = 0;
  256. continue;
  257. }
  258. nanosleep(&timeout, NULL);
  259. }
  260. pyfcgi_wd_arm();
  261. //Debug wait & exit
  262. for(; n_wrk != 0; n_wrk--)
  263. {
  264. waitpid(wrk_pids[n_wrk], &status, 0);
  265. pyfcgi_log(LOG_DEBUG, "Child %d stopped with status %d",
  266. wrk_pids[n_wrk], status);
  267. PyFCGI_conf.context.n_wrk = n_wrk;
  268. }
  269. //printf("Content-Type: text/html\r\n\r\nHello world !\n");
  270. pyfcgi_wd_stop();
  271. pyfcgi_log(LOG_INFO,"Child workers stoped, stopping responder");
  272. exit(0);
  273. }
  274. pid_t spawn(int wrk_id)
  275. {
  276. pid_t res;
  277. struct timespec wd_timeout;
  278. struct sigaction act;
  279. char ident[128];
  280. act.sa_handler = worker_sighandler;
  281. sigemptyset(&act.sa_mask);
  282. act.sa_flags = 0;
  283. act.sa_restorer = NULL;
  284. res = fork();
  285. if(res == -1)
  286. {
  287. pyfcgi_log(LOG_ERR, "Fork fails for worker #%d : %s",
  288. wrk_id, strerror(errno));
  289. return -1;
  290. }
  291. else if(!res)
  292. {
  293. // Child process
  294. PyFCGI_conf.context.ppid = PyFCGI_conf.context.pid;
  295. PyFCGI_conf.context.pid = getpid();
  296. snprintf(ident, 128, "Worker%2d", wrk_id);
  297. pyfcgi_logger_set_ident(ident);
  298. // Init IPC components
  299. if(pyfcgi_IPC_init(IPC_WSTATE | IPC_WREQS) < 0)
  300. {
  301. pyfcgi_log(LOG_ALERT, "Unable to initialize semaphore when spawning process...");
  302. exit(PYFCGI_FATAL);
  303. }
  304. // Set handler for SIGINT & SIGTERM
  305. if(sigaction(SIGINT, &act, NULL))
  306. {
  307. perror("Sigaction error for pool process");
  308. exit(PYFCGI_FATAL);
  309. }
  310. if(sigaction(SIGTERM, &act, NULL))
  311. {
  312. perror("Sigaction2 error for pool process");
  313. exit(PYFCGI_FATAL);
  314. }
  315. // Set watchdog
  316. if(PyFCGI_conf.worker_timeout)
  317. {
  318. wd_timeout.tv_nsec = 0;
  319. wd_timeout.tv_sec = PyFCGI_conf.worker_timeout;
  320. pyfcgi_wd_init(worker_sigalrmhandler, &wd_timeout);
  321. }
  322. if(PyFCGI_conf.pep333)
  323. {
  324. exit(work333(wrk_id));
  325. }
  326. else
  327. {
  328. exit(work(wrk_id));
  329. }
  330. }
  331. pyfcgi_IPC_init(IPC_WSTATE | IPC_WREQS | IPC_SEMST);
  332. // Sleep to avoid spawning like hell thinking all workers are
  333. // busy. Let some time to this one to go up...
  334. // TODO: find a better way to avoid spawning to max_wrk
  335. //nanosleep(&timeout, NULL);
  336. pyfcgi_log( LOG_INFO,
  337. "Worker #%d spawned with PID %d", wrk_id, res);
  338. return res;
  339. }
  340. int pyfcgi_pool_state()
  341. {
  342. int err, res;
  343. if(sem_getvalue(PyFCGI_SEM(SEM_WSTATE).sem, &res) < 0)
  344. {
  345. err = errno;
  346. pyfcgi_log(LOG_ALERT, "Unable to read WSTATE semaphore value : %s",
  347. strerror(err));
  348. clean_exit(PYFCGI_FATAL);
  349. }
  350. return res;
  351. }
  352. int pyfcgi_pool_idle(const struct timespec *timeout)
  353. {
  354. int err;
  355. struct timespec abs_timeout;
  356. if(clock_gettime(CLOCK_REALTIME_COARSE, &abs_timeout) < 0)
  357. {
  358. //clock error
  359. pyfcgi_log(LOG_WARNING, "Unable to fetch asbtime for WSTATE sem_timedwait : %s",
  360. strerror(errno));
  361. }
  362. abs_timeout.tv_sec += timeout->tv_sec;
  363. if(abs_timeout.tv_nsec + timeout->tv_nsec > 999999999)
  364. {
  365. abs_timeout.tv_nsec = abs_timeout.tv_nsec + timeout->tv_nsec - 999999999;
  366. abs_timeout.tv_sec +=1;
  367. }
  368. else
  369. {
  370. abs_timeout.tv_nsec = timeout->tv_nsec;
  371. }
  372. if(sem_timedwait(PyFCGI_SEM(SEM_WSTATE).sem, &abs_timeout) < 0)
  373. {
  374. err = errno;
  375. switch(err)
  376. {
  377. case ETIMEDOUT:
  378. case EAGAIN:
  379. return 0; //busy
  380. case EINVAL:
  381. sleep(1);
  382. return 1;
  383. default:
  384. pyfcgi_log(LOG_ALERT, "Unable to wait WSTATE sem : %s",
  385. strerror(err));
  386. clean_exit(PYFCGI_FATAL);
  387. }
  388. }
  389. sem_post(PyFCGI_SEM(SEM_WSTATE).sem); //Hope no worker fails to set busy...
  390. return 1; //idle
  391. }
  392. void pool_sighandler(int signum)
  393. {
  394. unsigned int i;
  395. struct timespec req;
  396. req.tv_sec = 0;
  397. req.tv_nsec = 200000000; //0.2s
  398. if(PyFCGI_conf.context.n_wrk < 1) { clean_exit(0); }
  399. for(i=0; i<PyFCGI_conf.context.n_wrk; i++)
  400. {
  401. pyfcgi_log(LOG_INFO, "Sending SIGTERM to child #%d (pid %d)",
  402. i,(*PyFCGI_conf.context.wrk_pids)[i]);
  403. kill((*PyFCGI_conf.context.wrk_pids)[i], SIGTERM);
  404. nanosleep(&req, NULL); //waiting 0.2s
  405. }
  406. for(i=0; i<PyFCGI_conf.context.n_wrk; i++)
  407. {
  408. if(kill((*PyFCGI_conf.context.wrk_pids)[i], SIGCONT))
  409. {
  410. pyfcgi_log(LOG_INFO, "Sending SIGKILL to child %d", i);
  411. kill((*PyFCGI_conf.context.wrk_pids)[i], SIGKILL);
  412. }
  413. }
  414. clean_exit(0);
  415. }
  416. void pool_wd_sighandler(int signum)
  417. {
  418. unsigned int i;
  419. pyfcgi_log(LOG_ALERT, "Worker pool timeout ! Attempt to kill all childs");
  420. for(i=0; i<PyFCGI_conf.context.n_wrk; i++)
  421. {
  422. pyfcgi_log(LOG_ALERT, "Child[%d] PID %d", i, (*PyFCGI_conf.context.wrk_pids)[i]);
  423. kill((*PyFCGI_conf.context.wrk_pids)[i], SIGALRM);
  424. }
  425. while(PyFCGI_conf.context.n_wrk)
  426. {
  427. kill((*PyFCGI_conf.context.wrk_pids)[PyFCGI_conf.context.n_wrk], SIGALRM);
  428. PyFCGI_conf.context.n_wrk--;
  429. }
  430. pyfcgi_wd_stop();
  431. kill(PyFCGI_conf.context.pid, SIGTERM);
  432. clean_exit(PYFCGI_TIMEOUT);
  433. exit(PYFCGI_TIMEOUT);
  434. }