非常實用的Linux 進程監控工具---Supervisor(一)

簡述:

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(進程管理工具)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章