supervisor托管程序开机自启

发布时间 2023-10-10 10:36:47作者: 小糊涂90

1.supervisor简介

#Supervisor是用Python开发的一套通用的进程管理程序,能将一个普通的命令行进程变为后台daemon,并监控进程状态,异常退出时能自动重启。它是通过fork/exec的方式把这些被管理的进程当作supervisor的子进程来启动,这样只要在supervisor的配置文件中,把要管理的进程的可执行文件的路径写进去即可。也实现当子进程挂掉的时候,父进程可以准确获取子进程挂掉的信息的,可以选择是否自己启动和报警。

2.supervisor安装

[root@localhost cenborder]#yum install -y epel-release
[root@localhost cenborder]# yum list |grep supervisor
supervisor.noarch                        3.4.0-1.el7                   @epel    
nodejs-supervisor.noarch                 0.6.0-2.el7                   epel 
[root@localhost cenborder]# yum install -y supervisor.noarch
[root@localhost cenborder]# systemctl enable --now supervisord.service 
Created symlink from /etc/systemd/system/multi-user.target.wants/supervisord.service to /usr/lib/systemd/system/supervisord.service.
[root@localhost cenborder]# systemctl status supervisord.service 
● supervisord.service - Process Monitoring and Control Daemon
   Loaded: loaded (/usr/lib/systemd/system/supervisord.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2023-01-05 17:32:36 CST; 2s ago
  Process: 11343 ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf (code=exited, status=0/SUCCESS)
 Main PID: 11346 (supervisord)
    Tasks: 1
   Memory: 11.2M
   CGroup: /system.slice/supervisord.service
           └─11346 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf

Jan 05 17:32:36 localhost.localdomain systemd[1]: Starting Process Monitoring and Control Daemon...
Jan 05 17:32:36 localhost.localdomain systemd[1]: Started Process Monitoring and Control Daemon.
[root@localhost cenborder]# cat /etc/supervisord.conf
; Sample supervisor config file.

[unix_http_server]
file=/var/run/supervisor/supervisor.sock   ; (the path to the socket file)//unix socket文件
;chmod=0700                 ; sockef 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 //http服务器,提供web管理界面
;port=127.0.0.1:9001        ; (ip_address:port specifier, *:port for all iface) //监听ip和端口
;username=user              ; (default is no username (open server)) //登录管理后台的用户名
;password=123               ; (default is no password (open server))  //登录管理后台的密码

[supervisord]
logfile=/var/log/supervisor/supervisord.log  ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;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)
;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 below 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: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor/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
;两种连接方式,对应上面的[unix_http_server]和[inet_http_server] 
;username=chris              ; should be same as http_username if set
;password=123                ; should be same as http_password if set
;prompt=mysupervisor         ; cmd line prompt (default "supervisor")
;history_file=~/.sc_history  ; use readline history if available

; The below sample program section 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)
;autorestart=true              ; retstart at unexpected quit (default: true)
;startsecs=10                  ; number of secs prog must stay running (def. 1)
;startretries=3                ; max # of serial start failures (default 3)
;exitcodes=0,2                 ; 'expected' exit codes for process (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;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 (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 (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 below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more 'real'
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.

;[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)
;autorestart=unexpected        ; restart at unexpected quit (default: unexpected)
;startsecs=10                  ; number of secs prog must stay running (def. 1)
;startretries=3                ; max # of serial start failures (default 3)
;exitcodes=0,2                 ; 'expected' exit codes for process (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;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 (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        ; # of stderr logfile backups (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 below sample group section 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 = supervisord.d/*.ini

3.打开web管理界面

[root@localhost cenborder]# ss -tanl |grep 9001
LISTEN     0      1024         *:19001                    *:*                  
LISTEN     0      1024        :::19001                   :::*                  
[root@localhost cenborder]# vi /etc/supervisord.conf 
[inet_http_server]
port=127.0.0.1:9001
username=user
password=123 
[root@localhost cenborder]# systemctl restart supervisord.service 
[root@localhost cenborder]# ss -tanl |grep 9001
LISTEN     0      1024   127.0.0.1:9001                     *:*                  
LISTEN     0      1024         *:19001                    *:*                  
LISTEN     0      1024        :::19001                   :::*                  
[root@localhost cenborder]# curl localhost:9001
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code 401.
<p>Message: Unauthorized.
</body>
[root@localhost cenborder]# curl user:123@localhost:9001
...
      No programs to manage</form>
...

4.编辑redis服务的子配置文件

[root@localhost cenborder]# vi /etc/supervisord.d/redis.ini
[program:redis-server]
command=/usr/bin/redis-server /apps/redis/etc/redis.conf
priority=999                ; 优先级(越小越优先)
autostart=true              ; supervisord启动时,该程序也启动
autorestart=true            ; 异常退出时,自动启动
startsecs=10                ; 启动后持续10s后未发生异常,才表示启动成功
startretries=3              ; 异常后,自动重启次数
exitcodes=0,2               ; exit异常抛出的是0、2时才认为是异常
stopsignal=QUIT             ; 杀进程的信号
stopwaitsecs=10
user=redis                   ; 设置启动该程序的用户
log_stdout=true             ; 如果为True,则记录程序日志
log_stderr=false            ; 如果为True,则记录程序错误日志
logfile=/apps/redis/log/redis-server.log    ; 程序日志路径
logfile_maxbytes=1MB        ; 日志文件最大大小
logfile_backups=10          ; 日志文件最大数量

5.查看supervisorctl,验证redis是否启动

[root@localhost cenborder]# systemctl restart supervisord.service
[root@localhost cenborder]# supervisorctl
redis-server                     STARTING  
supervisor> status
redis-server                     RUNNING   pid 12132, uptime 0:10:39

[root@localhost cenborder]# ss -tnl |grep 6379
LISTEN     0      511    172.16.65.101:6379                     *:* 
[root@localhost cenborder]# redis-cli -a 123456 -h 172.16.65.101
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
172.16.65.101:6379> 

6.supervisor常用命令

supervisorctl status  //查看所有进程状态
supervisorctl stop redis-server    //停止
supervisorctl start redis-server    //启动
supervisorctl restart    //重启
supervisorctl update    //配置文件修改后使用该命令加载新的配置
supervisorctl reload    //重新穷配置中的所有程序
说明:把es换成all可以管理配置中的所有进程。直接输入supervisorctl进入supervisorctl的shell交互界面,此时上面的命令不带supervisorctl可直接使用

7.再次查看web界面

</html>[root@localhost cenborder]# curl user:123@localhost:9001
...
      <ul>
                <li>
                  <a href="index.html?processname=redis-server&amp;action=restart" name="Restart">Restart</a>
                </li>
              <li>
                  <a href="index.html?processname=redis-server&amp;action=stop" name="Stop">Stop</a>
                </li>
              <li>
                  <a href="index.html?processname=redis-server&amp;action=clearlog" name="Clear Log">Clear Log</a>
                </li>
              <li>
                  <a href="logtail/redis-server" name="Tail -f" target="_blank">Tail -f</a>
                </li>
              </ul>
...