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

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