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

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