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

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