开发手册 欢迎您!
软件开发者资料库

Linux Supervisor 进程管理工具安装及使用

Supervisor是用Python开发的进程管理工具,可以很方便的用来启动、重启、关闭进程(不仅仅是 Python 进程)。能将一个普通的命令行进程变为后台daemon,并监控进程状态,异常退出时能自动重启。除了对单个进程的控制,还可以同时启动、关闭多个进程。本文主要介绍Linux Supervisor 进程管理工具安装及使用。

1、Supervisor 安装

1)easy_install 安装 supervisor

wget https://pypi.io/packages/source/s/setuptools/setuptools-33.1.1.zip  unzip setuptools-33.1.1.zip  cd setuptools-33.1.1  python setup.py install  easy_install supervisor

2)pip 安装 supervisor

pip install supervisor 

3)CentOS或Debian/Ubuntu 安装

CentOS:

yum install -y epel-releaseyum -y install supervisor

Debian/Ubuntu:

apt-get install supervisor

2、配置Supervisor

1)初始化配置文件

使用echo_supervisord_conf命令生成Supervisor的配置文件。

mkdir /etc/supervisord.d  echo_supervisord_conf >/etc/supervisord.conf 

2)修改配置文件

配置文件内容比较多,需要修改内容如下,

#修改socket文件的mode,默认是0700  sed -i 's/;chmod=0700/chmod=0766/g'/etc/supervisord.conf     #在配置文件最后添加以下两行内容来包含/etc/supervisord目录  sed -i '$a [include] \  files =/etc/supervisord.d/*.conf' /etc/supervisord.conf 

内容如下:

; Sample supervisor config file.;; For more information on the config file, please see:; http://supervisord.org/configuration.html;; Notes:;  - Shell expansion ("~" or "$HOME") is not supported.  Environment;    variables can be expanded using this syntax: "%(ENV_HOME)s".;  - Quotes around values are not supported, except in the case of;    the environment= options as shown below.;  - Comments must have a leading space: "a=b ;comment" not "a=b;comment".;  - Command will be truncated if it looks like a config file comment, e.g.;    "command=bash -c 'foo ; bar'" will truncate to "command=bash -c 'foo ".[unix_http_server]file=/var/run/supervisor.sock   ; the path to the socket file;chmod=0700                 ; socket file mode (default 0700);chown=nobody:nogroup       ; socket file uid:gid owner;username=user              ; default is no username (open server);password=123               ; default is no password (open server);[inet_http_server]         ; inet (TCP) server disabled by default;port=127.0.0.1:9001        ; ip_address:port specifier, *:port for all iface;username=user              ; default is no username (open server);password=123               ; default is no password (open server)[supervisord]logfile=/var/log/supervisord.log ; main log file; default $CWD/supervisord.loglogfile_maxbytes=50MB        ; max main logfile bytes b4 rotation; default 50MBlogfile_backups=10           ; # of main logfile backups; 0 means none, default 10loglevel=info                ; log level; default info; others: debug,warn,tracepidfile=/var/run/supervisord.pid ; supervisord pidfile; default supervisord.pidnodaemon=false               ; start in foreground if true; default falseminfds=1024                  ; min. avail startup file descriptors; default 1024minprocs=200                 ; min. avail process descriptors;default 200;umask=022                   ; process file creation umask; default 022;user=chrism                 ; default is current user, required if root;identifier=supervisor       ; supervisord identifier, default is 'supervisor';directory=/tmp              ; default is not to cd during start;nocleanup=true              ; don't clean up tempfiles at start; default false;childlogdir=/tmp            ; 'AUTO' child log dir, default $TEMP;environment=KEY="value"     ; key value pairs to add to environment;strip_ansi=false            ; strip ansi escape codes in logs; def. false; The rpcinterface:supervisor section must remain in the config file for; RPC (supervisorctl/web interface) to work.  Additional interfaces may be; added by defining them in separate [rpcinterface:x] sections.[rpcinterface:supervisor]supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface; The supervisorctl section configures how supervisorctl will connect to; supervisord.  configure it match the settings in either the unix_http_server; or inet_http_server section.[supervisorctl]serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL  for a unix socket;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket;username=chris              ; should be same as in [*_http_server] if set;password=123                ; should be same as in [*_http_server] if set;prompt=mysupervisor         ; cmd line prompt (default "supervisor");history_file=~/.sc_history  ; use readline history if available; The sample program section below shows all possible program subsection values.; Create one or more 'real' program: sections to be able to control them under; supervisor.;[program:theprogramname];command=/bin/cat              ; the program (relative uses PATH, can take args);process_name=%(program_name)s ; process_name expr (default %(program_name)s);numprocs=1                    ; number of processes copies to start (def 1);directory=/tmp                ; directory to cwd to before exec (def no cwd);umask=022                     ; umask for process (default None);priority=999                  ; the relative start priority (default 999);autostart=true                ; start at supervisord start (default: true);startsecs=1                   ; # of secs prog must stay up to be running (def. 1);startretries=3                ; max # of serial start failures when starting (default 3);autorestart=unexpected        ; when to restart if exited after running (def: unexpected);exitcodes=0,2                 ; 'expected' exit codes used with autorestart (default 0,2);stopsignal=QUIT               ; signal used to kill process (default TERM);stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10);stopasgroup=false             ; send stop signal to the UNIX process group (default false);killasgroup=false             ; SIGKILL the UNIX process group (def false);user=chrism                   ; setuid to this UNIX account to run the program;redirect_stderr=true          ; redirect proc stderr to stdout (default false);stdout_logfile=/a/path        ; stdout log path, NONE for none; default AUTO;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB);stdout_logfile_backups=10     ; # of stdout logfile backups (0 means none, default 10);stdout_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0);stdout_events_enabled=false   ; emit events on stdout writes (default false);stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB);stderr_logfile_backups=10     ; # of stderr logfile backups (0 means none, default 10);stderr_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0);stderr_events_enabled=false   ; emit events on stderr writes (default false);environment=A="1",B="2"       ; process environment additions (def no adds);serverurl=AUTO                ; override serverurl computation (childutils); The sample eventlistener section below shows all possible eventlistener; subsection values.  Create one or more 'real' eventlistener: sections to be; able to handle event notifications sent by supervisord.;[eventlistener:theeventlistenername];command=/bin/eventlistener    ; the program (relative uses PATH, can take args);process_name=%(program_name)s ; process_name expr (default %(program_name)s);numprocs=1                    ; number of processes copies to start (def 1);events=EVENT                  ; event notif. types to subscribe to (req'd);buffer_size=10                ; event buffer queue size (default 10);directory=/tmp                ; directory to cwd to before exec (def no cwd);umask=022                     ; umask for process (default None);priority=-1                   ; the relative start priority (default -1);autostart=true                ; start at supervisord start (default: true);startsecs=1                   ; # of secs prog must stay up to be running (def. 1);startretries=3                ; max # of serial start failures when starting (default 3);autorestart=unexpected        ; autorestart if exited after running (def: unexpected);exitcodes=0,2                 ; 'expected' exit codes used with autorestart (default 0,2);stopsignal=QUIT               ; signal used to kill process (default TERM);stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10);stopasgroup=false             ; send stop signal to the UNIX process group (default false);killasgroup=false             ; SIGKILL the UNIX process group (def false);user=chrism                   ; setuid to this UNIX account to run the program;redirect_stderr=false         ; redirect_stderr=true is not allowed for eventlisteners;stdout_logfile=/a/path        ; stdout log path, NONE for none; default AUTO;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB);stdout_logfile_backups=10     ; # of stdout logfile backups (0 means none, default 10);stdout_events_enabled=false   ; emit events on stdout writes (default false);stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB);stderr_logfile_backups=10     ; # of stderr logfile backups (0 means none, default 10);stderr_events_enabled=false   ; emit events on stderr writes (default false);environment=A="1",B="2"       ; process environment additions;serverurl=AUTO                ; override serverurl computation (childutils); The sample group section below shows all possible group values.  Create one; or more 'real' group: sections to create "heterogeneous" process groups.;[group:thegroupname];programs=progname1,progname2  ; each refers to 'x' in [program:x] definitions;priority=999                  ; the relative start priority (default 999); The [include] section can just contain the "files" setting.  This; setting can list multiple files (separated by whitespace or; newlines).  It can also contain wildcards.  The filenames are; interpreted as relative to this file.  Included files *cannot*; include files themselves.[include]files = /etc/supervisor/conf.d/*.conf

3)添加被管理应用nginx和tomcat配置文件 

 vim /etc/supervisord.d/tomcat.conf  
[program:tomcat-app]#程序唯一名称  directory=/usr/local/tomcat                             #程序路径  command=/usr/local/tomcat/bin/catalina.sh run           #运行程序的命令  autostart=true#是否在supervisord启动后tomcat也启动  startsecs=10#启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒  autorestart=true#程序退出后自动重启,可选值:[unexpected,true,false],默认为unexpected,表示进程意外杀死后才重启;意思为如果不是supervisord来关闭的该进程则认为不正当关闭,supervisord会再次把该进程给启动起来,只能使用该supervisorctl来进行关闭、启动、重启操作  startretries=3#启动失败自动重试次数,默认是3  user=root                                               #用哪个用户启动进程,默认是root  priority=999#进程启动优先级,默认999,假如Supervisord需要管理多个进程,那么值小的优先启动 stopsignal=INT  redirect_stderr=true#把stderr重定向到stdout标准输出,默认false  stdout_logfile_maxbytes=200MB#stdout标准输出日志文件大小,日志文件大小到200M后则进行切割,切割后的日志文件会标示为catalina.out1,catalina.out2,catalina.out3...,默认50MB stdout_logfile_backups =100#stdout标准输出日志文件备份数,保存100个200MB的日志文件,超过100个后老的将被删除,默认为10保存10个 stdout_logfile=/usr/local/tomcat/logs/catalina.out#标准日志输出位置,如果输出位置不存在则会启动失败  stopasgroup=false#默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程  killasgroup=false#默认为false,向进程组发送kill信号,包括子进程 [program:nginx-app]user=rootcommand = /bin/nginx -g 'daemon off;'stderr_logfile=/tmp/nginxapp.err.logstdout_logfile=/tmp/nginxapp.out.log

注意:通过 fork/exec 的方式把这些被管理的进程当作supervisor的子进程来启动,如此只要在supervisor的配置文件中,把要管理的进程的可执行文件的路径写进去即可。也实现当子进程挂掉的时候,父进程可以准确获取子进程挂掉的信息的,可以选择是否自己启动和报警。supervisor还提供了一个功能,可以为supervisord或者每个子进程,设置一个非root的user,这个user就可以管理它对应的进程。

3、启动supervisord

使用supervisord管理启动后,当使用/usr/local/tomcat/shutdown.sh或者kill $PID时,supervisord都当是意外关闭,会自动再次把进程启动,除非是使用supervisord命令关闭。

supervisord -c /etc/supervisord.conf  

注意:启动supervisord后,配置文件中设置了 autostart=true 参数,配置的应用也会随之启动。

1)单个程序管理命令

supervisorctl status tomcat-app                            supervisorctl stop tomcat-app                                 supervisorctl start tomcat-app                                supervisorctl restart tomcat-app                             supervisorctl reoload tomcat-app

注意:tomcat-app是配置文件中名字。

2)所有程序管理命令

supervisorctl stop all                                 supervisorctl start all                                supervisorctl restart all                             supervisorctl reoload all                        

4、配置开机启动

1)添加服务文件

vim /usr/lib/systemd/system/supervisord.service  

添加文件内容如下:

[Unit]  Description=ProcessMonitoringandControlDaemon  After=rc-local.service nss-user-lookup.target  [Service] Type=forking  ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf  [Install]  WantedBy=multi-user.target  

2)设置开机启动

systemctl enable supervisord  systemctl is-enabled supervisord