用Supervisord管理進程

來源:互聯網
上載者:User

標籤:python   supervisord   

Supervisord是用Python實現的一款非常實用的進程管理工具,類似於monit。

Monit和Supervisord的一個比較大的差異是Supervisord管理的進程必須由Supervisord來啟動,Monit可以管理已經在啟動並執行程式。

Supervisord還要求管理的程式是非Daemon程式,Supervisord會幫你把它轉成Daemon程式,因此如果用Supervisord來管理Nginx的話,必須在Nginx的設定檔裡添加一行設定Daemon off讓Nginx以非Daemon方式啟動。


一、Supervisord安裝

        Supervisord可以通過easy_install supervisor安裝,當然也可以通過Supervisord官網下載後setup.py install安裝。也可以通過其他包管理來安裝,比如apt/yum等。

        我這裡用easy_install supervisor來安裝:

# yum install python-setuptools

# easy_install supervisor

        安裝好以後,有兩個可執行檔和一個指令檔
/usr/bin/supervisord             --  supervisor服務守護進程
/usr/bin/supervisorctl           --  supervisor服務控製程序,比如:status/start/stop/restart xx 等

/usr/bin/echo_supervisord_conf   --  supervisor產生設定檔範例

# echo_supervisord_conf > /etc/supervisord.conf  -- 組建組態檔案


二、Supervisor配置
#vi /etc/supervisord.conf[unix_http_server]          ; supervisord的unix socket服務配置file=/tmp/supervisor.sock   ; socket檔案的儲存目錄;chmod=0700                 ; socket的檔案許可權 (default 0700);chown=nobody:nogroup       ; socket的擁有者和組名;username=user              ; 預設不需要登陸使用者 (open server);password=123               ; 預設不需要登陸密碼 (open server)[inet_http_server]         ; supervisord的tcp服務配置; Web管理介面設定port=127.0.0.1:9001        ; tcp連接埠username=user              ; tcp登陸使用者password=123               ; tcp登陸密碼[supervisord]                ; supervisord的主進程配置logfile=/tmp/supervisord.log ; 主要的進程日誌配置logfile_maxbytes=50MB        ; 最大日誌體積,預設50MBlogfile_backups=10           ; 記錄檔備份數目,預設10loglevel=info                ; 記錄層級,預設info; 還有:debug,warn,tracepidfile=/tmp/supervisord.pid ; supervisord的pidfile檔案nodaemon=false               ; 是否以守護進程的方式啟動minfds=1024                  ; 最小的有效檔案描述符,預設1024minprocs=200                 ; 最小的有效進程描述符,預設200;umask=022                   ; 進程檔案的umask,預設200;user=chrism                 ; 預設為目前使用者,如果為root則必填;identifier=supervisor       ; supervisord的表示符, 預設時'supervisor';directory=/tmp              ; 預設不cd到目前的目錄;nocleanup=true              ; 不在啟動的時候清除臨時檔案,預設false;childlogdir=/tmp            ; ('AUTO' child log dir, default $TEMP);environment=KEY=value       ; 初始索引值對傳遞給進程;strip_ansi=false            ; (strip ansi escape codes in logs; def. false)[supervisorctl]serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL  for a unix socket;username=chris              ; 如果設定應該與http_username相同;password=123                ; 如果設定應該與http_password相同;prompt=mysupervisor         ; 命令列提示符,預設"supervisor";history_file=~/.sc_history  ; 命令列曆史紀錄; 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; 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    ; 啟動並執行程式 (相對使用PATH路徑, 可以使用參數);process_name=%(program_name)s ; 進程名運算式,預設為%(program_name)s;numprocs=1                    ; 預設啟動的進程數目,預設為1;events=EVENT                  ; event notif. types to subscribe to (req'd);buffer_size=10                ; 事件緩衝區隊列大小,預設10;directory=/tmp                ; 在運行前cwd到指定的目錄,預設不執行cmd;umask=022                     ; 進程umask,預設None;priority=-1                   ; 程式啟動並執行優先順序,預設-1;autostart=true                ; 預設隨supervisord自動啟動,預設true;autorestart=unexpected        ; whether/when to restart (default: unexpected);startsecs=1                   ; number of secs prog must stay running (def. 1);startretries=3                ; max # of serial start failures (default 3);exitcodes=0,2                 ; 期望的退出碼,預設0,2;stopsignal=QUIT               ; 殺死進程的訊號,預設TERM;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10);stopasgroup=false             ; 向unix進程組發送停止訊號,預設false;killasgroup=false             ; 向unix進程組發送SIGKILL訊號,預設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 (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)[group:appgroup]programs=wapp,wfapp           ; 任何在[program:x]中定義的x;priority=999                  ; 程式啟動並執行優先順序,預設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 = relative/directory/*.ini; 管理的單個進程的配置,可以添加多個program[program:cobar]; 被監控程式指定的運行指令碼; 如果command的欄啟動並執行是shell指令碼,那麼在shell 指令碼啟動被監控程式時要用exec修飾。例如:;   echo $RUN_CMD;   eval exec $RUN_CMD; 否則,supervisord停止不了啟動的進程.除此之外,shell指令碼裡不能出現&之類的後台運行符號command=/bin/sh /home/jfy/soft/cobar-server-1.2.7/bin/startup2.sh  ;process_name=%(program_name)s ; 進程名運算式,預設為%(program_name)s;numprocs=1                    ; 預設啟動的進程數目,預設為1directory=/home/jfy/soft/cobar-server-1.2.7/bin                    ; 在運行前cwd到指定的目錄,預設不執行cmd;umask=022                     ; 進程umask,預設Nonepriority=1                    ; 程式啟動並執行優先順序,預設999autostart=true                ; 預設隨supervisord自動啟動,預設trueautorestart=true              ; 被監控程式異常中斷是否自動重啟startsecs=5                   ; 被監控程式啟動時期間startretries=5                ; 被監控程式啟動失敗重試的次數;exitcodes=0,2                 ; 期望的退出碼,預設0,2;stopsignal=QUIT               ; 殺死進程的訊號,預設TERM;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10);stopasgroup=false             ; 向unix進程組發送停止訊號,預設false;killasgroup=false             ; 向unix進程組發送SIGKILL訊號,預設false;user=root                     ; 為運行程式的unix帳號設定setuidredirect_stderr=true          ; 將標準錯誤重新導向到標準輸出,預設falsestdout_logfile=/home/jfy/soft/cobar-server-1.2.7/logs/console.log        ; stdou 重新導向輸出檔案;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)[program:cardapi]command=/usr1/app/run/CARDAPI /usr1/app/ini/cardapi.ini /usr1/app/log/cardapi.trpriority=1numprocs=1autostart=trueautorestart=true; 配置一組進程,對於類似的program可以通過這種方式添加,避免手工一個個添加;[program:bsapp];command=/usr1/app/run/%(program_name)s_%(process_num)02d wapp /usr1/app/log/%(program_name)s_%(process_num)02d.tr;numprocs=3;process_name=%(program_name)s_%(process_num)02d;autostart=true;autorestart=true</span><span style="font-family: 微軟雅黑, 'Microsoft YaHei', Oswald, 'Helvetica Neue', Helvetica, Verdana, arial, sans-serif;">
(更多配置說明請參考:http://supervisord.org/configuration.html)

三、Supervisor管理

Supervisord安裝完成後有兩個可用的命令列supervisor和supervisorctl。


啟動Supervisord
# supervisord
啟動時指定設定檔
# supervisord -c /etc/supervisord.conf


# supervisord --helpsupervisord -- run a set of applications as daemons.Usage: /usr/bin/supervisord [options]Options:-c/--configuration FILENAME -- configuration file-n/--nodaemon -- run in the foreground (same as 'nodaemon true' in config file)-h/--help -- print this usage message and exit-v/--version -- print supervisord version number and exit-u/--user USER -- run supervisord as this user (or numeric uid)-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')

supervisorctl命令列控製程序

# supervisorctlappgroup:wapp                    RUNNING   pid 42981, uptime 0:01:45appgroup:wfapp                   RUNNING   pid 42982, uptime 0:01:45cardapi                          RUNNING   pid 33133, uptime 1:02:32cobar                            RUNNING   pid 6761, uptime 22:43:42gearmand                         RUNNING   pid 6743, uptime 22:43:53memcached                        RUNNING   pid 6728, uptime 22:44:05supervisor> helpdefault commands (type help <topic>):=====================================add    clear  fg        open  quit    remove  restart   start   stop  update avail  exit   maintail  pid   reload  reread  shutdown  status  tail  versionstop <name>      停止某一個進程(name),name為[program:cobar]裡配置的值,這個樣本就是cobar。 start <name>     啟動某個進程 restart <name>   重啟某個進程 stop <gname>:*   重啟屬於名為gname這個分組的進程(start,restart同理) ,如:stop appgroup:wappstop all         停止全部進程,註:start、restart、stop都不會載入最新的設定檔。 reload           載入最新的設定檔,停止原有進程並按新的配置啟動、管理所有進程。 update           根據最新的設定檔,啟動新配置或有改動的進程,配置沒有改動的進程不會受影響而重啟。 注意:顯示用stop停止掉的進程,用reload或者update都不會自動重啟。

OK,基本的操作就是類似這個了


supervisor還支援以WEB方式監控管理進程
找到[inet_http_server]這一段,修改成

[inet_http_server]         ; inet (TCP) server disabled by defaultport=*:9001                ; (ip_address:port specifier, *:port for all iface)username=admin             ; (default is no username (open server))password=123               ; (default is no password (open server))
其中port這個欄位要各位注意,如果*:9001表示允許所有ip訪問,如果指定單個IP可以 xx.xx.xx.xx:9001 這樣既可。如果你開啟了iptabls記得要在規則裡允許port指定的連接埠號碼。


然後儲存配置,重啟supervisord
# supervisord reload

啟用瀏覽器訪問效果:



用Supervisord管理進程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.