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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. if(PyFCGI_conf.context.n_wrk)
  25. {
  26. kill(PyFCGI_conf.context.pid, SIGTERM);
  27. }
  28. pyfcgi_IPC_close(IPC_WSTATE | IPC_WREQS | IPC_SEMST | IPC_SHMST);
  29. pyfcgi_IPC_destroy(IPC_WSTATE | IPC_WREQS | IPC_SEMST | IPC_SHMST);
  30. exit(status);
  31. }
  32. pid_t spawn_pool_handler()
  33. {
  34. pid_t res;
  35. struct sigaction act;
  36. act.sa_handler = pyfcgi_sighandler_drop;
  37. sigemptyset(&act.sa_mask);
  38. act.sa_flags = 0;
  39. act.sa_restorer = NULL;
  40. res = fork();
  41. if(res < 0)
  42. {
  43. pyfcgi_log(LOG_ALERT, "Failed to fork pool_handler : %s",
  44. strerror(errno));
  45. return -1;
  46. }
  47. if(!res)
  48. {
  49. if(sigaction(SIGINT, &act, NULL))
  50. {
  51. pyfcgi_log(LOG_WARNING,
  52. "Unable to sigaction SIGINT handler : %s",
  53. strerror(errno));
  54. }
  55. responder_loop();
  56. exit((unsigned char)-1);
  57. }
  58. return res;
  59. }
  60. void init_context()
  61. {
  62. PyFCGI_conf.context.pid = getpid();
  63. PyFCGI_conf.context.ppid = getppid();
  64. if(pyfcgi_IPC_create(IPC_WSTATE | IPC_WREQS | IPC_SEMST | IPC_SHMST) < 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. if(sem_post(PyFCGI_SEM(SEM_STATS).sem) < 0)
  71. {
  72. pyfcgi_log(LOG_ALERT, "Unable to POST stat semaphore : %s",
  73. strerror(errno));
  74. clean_exit(PYFCGI_FATAL);
  75. }
  76. //Alloc workers PID array
  77. PyFCGI_conf.context.wrk_pids = malloc(
  78. sizeof(pid_t)*(PyFCGI_conf.max_wrk+1));
  79. if(!PyFCGI_conf.context.wrk_pids)
  80. {
  81. pyfcgi_log(LOG_ALERT,
  82. "Unable to allocate worker PID array : %s",
  83. strerror(errno));
  84. clean_exit(PYFCGI_FATAL);
  85. }
  86. bzero(PyFCGI_conf.context.wrk_pids,
  87. sizeof(pid_t) * (PyFCGI_conf.max_wrk + 1));
  88. // Open FCGI listen socket
  89. PyFCGI_conf.context.fcgi_socket = FCGX_OpenSocket(PyFCGI_conf.sock_path,
  90. PYFCGI_SOCK_BACKLOG);
  91. if(PyFCGI_conf.context.fcgi_socket == -1)
  92. {
  93. pyfcgi_log(LOG_ALERT, "Unable to open socket : '%s'",
  94. PyFCGI_conf.sock_path);
  95. clean_exit(PYFCGI_FATAL);
  96. }
  97. if(FCGX_Init() != 0)
  98. {
  99. pyfcgi_log(LOG_ALERT, "Unable to init libfcgi");
  100. clean_exit(PYFCGI_FATAL);
  101. }
  102. pyfcgi_log(LOG_INFO, "Listening on %s", PyFCGI_conf.sock_path);
  103. }
  104. int responder_loop()
  105. {
  106. unsigned int n_wrk, wanted_n, n;
  107. pid_t *wrk_pids;
  108. int status;
  109. pid_t ret;
  110. /**@brief poll timeout */
  111. struct timespec timeout;
  112. struct timespec idle_timeout;
  113. /**@brief watchdog timeout */
  114. struct timespec pool_timeout;
  115. time_t idle_start, busy_start;
  116. short idle, busy;
  117. struct sigaction act;
  118. char *statusstr;
  119. time_t last_update, now;
  120. act.sa_handler = pool_sighandler;
  121. sigemptyset(&act.sa_mask);
  122. sigaddset(&act.sa_mask, SIGTERM);
  123. act.sa_flags = 0;
  124. act.sa_restorer = NULL;
  125. if(sigaction(SIGTERM, &act, NULL))
  126. {
  127. pyfcgi_log(LOG_ALERT,
  128. "Sigaction error for SIGTERM pool process : %s",
  129. strerror(errno));
  130. exit(PYFCGI_FATAL);
  131. }
  132. idle_timeout.tv_sec = 0;
  133. idle_timeout.tv_nsec = 100000; //0.0001s
  134. timeout.tv_sec = 0;
  135. timeout.tv_nsec = 100000000; //0.1s
  136. idle = busy = 0;
  137. pyfcgi_logger_set_ident("Workpool");
  138. if(PyFCGI_conf.pool_timeout)
  139. {
  140. pool_timeout.tv_nsec = 0;
  141. pool_timeout.tv_sec = PyFCGI_conf.pool_timeout;
  142. pyfcgi_wd_init(pool_wd_sighandler, &pool_timeout);
  143. }
  144. pyfcgi_log(LOG_INFO, "Preparing workers");
  145. init_context();
  146. pyfcgi_wd_arm();
  147. wrk_pids = PyFCGI_conf.context.wrk_pids;
  148. PyFCGI_conf.context.n_wrk = 0;
  149. wanted_n = PyFCGI_conf.min_wrk;
  150. n_wrk = 0;
  151. // prespawning minimum worker count
  152. for(n_wrk=0; n_wrk < wanted_n; n_wrk++)
  153. {
  154. wrk_pids[n_wrk] = spawn(n_wrk);
  155. PyFCGI_conf.context.n_wrk = n_wrk;
  156. }
  157. //Wait at least for a process to be ready
  158. while(!pyfcgi_pool_idle(&idle_timeout));
  159. last_update = 0;
  160. // main loop, taking care to restart terminated workers,
  161. // spawn new one if needed, etc.
  162. while(1)
  163. {
  164. pyfcgi_wd_arm();
  165. PyFCGI_conf.context.n_wrk = n_wrk;
  166. if(last_update != (now = time(NULL)))
  167. {
  168. pyfcgi_log(LOG_DEBUG, "Infos : n_wrk=%d max=%d min=%d",
  169. n_wrk, PyFCGI_conf.max_wrk, PyFCGI_conf.min_wrk);
  170. pyfcgi_pool_shm_update(n_wrk);
  171. last_update = now;
  172. }
  173. if( (ret = waitpid(0, &status, WNOHANG)) )
  174. {
  175. if(ret < 0)
  176. {
  177. //TODO : error
  178. }
  179. for(n=0; n<n_wrk; n++)
  180. {
  181. if(wrk_pids[n] == ret)
  182. {
  183. break;
  184. }
  185. }
  186. if(n == n_wrk)
  187. {
  188. pyfcgi_log(LOG_WARNING,
  189. "Child %d stopped but was notregistered",
  190. ret);
  191. continue;
  192. }
  193. if(WIFSIGNALED(status))
  194. {
  195. if(WTERMSIG(status) == 9)
  196. {
  197. pyfcgi_log(LOG_ALERT,
  198. "Worker[%d] get killed ! No guaranty that SEM_WSTATE is OK, exiting...",
  199. n);
  200. clean_exit(PYFCGI_WORKER_FAIL);
  201. }
  202. if(WTERMSIG(status) == 11)
  203. {
  204. pyfcgi_log(LOG_ALERT,
  205. "Worker[%d] segfault ! No guaranty that SEM_WSTATE is OK, exiting...",
  206. n);
  207. clean_exit(PYFCGI_WORKER_FAIL);
  208. }
  209. else
  210. {
  211. pyfcgi_log(LOG_ALERT,
  212. "Worker[%d] terminated by signal %s(%d)",
  213. n, strsignal(WTERMSIG(status)),
  214. WTERMSIG(status));
  215. }
  216. }
  217. if(WEXITSTATUS(status))
  218. {
  219. statusstr = status2str(WEXITSTATUS(status));
  220. pyfcgi_log((WEXITSTATUS(status)&PYFCGI_FATAL)?
  221. LOG_ALERT:LOG_WARNING,
  222. "Worker[%d] exited with status %s",
  223. n, statusstr);
  224. free(statusstr);
  225. }
  226. if(!status)
  227. {
  228. pyfcgi_log(LOG_INFO,
  229. "Worker[%d] PID %d exited normally",
  230. n, wrk_pids[n]);
  231. }
  232. // respawn on same slot
  233. pyfcgi_log(LOG_DEBUG, "respawning worker #%d", n);
  234. wrk_pids[n] = spawn(n);
  235. }
  236. // Check if the pool is idle or busy
  237. if(pyfcgi_pool_idle(&idle_timeout))
  238. {
  239. // workers idle
  240. busy = 0;
  241. if(!idle)
  242. {
  243. idle = 1;
  244. idle_start = time(NULL);
  245. }
  246. else if((time(NULL) - idle_start) > PyFCGI_conf.worker_gc_timeout &&
  247. wanted_n > PyFCGI_conf.min_wrk
  248. && n_wrk - wanted_n < 2)
  249. {
  250. wanted_n--;
  251. idle = 0;
  252. }
  253. }
  254. else
  255. {
  256. idle = 0;
  257. if(!busy)
  258. {
  259. busy = 1;
  260. busy_start = time(NULL);
  261. }
  262. else if(time(NULL) - busy_start > 0 &&
  263. wanted_n < PyFCGI_conf.max_wrk)
  264. {
  265. pyfcgi_log( LOG_DEBUG,
  266. "All workers busy, spawning a new one");
  267. n = n_wrk;
  268. n_wrk++;
  269. wanted_n = n_wrk;
  270. wrk_pids[n] = spawn(n);
  271. if(!PyFCGI_conf.worker_fast_spawn)
  272. {
  273. busy_start = time(NULL);
  274. }
  275. }
  276. }
  277. // Stopping & deleting useless childs
  278. if(wanted_n < n_wrk && idle)
  279. {
  280. busy = 0;
  281. n_wrk--;
  282. kill(wrk_pids[n_wrk], SIGTERM); // kill last worker
  283. nanosleep(&timeout, NULL);
  284. if( (ret = waitpid(wrk_pids[n_wrk], &status, WNOHANG)) < 0 )
  285. {
  286. pyfcgi_log(LOG_ERR, "Pool idle since %ds but unable to kill child %d (PID %d)",
  287. PyFCGI_conf.worker_gc_timeout,
  288. n_wrk, wrk_pids[n_wrk]);
  289. kill(wrk_pids[n_wrk], SIGKILL);
  290. }
  291. else
  292. {
  293. pyfcgi_log(LOG_INFO, "Pool idle since %ds : worker[%d](%d) killed",
  294. PyFCGI_conf.worker_gc_timeout,
  295. n_wrk, wrk_pids[n_wrk]);
  296. }
  297. wrk_pids[n_wrk] = 0;
  298. idle = 0;
  299. continue;
  300. }
  301. nanosleep(&timeout, NULL);
  302. }
  303. pyfcgi_wd_arm();
  304. //Debug wait & exit
  305. for(; n_wrk != 0; n_wrk--)
  306. {
  307. waitpid(wrk_pids[n_wrk], &status, 0);
  308. pyfcgi_log(LOG_DEBUG, "Child %d stopped with status %d",
  309. wrk_pids[n_wrk], status);
  310. PyFCGI_conf.context.n_wrk = n_wrk;
  311. }
  312. //printf("Content-Type: text/html\r\n\r\nHello world !\n");
  313. pyfcgi_wd_stop();
  314. pyfcgi_log(LOG_INFO,"Child workers stoped, stopping responder");
  315. exit(0);
  316. }
  317. pid_t spawn(int wrk_id)
  318. {
  319. pid_t res;
  320. struct timespec wd_timeout;
  321. struct sigaction act;
  322. char ident[128];
  323. act.sa_handler = worker_sighandler;
  324. sigemptyset(&act.sa_mask);
  325. act.sa_flags = 0;
  326. act.sa_restorer = NULL;
  327. res = fork();
  328. if(res == -1)
  329. {
  330. pyfcgi_log(LOG_ERR, "Fork fails for worker #%d : %s",
  331. wrk_id, strerror(errno));
  332. return -1;
  333. }
  334. else if(!res)
  335. {
  336. // Child process
  337. PyFCGI_conf.context.ppid = PyFCGI_conf.context.pid;
  338. PyFCGI_conf.context.pid = getpid();
  339. snprintf(ident, 128, "Worker%2d", wrk_id);
  340. pyfcgi_logger_set_ident(ident);
  341. // Init IPC components
  342. if(pyfcgi_IPC_init(IPC_WSTATE | IPC_WREQS) < 0)
  343. {
  344. pyfcgi_log(LOG_ALERT, "Unable to initialize semaphore when spawning process...");
  345. exit(PYFCGI_FATAL);
  346. }
  347. // Set handler for SIGINT & SIGTERM
  348. /*
  349. if(sigaction(SIGINT, &(PyFCGI_conf.context.master_old_sigint),
  350. NULL))
  351. {
  352. pyfcgi_log(LOG_ALERT,
  353. "Sigaction error for worker process when restoring SIGINT handler: %s",
  354. strerror(errno));
  355. exit(PYFCGI_FATAL);
  356. }
  357. */
  358. if(sigaction(SIGTERM, &act, NULL))
  359. {
  360. pyfcgi_log(LOG_ALERT,
  361. "Sigaction error for worker process : %s",
  362. strerror(errno));
  363. exit(PYFCGI_FATAL);
  364. }
  365. // Set watchdog
  366. if(PyFCGI_conf.worker_timeout)
  367. {
  368. wd_timeout.tv_nsec = 0;
  369. wd_timeout.tv_sec = PyFCGI_conf.worker_timeout;
  370. pyfcgi_wd_init(worker_sigalrmhandler, &wd_timeout);
  371. }
  372. if(PyFCGI_conf.pep333)
  373. {
  374. exit(work333(wrk_id));
  375. }
  376. else
  377. {
  378. exit(work(wrk_id));
  379. }
  380. }
  381. pyfcgi_IPC_init(IPC_WSTATE | IPC_WREQS | IPC_SEMST);
  382. // Sleep to avoid spawning like hell thinking all workers are
  383. // busy. Let some time to this one to go up...
  384. // TODO: find a better way to avoid spawning to max_wrk
  385. //nanosleep(&timeout, NULL);
  386. pyfcgi_log( LOG_INFO,
  387. "Worker #%d spawned with PID %d", wrk_id, res);
  388. return res;
  389. }
  390. int pyfcgi_pool_state()
  391. {
  392. int err, res;
  393. if(sem_getvalue(PyFCGI_SEM(SEM_WSTATE).sem, &res) < 0)
  394. {
  395. err = errno;
  396. pyfcgi_log(LOG_ALERT, "Unable to read WSTATE semaphore value : %s",
  397. strerror(err));
  398. clean_exit(PYFCGI_FATAL);
  399. }
  400. return res;
  401. }
  402. int pyfcgi_pool_idle(const struct timespec *timeout)
  403. {
  404. int err;
  405. struct timespec abs_timeout;
  406. if(clock_gettime(CLOCK_REALTIME_COARSE, &abs_timeout) < 0)
  407. {
  408. //clock error
  409. pyfcgi_log(LOG_WARNING, "Unable to fetch asbtime for WSTATE sem_timedwait : %s",
  410. strerror(errno));
  411. }
  412. abs_timeout.tv_sec += timeout->tv_sec;
  413. if(abs_timeout.tv_nsec + timeout->tv_nsec > 999999999)
  414. {
  415. abs_timeout.tv_nsec = abs_timeout.tv_nsec + timeout->tv_nsec - 999999999;
  416. abs_timeout.tv_sec +=1;
  417. }
  418. else
  419. {
  420. abs_timeout.tv_nsec = timeout->tv_nsec;
  421. }
  422. if(sem_timedwait(PyFCGI_SEM(SEM_WSTATE).sem, &abs_timeout) < 0)
  423. {
  424. err = errno;
  425. switch(err)
  426. {
  427. case ETIMEDOUT:
  428. case EAGAIN:
  429. return 0; //busy
  430. case EINVAL:
  431. sleep(1);
  432. return 1;
  433. default:
  434. pyfcgi_log(LOG_ALERT, "Unable to wait WSTATE sem : %s",
  435. strerror(err));
  436. clean_exit(PYFCGI_FATAL);
  437. }
  438. }
  439. if(sem_post(PyFCGI_SEM(SEM_WSTATE).sem) < 0)
  440. {
  441. pyfcgi_log(LOG_ALERT,
  442. "Unable to sempost after a sem_timedwait : %s",
  443. strerror(errno));
  444. clean_exit(PYFCGI_FATAL);
  445. }
  446. return 1; //idle
  447. }
  448. void pool_sighandler(int signum)
  449. {
  450. unsigned int i, retry;
  451. int status, ret;
  452. struct timespec req;
  453. pyfcgi_log(LOG_NOTICE, "Received signal %s, cleaning & exiting...",
  454. strsignal(signum));
  455. if(PyFCGI_conf.context.n_wrk < 1) { clean_exit(0); }
  456. for(i=0; i<PyFCGI_conf.context.n_wrk; i++)
  457. {
  458. pyfcgi_log(LOG_INFO, "Sending SIGTERM to child #%d (pid %d)",
  459. i,PyFCGI_conf.context.wrk_pids[i]);
  460. kill(PyFCGI_conf.context.wrk_pids[i], SIGTERM);
  461. }
  462. retry = i = 0;
  463. while(i<PyFCGI_conf.context.n_wrk)
  464. {
  465. ret = waitpid(PyFCGI_conf.context.wrk_pids[i], &status,
  466. WNOHANG);
  467. if(ret <= 0 && retry < 3)
  468. {
  469. retry++;
  470. req.tv_sec = 0;
  471. req.tv_nsec = 100000000; //0.1s
  472. nanosleep(&req, NULL);
  473. }
  474. else
  475. {
  476. if(retry < 3)
  477. {
  478. PyFCGI_conf.context.wrk_pids[i] = 0;
  479. }
  480. retry = 0;
  481. i++;
  482. }
  483. }
  484. for(i=0; i<PyFCGI_conf.context.n_wrk; i++)
  485. {
  486. if(PyFCGI_conf.context.wrk_pids[i])
  487. {
  488. pyfcgi_log(LOG_INFO, "Sending SIGKILL to child %d", i);
  489. kill(PyFCGI_conf.context.wrk_pids[i], SIGKILL);
  490. }
  491. }
  492. PyFCGI_conf.context.n_wrk = 0;
  493. clean_exit(0);
  494. }
  495. void pool_wd_sighandler(int signum)
  496. {
  497. unsigned int i;
  498. pyfcgi_log(LOG_ALERT, "Worker pool timeout ! Attempt to kill all childs");
  499. for(i=0; i<PyFCGI_conf.context.n_wrk; i++)
  500. {
  501. pyfcgi_log(LOG_ALERT, "Child[%d] PID %d", i, PyFCGI_conf.context.wrk_pids[i]);
  502. kill(PyFCGI_conf.context.wrk_pids[i], SIGALRM);
  503. }
  504. while(PyFCGI_conf.context.n_wrk)
  505. {
  506. kill(PyFCGI_conf.context.wrk_pids[PyFCGI_conf.context.n_wrk], SIGALRM);
  507. PyFCGI_conf.context.n_wrk--;
  508. }
  509. pyfcgi_wd_stop();
  510. kill(PyFCGI_conf.context.pid, SIGTERM);
  511. clean_exit(PYFCGI_TIMEOUT);
  512. exit(PYFCGI_TIMEOUT);
  513. }
  514. void pyfcgi_pool_shm_update(int nworker)
  515. {
  516. short retry;
  517. int err;
  518. pyfcgi_stats_shm_t *data;
  519. struct timespec req;
  520. req.tv_sec = 0;
  521. req.tv_nsec = 10000000; //0.01s
  522. retry = 0;
  523. while(1)
  524. {
  525. if(sem_trywait(PyFCGI_SEM(SEM_STATS).sem) < 0)
  526. {
  527. err = errno;
  528. if(err == EAGAIN)
  529. {
  530. if(retry >= 5)
  531. {
  532. pyfcgi_log(LOG_ALERT,
  533. "Deadlock on SEM_STATS");
  534. clean_exit(PYFCGI_FATAL);
  535. }
  536. nanosleep(&req, NULL);
  537. continue;
  538. }
  539. pyfcgi_log(LOG_ALERT,
  540. "Unable to wait stats semaphore : %s",
  541. strerror(err));
  542. clean_exit(PYFCGI_FATAL);
  543. }
  544. break;
  545. }
  546. data = (pyfcgi_stats_shm_t*)PyFCGI_conf.shm.ptr;
  547. data->nworker = nworker;
  548. err = 0;
  549. if(sem_getvalue(PyFCGI_SEM(SEM_WSTATE).sem, &(data->pool_load)) < 0)
  550. {
  551. data->pool_load = -1;
  552. pyfcgi_log(LOG_ALERT,
  553. "Unable to get semaphore value for SEM_WSTATE : ",
  554. strerror(errno));
  555. err = 1;
  556. }
  557. if(sem_post(PyFCGI_SEM(SEM_STATS).sem) < 0)
  558. {
  559. pyfcgi_log(LOG_ALERT, "Unable to post sem at shm update : %s",
  560. strerror(errno));
  561. clean_exit(PYFCGI_FATAL);
  562. }
  563. if(err)
  564. {
  565. clean_exit(PYFCGI_FATAL);
  566. }
  567. }