简述:

Supervisor 是用Python开发的通用进程管理程序,能将一个普通的命令行进程变为其子进程,并监控进程状态,异常退出时能自动重启。通过fork/exec的方式将这些被管理的进程当作supervisor的子进程来启动,允许其用户控制类似UNIX的操作系统上的许多进程。Supervisord将进程作为其子进程启动,并且可以配置为在崩溃时自动重新启动它们。也可以将其自动配置为自行调用启动进程。被管理进程被视为supervisor的子进程,若该子进程异常中断,则父进程可以准确的获取子进程异常中断的信息,通过在配置文件中配置 autostart=ture,来实现对异常退出的子进程进行自动重启。

一、安装

安装Supervisor 官方有两种,详细参见 Installing,我通过离线方式安装 Supevisor ,需要准备 依赖:[meld3-2.0.1.tar.gz] (meld3软件包不再是Supervisor 4.1.0以后版本的依赖项,即不需要安装)(https://files.pythonhosted.org/packages/53/af/5b8b67d04a36980de03505446d35db39c7b2a01b9bac1cb673434769ddb8/meld3-2.0.1.tar.gz)
以及Supervisor 源码包,Supervisor

1.1 安装环境要求:

  1. CentOS 7 默认安装
  2. Python 2.4+ 即可,本地 Python 2.7.5 (default, Oct 30 2018, 23:45:53)
  3. Supervisor-4.1.0.tar.gz 源码文件

1.2 Supervisor 安装:

1. 解压源码包

// 解压Supervisor 源码包
[root@localhost Supervisor]# tar -xvf supervisor-4.1.0.tar.gz
[root@localhost Supervisor]# cd supervisor-4.1.0/
[root@localhost supervisor-4.1.0]# ls
CHANGES.rst    docs          MANIFEST.in  setup.cfg  supervisor
COPYRIGHT.txt  LICENSES.txt  README.rst   setup.py   tox.ini

2. 源码安装Supervisor 应用

[root@localhost supervisor-4.1.0]# python setup.py install
......
Installed /usr/lib/python2.7/site-packages/supervisor-4.1.0-py2.7.egg
Processing dependencies for supervisor==4.1.0
Finished processing dependencies for supervisor==4.1.0 # 安装完成

3. 安装meld 依赖

Supervisor 4.1.0 以前的版本会要求该依赖,否则会安装 Error,安装方法如下:

[root@localhost supervisor-4.1.0]# cd ../meld3-2.0.1/
[root@localhost meld3-2.0.1]# python setup.py install
....
Installed /usr/lib/python2.7/site-packages/meld3-2.0.1-py2.7.egg
Processing dependencies for meld3==2.0.1
Finished processing dependencies for meld3==2.0.1

二、supervisord 配置文件

默认没有配置文件,我们可以通过 echo_supervisord_conf,生成默认的Supervisor 配置文件;

[root@localhost meld3-2.0.1]# mkdir /etc/supervisord
[root@localhost meld3-2.0.1]# echo_supervisord_conf > /etc/supervisord/supervisord.conf

默认参数解析:

[root@localhost meld3-2.0.1]# cat /etc/supervisord/supervisord.conf
; 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 ".
;
; 注意上面的提示:- 配置文件不支持Shell 的声明、环境变量,可以通过 "%(ENV_HOME)s"使用变量
;     			 - 不支持引号的值,可以通过等号(=)赋值,如 environment= options
;				 - 注释至少有一个空格 如 a=b ; 给a赋值
;				 - 如果命令中有; 将会被截断,后面的会被理解为注释

配置文件字段含义

字段含义
[unix_http_server]
file=/tmp/supervisor.sock; socket 文件的默认路径,注,有的系统会自动删除/tmp目录下的文件
;chmod=0700; socket 文件的权限 (default 0700)
;chown=nobody:nogroup; socket 的所属组和所有人
;username=user; default is no username (open server)连接socket 的用户名
;password=123; default is no password (open server)连接socket 的密码
;[inet_http_server]; inet (TCP) server disabled by default;HTTP服务器,提供web管理界面
;port=127.0.0.1:9001; ip_address:port specifier, *:port for all iface;Web管理后台运行的IP和端口,如果开放到公网,需要注意安全性
;username=user; default is no username (open server)
;password=123; default is no password (open server)
[supervisord]#Supervisord 进程配置
logfile=/tmp/supervisord.log; default $CWD/supervisord.log # 日志路径
logfile_maxbytes=50MB; default 50MB #单个日志大小
logfile_backups=10; 0 means none, default 10 #备份日志数量
loglevel=info; default info; others: debug,warn,trace #日级别
pidfile=/tmp/supervisord.pid; default supervisord.pid #pid 文件
nodaemon=false; start in foreground if true; default false # 是否以daemon 运行
minfds=1024; min. avail startup file descriptors; default 1024 #最小文件打开数
minprocs=200; min. avail process descriptors;default 200 #最小进程描述
;umask=022; process file creation umask; default 022 #进程文件的umask值
;user=supervisord; setuid to this UNIX account at startup; recommended 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 #不清理/tmp
;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 # 日志删除ansi码
[supervisorctl]supervisorctl 管理命令
serverurl=unix:///tmp/supervisor.sock; 通过UNIX socket连接supervisord,路径与unix_http_server部分的file一致
;serverurl=http://127.0.0.1:9001; 通过http 连接supervisord
;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 # 历史记录
;[program:theprogramname]被监控进程
;command=/bin/cat; 启动程序的命令
;process_name=%(program_name)s; 声明的变量
;numprocs=1; (def 1)启动的进程数
;directory=/tmp; 执行之前切换到该目录
;umask=022; (default None)进程的umask值
;priority=999; (default 999)启动的相对优先级,默认999
;autostart=true; (default: true)在supervisord启动时也自动启动
;startsecs=1; (def. 1)进程启动1秒后没有异常退出,就表示进程正常启动了,默认1秒
;startretries=3; (default 3)重新启动失败后,尝试的次数
;autorestart=true; (def: unexpected)程序退出后自动重启,默认为unexpected,表示进程意外杀死后才重启
;exitcodes=0; 自动重启使用的错误代码(default 0)
;stopsignal=QUIT; 向结束进程发送的信号 (default TERM)
;stopwaitsecs=10; 最大的停止等待时间 (default 10)
;stopasgroup=false; 进程被杀死时,是否向这个进程组发送stop信号,包括子进程 (default false)
;killasgroup=false; 向进程组发送kill信号,包括子进程 (def false)
;user=chrism; 运行程序的用户
;redirect_stderr=true; 重定向错误日志到标准输出 (default false)
;stdout_logfile=/a/path; 标准输出路径; default AUTO
;stdout_logfile_maxbytes=1MB; 标准输出日志的大小 (default 50MB)
;stdout_logfile_backups=10; 标准输出日志的备份数 (0 means none, default 10)
;stdout_capture_maxbytes=1MB; 在’capturemode’ 模式下,最大的字节数(default 0)
;stdout_events_enabled=false; 在标准输出写入时发出事件(default false)
;stdout_syslog=false; 使用进程名称将stderr发送到syslog(default false)
;stderr_logfile=/a/path; stderr 日志路径, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB; stderr日志大小 (default 50MB)
;stderr_logfile_backups=10; stderr日志文件备份数 (0 means none, default 10)
;stderr_capture_maxbytes=1MB; 在’capturemode’捕获的字节数 (default 0)
;stderr_events_enabled=false; 在stderr写入时发出事件 (default false)
;stderr_syslog=false; 发送 stderr to syslog with process name (default false)
;environment=A=“1”,B=“2”; 添加进程的环境变量(def no adds)
;serverurl=AUTO; 覆盖 serverurl 计算 (childutils)
;[include]使用额外的配置文件
;files = relative/directory/*.ini配置文件

注:参数修改后需要重现加载配置文件,新的配置参数才会生效;supervisorctl -c supervisor.conf reload

最小化的supervisor 配置文件:

[root@localhost supervisord]# cat /etc/supervisord/supervisord.conf 
[unix_http_server]
file=/var/run/supervisor.sock   ; the path to the socket file
username=users              ; default is no username (open server)
password=123456               ; default is no password (open server)
[inet_http_server]         ; inet (TCP) server disabled by default
port=*:9003        ; 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=/opt/supervisor/log/supervisord.log ; main log file; default $CWD/supervisord.log
logfile_maxbytes=10MB        ; max main logfile bytes b4 rotation; default 50MB
logfile_backups=10           ; # of main logfile backups; 0 means none, default 10
loglevel=info                ; log level; default info; others: debug,warn,trace
pidfile=/var/run/supervisord.pid ; supervisord pidfile; default supervisord.pid
nodaemon=false               ; start in foreground if true; default false
minfds=1024                  ; min. avail startup file descriptors; default 1024
minprocs=200                 ; min. avail process descriptors;default 200
umask=022                   ; process file creation umask; default 022
directory=/opt/supervisor          ; default is not to cd during start
nocleanup=true              ; don't clean up tempfiles at start; default false
childlogdir=/opt/supervisor/process            ; 'AUTO' child log dir, default $TEMP
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL  for a unix socket
username=users              ; should be same as in [*_http_server] if set
password=123456                ; should be same as in [*_http_server] if set
history_file=/opt/supervisor/.sc_history  ; use readline history if available
[include]
files = relative/directory/*.ini

更多的配置参数详见 Supervisor Configuration

三、常用命令

1. supervisord 命令

[root@localhost Supervisor]# supervisord -h
supervisord -- run a set of applications as daemons.

Usage: /usr/bin/supervisord [options]

Options:
-c/--configuration FILENAME  指定配置文件启动
-n/--nodaemon -- 运行在前台 (same as 'nodaemon=true' in config file)
-h/--help -- 帮助
-v/--version -- 版本信息
-u/--user USER -- 运行的用户
-m/--umask UMASK -- use this umask for daemon subprocess (default is 022)
-d/--directory DIRECTORY -- directory to chdir to when daemonized
-l/--logfile FILENAME -- use FILENAME as logfile path
-y/--logfile_maxbytes BYTES -- use BYTES to limit the max size of logfile
-z/--logfile_backups NUM -- number of backups to keep when max bytes reached
-e/--loglevel LEVEL -- use LEVEL as log level (debug,info,warn,error,critical)
-j/--pidfile FILENAME -- write a pid file for the daemon process to FILENAME
-i/--identifier STR -- identifier used for this instance of supervisord
-q/--childlogdir DIRECTORY -- the log directory for child process logs
-k/--nocleanup --  prevent the process from performing cleanup (removal of
                   old automatic child log files) at startup.
-a/--minfds NUM -- the minimum number of file descriptors for start success
-t/--strip_ansi -- strip ansi escape codes from process output
--minprocs NUM  -- the minimum number of processes available for start success
--profile_options OPTIONS -- run supervisord under profiler and output
                             results based on OPTIONS, which  is a comma-sep'd
                             list of 'cumulative', 'calls', and/or 'callers',
                             e.g. 'cumulative,callers')

2.supervisord 管理

supervisor安装完成后会生成三个执行程序:supervisortd、supervisorctl、echo_supervisord_conf,分别是supervisor的守护进程服务(用于接收进程管理命令)、客户端(用于和守护进程通信,发送管理进程的指令)、生成初始配置文件程序。

2.1. 启动supervisord

[root@localhost supervisord]# supervisord -c /etc/supervisord/supervisord.conf
[root@localhost supervisord]# ps -ef | grep super
root     109841      1  0 15:38 ?        00:00:00 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord/supervisord.conf

2.2. 关闭supervisord

$supervisorctl shutdown

2.3. 重新加载配置文件,重启supervisor

$supervisorctl reload

2.5.启动某个进程

supervisorctl start program_name

2.6.查看正在监控的进程

supervisorctl

2.7.停止监控进程 (program_name)

supervisorctl stop program_name

2.8.重启监控进程 (program_name)

supervisorctl restart program_name

2.9.停止全部进程

supervisorctl stop all
注:用stop停止掉的进程,用reload或者update不会自动重启。

2.10. 更新新的配置文件,不需要重启

supervisorctl update #更新配置

3. 启用web管理控制台

  1. 修改配置文件,取消如下注释:

    [inet_http_server]         ; inet (TCP) server disabled by default
    port=*:9003        ; ip_address:port specifier, *:port for all iface
    username=admin              ; default is no username (open server)
    password=123456               ; default is no password (open server)
    
  2. 重新加载配置文件

    [root@localhost supervisord]# supervisorctl reload
    Restarted supervisord
    
  3. 登录Web 管理控制台
    在这里插入图片描述

四、Systemd管理Supervisor服务

Linux发行版本的启动脚本:Linux发行版开机启动脚本
在CentOS 7+ 下:

  1. 添加services文件:

    # supervisord service for systemd (CentOS 7.0+)
    # by ET-CS (https://github.com/ET-CS)
    [Unit]
    Description=Supervisor daemon
    
    [Service]
    Type=forking
    ExecStart=/usr/bin/supervisord -c /etc/supervisord/supervisord.conf
    ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown
    ExecReload=/usr/bin/supervisorctl $OPTIONS reload
    KillMode=process
    Restart=on-failure
    RestartSec=42s
    
    [Install]
    WantedBy=multi-user.target
    
  2. 加入开机启动

    [root@localhost ~]# systemctl enable supervisord.service
    

到此为止,Supervisor 进程管理工具,就部署好了,对于实际的使用更多的,需要我们根据自己的需求场景来定制这个工具,同时也欢迎各位Linux prober 留言交流。

参考:

  1. Linux运维工具Supervisor(进程管理工具)
Logo

更多推荐