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

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