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.

main.c 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. /**@defgroup processes Process organisation of PyFCGI
  20. *
  21. * PyFCGI is organised in three layer :
  22. * A @ref main_proc : simple, that keep running and spawn a
  23. * @ref work_master_proc . This process handles @ref worker_process creation
  24. * and try to maintain a pool able to reply efficiently to CGI requests.
  25. */
  26. /**@defgroup main_proc Main process
  27. * @brief The main process in the @ref main() function
  28. * @ingroup processes
  29. */
  30. #include <fcgi_stdio.h> /* fcgi library; put it first*/
  31. #include <unistd.h>
  32. #include <stdlib.h>
  33. #include <syslog.h>
  34. #include <string.h>
  35. #include <errno.h>
  36. #include <signal.h>
  37. #include <time.h>
  38. #include <sys/types.h>
  39. #include <sys/wait.h>
  40. #include "conf.h"
  41. #include "logger.h"
  42. #include "responder.h"
  43. #include "ipc.h"
  44. #define IDENT_FMT "pyfcgi[%d]"
  45. #define MAX_REQS 1024
  46. #define EARLY_ERR(err_str) write(2, err_str, strlen(err_str))
  47. extern pyfcgi_conf_t PyFCGI_conf;
  48. pid_t pool_handler_pid;
  49. pid_t monitor_serv_pid;
  50. void sighandler(int signum)
  51. {
  52. int status, ret, i;
  53. struct timespec req;
  54. req.tv_sec = 0;
  55. req.tv_nsec = 100000000; //0.1s
  56. if(signum == SIGALRM)
  57. {
  58. pyfcgi_log(LOG_WARNING, "Master process received SIGALRM !");
  59. return;
  60. }
  61. else if(signum == SIGINT)
  62. {
  63. pyfcgi_log(LOG_INFO,
  64. "Master process received ctrl+c, exiting...");
  65. }
  66. else
  67. {
  68. pyfcgi_log(LOG_INFO,
  69. "Master process received signal %s(%d), exiting...",
  70. strsignal(signum), signum);
  71. }
  72. if(pool_handler_pid)
  73. {
  74. pyfcgi_log(LOG_INFO, "Killing pool_handler(%d)",
  75. pool_handler_pid);
  76. kill(pool_handler_pid, SIGTERM);
  77. for(i=0; i<5; i++)
  78. {
  79. ret = waitpid(pool_handler_pid, &status, WNOHANG);
  80. if(ret <= 0)
  81. {
  82. nanosleep(&req, NULL);
  83. continue;
  84. }
  85. pool_handler_pid = 0;
  86. break;
  87. }
  88. }
  89. if(monitor_serv_pid)
  90. {
  91. pyfcgi_log(LOG_INFO, "Killing monitor(%d)",
  92. monitor_serv_pid);
  93. kill(monitor_serv_pid, SIGTERM);
  94. for(i=0; i<5; i++)
  95. {
  96. ret = waitpid(monitor_serv_pid, &status, WNOHANG);
  97. if(ret <= 0)
  98. {
  99. nanosleep(&req, NULL);
  100. continue;
  101. }
  102. monitor_serv_pid = 0;
  103. break;
  104. }
  105. }
  106. if(pool_handler_pid)
  107. {
  108. pyfcgi_log(LOG_WARNING,
  109. "pool_handler(%d) seems to freeze, sending SIGKILL",
  110. pool_handler_pid);
  111. kill(pool_handler_pid, SIGKILL);
  112. }
  113. if(monitor_serv_pid)
  114. {
  115. pyfcgi_log(LOG_WARNING,
  116. "pool_handler(%d) seems to freeze, sending SIGKILL",
  117. monitor_serv_pid);
  118. kill(monitor_serv_pid, SIGKILL);
  119. }
  120. pyfcgi_log(LOG_INFO,
  121. "Master process exiting.");
  122. exit(0);
  123. }
  124. void debug_sighandler(int signum)
  125. {
  126. pyfcgi_log(LOG_WARNING, "Master process received signal %s(%d)",
  127. strsignal(signum), signum);
  128. return;
  129. }
  130. int main(int argc, char **argv)
  131. {
  132. int emerg_sleep = 3;
  133. int child_ret;
  134. pid_t rpid;
  135. struct sigaction act;
  136. short fails, need_wait;
  137. //Sleeping on waitpid WNOHANG
  138. struct timespec tsleep;
  139. char *child_name;
  140. act.sa_handler = sighandler;
  141. sigemptyset(&act.sa_mask);
  142. act.sa_flags = 0;
  143. act.sa_restorer = NULL;
  144. if(sigaction(SIGTERM, &act, NULL))
  145. {
  146. perror("Sigaction error");
  147. exit(4);
  148. }
  149. if(sigaction(SIGINT, &act, NULL))
  150. {
  151. perror("Sigaction error");
  152. exit(4);
  153. }
  154. act.sa_handler = debug_sighandler;
  155. if(sigaction(SIGALRM, &act, NULL))
  156. {
  157. perror("Sigaction2 error");
  158. exit(4);
  159. }
  160. pool_handler_pid = 0;
  161. monitor_serv_pid = 0;
  162. default_conf();
  163. pyfcgi_name_IPC(getpid()); //name semaphore using master proc PID
  164. pyfcgi_logger_init();
  165. pyfcgi_logger_set_ident("MainProc");
  166. if(parse_args(argc, argv))
  167. {
  168. return 1;
  169. }
  170. pyfcgi_log(LOG_INFO, "New server started");
  171. while(1)
  172. {
  173. if(!pool_handler_pid)
  174. {
  175. pool_handler_pid = spawn_pool_handler();
  176. if(pool_handler_pid < 0)
  177. {
  178. fails = 1;
  179. pool_handler_pid = 0;
  180. }
  181. }
  182. if(PyFCGI_conf.mon_socket && !monitor_serv_pid)
  183. {
  184. monitor_serv_pid = pyfcgi_spawn_monitor();
  185. if(monitor_serv_pid < 0)
  186. {
  187. fails = 1;
  188. monitor_serv_pid = 0;
  189. }
  190. }
  191. if(fails)
  192. {
  193. if(emerg_sleep > 600)
  194. {
  195. pyfcgi_log(LOG_EMERG, "Abording...");
  196. exit(PYFCGI_FATAL);
  197. }
  198. fails = 0;
  199. pyfcgi_log(LOG_WARNING, "Sleeping %ds",
  200. emerg_sleep);
  201. emerg_sleep *= 2;
  202. continue;
  203. }
  204. else
  205. {
  206. emerg_sleep = 3;
  207. }
  208. need_wait = ((!PyFCGI_conf.mon_socket || monitor_serv_pid)
  209. && pool_handler_pid);
  210. rpid = waitpid(0, &child_ret, need_wait?0:WNOHANG);
  211. if(rpid == pool_handler_pid)
  212. {
  213. child_name = "Pool handler";
  214. pool_handler_pid = 0;
  215. if(!child_ret)
  216. {
  217. pyfcgi_log(LOG_NOTICE,
  218. "Restarting main process after %d requests",
  219. MAX_REQS);
  220. continue;
  221. }
  222. }
  223. else if(rpid == monitor_serv_pid)
  224. {
  225. child_name = "Monitor server";
  226. monitor_serv_pid = 0;
  227. }
  228. else if(rpid == 0 && !need_wait)
  229. {
  230. tsleep.tv_sec = 0;
  231. tsleep.tv_nsec = 100000000;
  232. nanosleep(&tsleep, NULL);
  233. continue;
  234. }
  235. else if(rpid < 0)
  236. {
  237. pyfcgi_log(LOG_EMERG, "Unable to waitpid : %s",
  238. strerror(errno));
  239. exit(PYFCGI_FATAL);
  240. }
  241. else
  242. {
  243. child_name = "Unknown child";
  244. pyfcgi_log(LOG_WARNING,
  245. "Unknown child (PID %d) exited...", rpid);
  246. }
  247. if(child_ret)
  248. {
  249. pyfcgi_log(LOG_ERR, "%s exits with error code : %s",
  250. child_name, status2str(WEXITSTATUS(child_ret)));
  251. if(WIFSIGNALED(child_ret))
  252. {
  253. pyfcgi_log(LOG_ERR, "%s terminated by sig %s(%d)",
  254. child_name,
  255. strsignal(WTERMSIG(child_ret)),
  256. WTERMSIG(child_ret));
  257. }
  258. }
  259. else
  260. {
  261. pyfcgi_log(LOG_WARNING,
  262. "%s exits with no error status 0",
  263. child_name);
  264. }
  265. }
  266. closelog();
  267. }
  268. /**@mainpage PyFCGI
  269. * @section main_what What is PyFCGI ?
  270. * PyFCGI is a simple python3 fastcgi runner.
  271. *
  272. * Usage : Usage : spawn-fcgi [OPTIONS] -- pyfcgi -e PYMODULE [-E PYFUN] [OPTIONS]
  273. *
  274. * To run foo.entrypoint() python function.
  275. *
  276. * @subsection main_how_use How to use it ?
  277. *
  278. * @warning For the moment PyFCGI is under heavy developpement and in early
  279. * stage. Everything will change ;o)
  280. *
  281. * PyFCGI should be runned with spawn-fcgi (or something similar), allowing
  282. * to configure & forward environnement variables to libFCGI.
  283. *
  284. * For the moment no configuration files exists. You have to pass arguments
  285. * to pyfcgi using -- argument of spawnn-fcgi
  286. *
  287. * When called this function will have to send valid CGI data to the webserver
  288. * using sys.stdin (the print() function for exemple) like :
  289. *<code>Content-type: text/html\\r\\n\\r\\nHello world !\\n</code>
  290. *
  291. * The function will have access to updated CGI os.environ containing
  292. * all informations about a request
  293. *
  294. * @subsubsection main_how_use_syslog Logging, using syslog
  295. *
  296. * Right now PyFCGI uses pyfcgi_log() to log stuff using a pyfcgi ident.
  297. * PyFCGI logs can be filtered using /etc/rsyslog.d/pyfcgi.conf :
  298. *
  299. <pre>
  300. if ($programname contains 'pyfcgi') then {
  301. -/var/log/pyfcgi/pyfcgi.log
  302. stop
  303. }
  304. </pre>
  305. *
  306. * @subsubsection main_how_use_hardcode Hardcoded stuffs
  307. *
  308. * Right now there is a lot of hardcodd stuff. Fortunatly a vast majority
  309. * is in @ref main.c like the minimum and maximum number of workers, or
  310. * the number of requests before a worker restart. Some timers and stuff
  311. * are harcoded but should not in @ref pyworker.c & @ref responder.c
  312. *
  313. * @subsection main_how_works How it works ?
  314. *
  315. * - @ref processes
  316. * - @ref main_proc
  317. * - @ref work_master_proc
  318. * - @ref worker_process
  319. *
  320. */
  321. /**@page pyfcgi
  322. * @brief Python Fast CGI runner
  323. * @section man_syn SYNOPSIS
  324. * spawn-fcgi [OPTS] -- pyfcgi [OPTIONS]
  325. * @section man_desc DESCRIPTION
  326. * Run WSGI python application in a pool of worker.
  327. *
  328. * @section man_opt OPTIONS
  329. * @subsection man_opt_spawn spawn-fcgi OPTIONS
  330. * OPTS are @ref spawn-fcgi(1) options.
  331. *
  332. * @subsection man_opt_gen General OPTIONS
  333. * @par -h --help
  334. * Display help and exit
  335. * @par -V --version
  336. * Display pyfcgi and Python version and exit
  337. * @par -c --config=FILE
  338. * load a configuration file
  339. * @par -e --pymodule=MODULE_NAME
  340. * python entrypoint module name
  341. * @par -E --pyapp=FUNC_NAME
  342. * python entrypoint function name
  343. * @par -A --alt-io
  344. * use stdout to communicate with web server instead of entrypoint return as
  345. * specified in PEP333
  346. * @par -P --pid-file=PATH
  347. * Create a pidfile with master process PID
  348. *
  349. * @subsection man_opt_pool Worker pool OPTIONS
  350. * @par -w --min-worker
  351. * minimum worker in the pool
  352. * @par -W --max-worker
  353. * maximum worker in the pool
  354. * @par -f --fast-spawn
  355. * If not given there is at least 1s between two child creation. When given
  356. * childs may be spawned in small burst.
  357. * @par -t --timeout=SECONDS
  358. * Request timeout. If the timeout expires the worker process is restarted.
  359. *
  360. * @subsection man_opt_log Logging & monitoring OPTIONS
  361. * @par -L --log=LOGGERSPEC
  362. * Add a logfile using syntax "LOGFILE[;FILT][;FMT]" See @ref man_logger_specs
  363. * @par -S --syslog
  364. * Use syslog for logging
  365. * @par -v --verbose
  366. * Send all loglines on STDERR
  367. * @par -s --socket-server=SOCKURL
  368. * Indicate a socket like "tcp://localhost:8765" to listen on, replying status
  369. * and statistics. See @ref man_url_spec
  370. *
  371. * @section man_logger_specs Logfile format
  372. * A logger specification use the following format : LOGILE[;FILT][;FMT] with
  373. * - LOGFILE the logfile name
  374. * - FILT a number (in decimal or hex 0xHH) indicating wich facility/level to
  375. * log
  376. * - FMT the logline format, following the markup format described bellow
  377. * @subsection man_logger_fmt Logline format
  378. * Logline's format is indicated using a simple format using fields between
  379. * '{' and '}'. Supported fields are :
  380. * - {datetime} {datetime:SIZE} {datetime:SIZE:FMT} defines a format and a
  381. * constant length for a datetime field. Default : {datetime:25:%F %T%z}
  382. * - {level} the loglevel
  383. * - {facility} the log facility
  384. * - {pid} the process PID
  385. * - {ident} the process ident (friendly name)
  386. * - {msg} the log message (can appear only once)
  387. *
  388. * Specials chars '{' & '}' can be escpaed using "{{" and "}}", and all field
  389. * names can be abreviated to one character.
  390. *
  391. * @section man_url_spec Statistics socket URL format
  392. * Statistics server listen on a socket specified by an URL like :
  393. *
  394. * PROT://HOST:[PORT] with PROT one of :
  395. * - tcp with HOST a valid INET address
  396. * - udp with HOST a valid INET address
  397. * - unix with HOST a valid PATH
  398. *
  399. * @section EXAMPLES
  400. * To run foo_pep333.entrypoint() PEP333 application :
  401. *
  402. * spawn-fcgi -d . -n -p 9000 -a 127.0.0.1 -- src/pyfcgi -S
  403. * -e foo_pep333 -E entrypoint
  404. *
  405. * Logfile example :
  406. *
  407. * spawn-fcgi -d . -n -p 9000 -a 127.0.0.1 -- src/pyfcgi -S
  408. * -e foo_pep333 -E entrypoint
  409. * -L '/tmp/foo.log;0xff;{datetime} {msg} {ident}'
  410. *
  411. * @section AUTHOR
  412. * Written by Yann Weber &lt;yann.weber@member.fsf.org>
  413. *
  414. * @section COPYRIGHT
  415. * Copyright @ 2019 Yann Weber License GPLv3+: GNU GPL version 3 or later
  416. * &lt;http://gnu.org/licences/gpl.html>.
  417. *
  418. * This is free software: you are free to change and redistribute it.
  419. * There is NO WARRANTY, to extent permitted by law.
  420. *
  421. * @section man_see_also See Also
  422. * @ref spawn-fcgi(1)
  423. *
  424. * PyFCGI git repositorie &lt;https://git.yannweb.net/yannweb/pyfcgi>
  425. *
  426. */