supervisor入門教程|安裝|啓動|實戰環節

supervisor是什麼

是一個客戶端/服務器系統,允許其用戶在類UNIX操作系統上控制許多進程(官方解釋)。

簡單點來講,就是一個監控腳本運行的工具,不過他可以統一化管理,laravel的隊列文檔上也有相關使用方式方法,例如:

  • 定時腳本的啓動、重啓、關閉和日誌監控
  • swoole的啓動、重啓、關閉和日誌監控 (衆所周知,swoole大部分的特性都只能在cli中運行)
  • redis的啓動、重啓、關閉和日誌監控 (redis自身未提供類似phpmyadmin的後臺可視化工具)
  • laravel中的隊列、一些自動化的腳本、workman等等的腳本

supervisor安裝

環境說明

CentOS Linux release 7.5.1804 (Core)

安裝

安裝時需要使用到easy_install命令,所以我們先安裝它
yum install python-setuptools

正式安裝supervisor
easy_install supervisor

配置

Supervisor安裝後不會自動生成配置文件。
請使用命令echo_supervisord_conf > /etc/supervisor/supervisord.conf來生成配置文件。

默認配置文件需要修改幾項,下面是修改後的內容

[root@altc1-mytest1 work]# more /etc/supervisor/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=/tmp/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=0.0.0.0: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=/tmp/supervisord.log ; main log file; default $CWD/supervisord.log
logfile_maxbytes=50MB        ; 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=/tmp/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=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
;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:///tmp/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                   ; 'expected' exit codes used with autorestart (default 0)
;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)
;stdout_syslog=false           ; send stdout to syslog with process name (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)
;stderr_syslog=false           ; send stderr to syslog with process name (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                   ; 'expected' exit codes used with autorestart (default 0)
;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)
;stdout_syslog=false           ; send stdout to syslog with process name (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)
;stderr_syslog=false           ; send stderr to syslog with process name (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

備註:上面有一行files = /etc/supervisor/conf.d/*.conf類似於nginx管理子配置文件風格一樣,這個地方需要提前執行一下
mkdir -p /etc/supervisor/conf.d/

啓動

supervisord -c /etc/supervisor/supervisord.conf

停止

supervisorctl shutdown

重新加載配置文件

supervisorctl reload

實戰環節

安裝好supervisor之後,就可以找個應用程序託管嘗試了,我這裏選擇的是應用程序就是一個手寫的shell程序

模擬應用程序

# more /root/work/hello.sh
echo "start..."
i=0;
while (( $i < 5)) ; 
do echo `date '+%Y-%m-%d %H:%M:%S'` ; 
sleep 1; 
i=$(($i+1)) ; 
done;

具體應用程序配置

Supervisor 以 [program:[your_cli_name]]以每段進程配置文件的開頭,your_cli_name 則是你的進程名稱,名稱會顯示在Supervisor後臺管理工具和Supervisor cli命令輸出上。我們以運行hello.sh爲例

[program:hello]
command=sh /root/work/hello.sh

完整的配置如下

# more /etc/supervisor/conf.d/hello_test.conf
[program:hello]
command=sh /root/work/hello.sh
stdout_logfile=/tmp/hello.log
stderr_logfile=/tmp/hello_err.log
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=50
priority=1

備註:command後面的內容不能只寫/root/work/hello.sh,前面的sh必須加上喲

執行結果

# more /tmp/hello.log
start...
2019-04-25 02:43:20
2019-04-25 02:43:21
2019-04-25 02:43:22
2019-04-25 02:43:23
2019-04-25 02:43:24
start...
2019-04-25 02:43:26
2019-04-25 02:43:27
2019-04-25 02:43:28
2019-04-25 02:43:29
2019-04-25 02:43:30
start...
2019-04-25 02:43:33
2019-04-25 02:43:34
2019-04-25 02:43:35
2019-04-25 02:43:36
2019-04-25 02:43:37
start...
2019-04-25 02:43:41
2019-04-25 02:43:42
2019-04-25 02:43:43
2019-04-25 02:43:44
2019-04-25 02:43:45

備註:可以看到 supervisor會以子進程的形式執行hello.sh應用程序,hello.sh的邏輯是5秒後全部邏輯執行完成並退出,但是從日誌上看下面還有3部分相同的日誌,這是由於supervisor管理子進程時,如果發現子進程退出後,再嘗試重啓3次造成的

子進程配置手冊

;*爲必須填寫項
;*[program:應用名稱]
[program:cat]
;*命令路徑,如果使用python啓動的程序應該爲 python /home/test.py, 
;不建議放入/home/user/, 對於非user用戶一般情況下是不能訪問
command=/bin/cat
;當numprocs爲1時,process_name=%(program_name)s
;當numprocs>=2時,%(program_name)s_%(process_num)02d
process_name=%(program_name)s
;進程數量
numprocs=1
;執行目錄,若有/home/supervisor_test/test1.py
;將directory設置成/home/supervisor_test
;則command只需設置成python test1.py
;否則command必須設置成絕對執行目錄
directory=/tmp
;掩碼:--- -w- -w-, 轉換後rwx r-x w-x
umask=022
;優先級,值越高,最後啓動,最先被關閉,默認值999
priority=999
;如果是true,當supervisor啓動時,程序將會自動啓動
autostart=true
;*自動重啓
autorestart=true
;啓動延時執行,默認1秒
startsecs=10
;啓動嘗試次數,默認3次
startretries=3
;當退出碼是0,2時,執行重啓,默認值0,2
exitcodes=0,2
;停止信號,默認TERM
;中斷:INT(類似於Ctrl+C)(kill -INT pid),退出後會將寫文件或日誌(推薦)
;終止:TERM(kill -TERM pid)
;掛起:HUP(kill -HUP pid),注意與Ctrl+Z/kill -stop pid不同
;從容停止:QUIT(kill -QUIT pid)
;KILL, USR1, USR2其他見命令(kill -l),說明1
stopsignal=TERM
stopwaitsecs=10
;*以root用戶執行
user=root
;重定向
redirect_stderr=false
stdout_logfile=/a/path
stdout_logfile_maxbytes=1MB
stdout_logfile_backups=10
stdout_capture_maxbytes=1MB
stderr_logfile=/a/path
stderr_logfile_maxbytes=1MB
stderr_logfile_backups=10
stderr_capture_maxbytes=1MB
;環境變量設置
environment=A="1",B="2"
serverurl=AUTO

WEB控制檯管理

可以通過瀏覽器查看管理的子進程
在這裏插入圖片描述

參考文章
https://blog.csdn.net/nbczw8750/article/details/84881501

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章