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

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