配置 Supervisor 管理 Laravel 佇列

imcavoy發表於2019-01-13

原文:配置Supervisor管理Laravel佇列

安裝

可以用Python的pip工具進行安裝

sudo pip install supervisor

也可以使用Linux的包管理命令安裝

sudo apt-get install supervisor

配置

執行如下命令可以檢視預設的配置

echo_supervisord_conf

如果需要修改預設的配置,可以執行下面命令生成一個預設的配置檔案

echo_supervisord_conf > /etc/supervisord.conf

修改預設配置

預設配置檔案中的supervisord.socksupervisord.log以及supervisord.pid是放在/tmp目錄下,這個目錄存放的是Linux中的臨時檔案,一旦被系統刪除,就會提示unix:///tmp/supervisor.sock no such file,所以我們要把這三個檔案放到其他目錄中儲存。

此處注意中文註釋的幾個需要修改的地方

[unix_http_server]
;此處修改為/var/run目錄,避免被系統刪除
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]
;此處修改為/var/log/supervisor目錄
logfile=/var/log/supervisor/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
;此處修改為/var/run目錄
pidfile=/var/run/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 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]
;此處是關鍵,否則執行supervisorctl status會爆出unix:// not found錯誤
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,新增的配置將在/etc/supervisord.d/conf.d目錄下並以.conf結尾
[include]
files = /etc/supervisord.d/conf.d/*.conf

上面的一些目錄如果做了修改首先要建立這些目錄,並且賦予相應的許可權

sudo chmod 777 /var/run
sudo chmod 777 /var/log/supervisor

現在我們啟動服務

supervisord -c /etc/supervisord.conf

此處最好別用root許可權啟動,否則可能導致後面php artisan命令出錯

現在我們檢視程式

pgrep supervisord | xargs ps -u --pid
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root     13744  0.0  1.7 226320 17460 ?        Ss   1月12   0:08 /bin/python /usr/bin/supervisord -c /etc/supervisord.conf

具體專案配置

Supervisorctl 是 Supervisord 的一個命令列客戶端工具,啟動時需要指定與 Supervisord 使用同一份配置檔案

我們在上面預設配置檔案中加入了[include],所以我們在/etc/supervisord.d/conf.d下新建一個配置檔案larashop-worker.conf

[program:larashop-worker]  ;專案名稱
process_name=%(program_name)s_%(process_num)02d
command=php (填入你的artisan路徑)/artisan queue:work redis --sleep=3 --tries=3  ;需要啟動的命令
autostart=true
autorestart=true
user=root ;此處填入你執行WEB應用的使用者
numprocs=8  ;程式數
redirect_stderr=true  ;把 stderr 重定向到 stdout,預設 false
stdout_logfile=/var/log/supervisor/larashop-queue.log  ;注意分配好日誌資料夾許可權

配置完成後我們執行

supervisorctl reread  # 讀取有更新(增加)的配置檔案,不會啟動新新增的程式

supervisorctl update # 重啟配置檔案修改過的程式

supervisorctl start larashop-worker:* # 啟動 larashop-worker 程式

執行

supervisorctl status # 檢視狀態

看到

larashop-worker:larashop-worker_00   RUNNING   pid 13769, uptime 14:03:33
larashop-worker:larashop-worker_01   RUNNING   pid 13770, uptime 14:03:33
larashop-worker:larashop-worker_02   RUNNING   pid 13767, uptime 14:03:33
larashop-worker:larashop-worker_03   RUNNING   pid 13768, uptime 14:03:33
larashop-worker:larashop-worker_04   RUNNING   pid 13765, uptime 14:03:33
larashop-worker:larashop-worker_05   RUNNING   pid 13766, uptime 14:03:33
larashop-worker:larashop-worker_06   RUNNING   pid 13763, uptime 14:03:33
larashop-worker:larashop-worker_07   RUNNING   pid 13764, uptime 14:03:33

說明Laravel佇列已經開始正常執行了

如果在Laravel中修改了佇列程式碼,需要重啟Supervisor才能生效

可能出現的問題

1. ERROR (spawn error)

此時如果提示

larashop-worker:larashop-worker_00: ERROR (spawn error)
...

先檢查上述的日誌目錄有沒有許可權,如果許可權正常,則進入上面設定的日誌目錄檢視日誌檔案

我這裡進入var/log/supervisor檢視日誌檔案larashop-queue.conf

可以看到錯誤均為

PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in xxx/artisan on line 33

然後我進入Laravel目錄,使用

sudo php artisan 你的命令

執行artisan命令,同樣爆出這個錯誤。所以原因在於啟動supervisord和服務端的時候使用了root許可權導致

先將原來的程式kill掉,使用非root許可權重新執行服務端和客戶端即可成功執行

2. unix:///tmp/supervisor.sock no such file

在服務端配置檔案中將/tmp/supervisor.sock修改為var/run/supervisor.sock

3. supervisorctl start錯誤

執行supervisorctl start 你的專案名稱,遲遲不出結果,按ctrl+c後爆出錯誤

Traceback (most recent call last):
  File "/bin/supervisorctl", line 11, in <module>
  ...

建議kill掉supervisord的程式,然後重新用pip安裝一次,並重新配置一遍預設配置檔案

參考連結

本作品採用《CC 協議》,轉載必須註明作者和本文連結
玄霄

相關文章