How to use Supervisor to guard PHP-FPM Master process for automatic restart of PHP-FPM

Source: Internet
Author: User
Tags virtualenv

Recently, a colleague has a guardianship requirement for the PHP-FPM process, i.e. if the master process of PHP-FPM quits unexpectedly (possibly crash, it could be a false kill), then the master process is expected to be pulled automatically to avoid interruption of service.

We know that supervisor is a very powerful process monitoring (monitor & Control) tool that can theoretically implement the PHP-FPM master process's daemon requirements. Therefore, I help colleagues to test how to use supervisor to complete his needs, the results show that supervisor is really an artifact, just a reasonable configuration file, it can solve the problem.

Here is my research process and the final implementation of the PHP-FPM main process daemon function configuration file, here to make a record, but also hope to help others.

1. Installing Supervisor

Supervisor itself is a Python implementation, and is the research phase, so first create a new virtualenv environment, and then install the Supervisor package with PIP.

At this point, the basic research environment has been built. Of course, PHP-FPM and PHP environments and the front-end nginx are ready for the long time.

2. Analyzing php-fpm.sh Scripts

Usually after compiling and installing PHP, PHP-FPM this 2-binary C program will also be compiled and installed, typical path in the php_install_path/sbin/directory. The directory also has a script named php-fpm.sh to control actions such as start/stop/restart/reload of the PHP-FPM process.

In the./sbin/php-fpm.sh script, the "start" Operation initiates the PHP-FPM master process, and the rest is implemented by signal to the PHP-FPM master process.

# # code segment in php-fpm.sh Case "$" inchStartEcho-N"Starting php-fpm"                # # The following line is the key command                $php _fpm_bin--daemonize$php _opts                if["$?"!=0] ; Then                        Echo "Failed"                        Exit 1                fiWait_ for_pid created$php _fpm_pid                if[-N"$try"] ; Then                        Echo "Failed"                        Exit 1                Else                        Echo "Done"                fi;;

From above is the terminal input "./sbin/php-fpm.sh start" When actually executing the code, you can see that the PHP-FPM process's startup parameters are –daemonize $php_opts, while $php_ The value of opts is "–fpm-config $php_fpm_conf–pid $php_fpm_pid".

Note : When php-fpm.sh starts the PHP-FPM master process, the Daemonize parameter is passed in, indicating that PHP-FPM master processes is started in Daemon (daemon) mode. According to the supervisor documentation, when using the Supervisor monitoring process, the guardianship process cannot be the daemon , because the daemon usually "ends the life" of the parent process after the child process is forked. That is, the parent process created by supervisor exits, at which point supervisor can no longer monitor the child processes that have been created by the exiting process. The behavior of Daemon process can be understood by referring to the Linux Daemon Writing howto article.

Based on the above analysis, we know that as long as supervisor starts the PHP-FPM process, it does not pass in the Daemonize parameter.

3. Supervisor configuration file that implements the PHP-FPM Master process daemon function

The above analysis has told us how to solve the problem, the following directly on the verification of the available configuration files. The file is located in the php-fpm.conf sibling directory (typical path is php_install_path/etc/).

[Inet_http_server]; inet (TCP) server disabled bydefaultPort=127.0. 0. 1:9015; (IP_Address:PortSpecifier, *:Port  for  AllIface) [Supervisord]logfile=./var/log/supervisord.log; (Main logfile;default$CWD/supervisord.log) logfile_maxbytes= -MB; (max main logfile bytes b4 rotation;default  -MB) logfile_backups=2; (num ofMain logfile rotation backups;default Ten) Loglevel=info; (Log level;defaultInfoothers: Debug,warn,trace) Pidfile=./var/run/supervisord.pid; (Supervisord pidfile;defaultSupervisord.pid) Nodaemon=false; (StartinchForegroundifTruedefaultFalse) minfds=1024x768; (min. avail startupfiledescriptors;default 1024x768) minprocs= $; (min. availProcessdescriptors;default  $) identifier=sup.php-fpm; (Supervisord identifier,default  is ' Supervisor') [rpcinterface:supervisor]supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface[ supervisorctl]serverurl=http://127.0. 0. 1:9015; UseAN/HTTP URL toSpecify an inet socket[program:php-fpm]command=bash-c"Sleep 1 &&/home/slvher/tools/php/5.6.11/sbin/php-fpm--fpm-config/home/slvher/tools/php/5.6.11/etc/ php-fpm.conf--pid/home/slvher/tools/php/5.6.11/var/run/php-fpm.pid "; The program (relative uses PATH, can take args) process_name=% (program_name) s; Process_name Expr (default% (program_name) s) autostart=true; Start at Supervisord start (default: true) autorestart=true; whether/ when  toRestart (default: unexpected) startretries=5; Max # ofSerial Start Failures (default 3) exitcodes=0,2, -;' expected‘ExitCodes for Process(default 0,2) Stopsignal=quit;SignalUsed toKillProcess(defaultterm) stopwaitsecs=2; Max num secs to waitB4 SIGKILL (default Ten)

The configuration file structure is easy to grasp by looking at the supervisor documentation, with two configuration items that require special attention :

1) Command

It specifies the start command for the process to be monitored by the supervisor, as you can see, we have not passed the daemonize parameter to PHP-FPM, and the rest of the arguments simply expand the shell variable in the php-fpm.sh.

It has been noted that command is not a direct php-fpm, but rather the execution of two commands through Bash-c, and the first command is Sleep 1. This is due to the fact that the port that is occupied by PHP-FPM after stop is usually not released immediately, and when supervisor attempts to pull up the process at a very fast speed, it may fail several times due to the following error retry:

## var/log/php-fpm.error.log[18-Jul-201521:35:28ERRORtofor‘127.0.0.1:9002‘: Address already in use (98)[18-Jul-201521:35:28ERROR: FPM initialization failed

And supervisor currently does not support the delay restart function, therefore, here can only be done by first sleep and then start a slightly tricky method to solve the problem, the results show that the curative effect is good and no side effects. -_-

2) AutoRestart

The documentation is described below:

May is One  of false, Unexpected,or true. Iffalse, the Processwould never be autorestarted. If Unexpected, the ProcessWould be restart when theProgram exits with  anExit code is not  One  of  theExit codes associated withThisProcess' Configuration (see Exitcodes). Iftrue, the ProcessWould be unconditionally restarted whenitExitswithoutRegard toIts exit code.

The default value is unexpected, which indicates that supervisor will not pull the process again until the exit code exception for the monitored process. This is set to true to indicate that any time the process exits will be pulled again.

After this configuration, in the 1th step of this article set up a good virtualenv environment, run the following command to complete the Supervisor PHP-FPM Master process monitoring:

shell> supervisord -c etc/sup.php-fpm.conf

Then, by PS x | Fgrep FPM can see that the PHP-FPM master process has been pulled up.
Then, kill the PHP-FPM main process, again PS x | Fgrep FPM You can see that a new PHP-FPM master process is created by supervisor.

At this point, the need to use Supervisor Daemon PHP-FPM master process to achieve PHP-FPM automatic restart has been resolved.

Resources
    1. Supervisor:a Process Control System
    2. Linux Daemon Writing HOWTO

========================= EOF ====================

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to use Supervisor to guard PHP-FPM Master process for automatic restart of PHP-FPM

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.