Photo by Felix Russell-Saw / Unsplash

Background

最近看到有其他人在用 Supervisor 來管理在 server 運行的程式. 看了一下感覺蠻方便的, 所以想說自己也來研究一下並且做個紀錄.

Installation

$ sudo apt-get install supervisor

Start

Supervisor is a client/server system that allows its users to control a number of processes on UNIX-like operating systems.

所以一開始我們需要有一個程式來讓 supervisor 來控制.

/home/ubuntu/test.py

from datetime import datetime
import time
import logging

while 1:
    time.sleep(1)
    print(datetime.now(),flush=True)
    logging.warning('Watch out!')

config of supervisor

$ sudo vim /etc/supervisor/conf.d/test.conf

/etc/supervisor/conf.d/test.conf

[program:test]
command=python3 /home/ubuntu/test.py
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisor/test.err.log
stdout_logfile=/var/log/supervisor/test.out.log

稍微說明一下 conf 文件:

  • autostart: 表示系統開機或是重開機時要自動執行這個 command.

  • autorestart:

    • false: 程式執行結束或是因為error而停止時都不須自動重啟
    • ture: 程式執行結束或是因為error而停止時都須自動重啟.
    • unexpected 程式執行因為error而停止時須自動重啟.
  • stderr_logfile & stdout_logfile: errot log & 一般log放置的路徑.

一但 configuration 有變更的時候, 這時候我們還需要透過以下 supervisorctl 指令來告知 Supervisor.

$ sudo supervisorctl reread
$ sudo supervisorctl update

可以利用help & status 來取得幫助

$ sudo supervisorctl help

default commands (type help <topic>):
=====================================
add    exit      open  reload  restart   start   tail
avail  fg        pid   remove  shutdown  status  update
clear  maintail  quit  reread  signal    stop    version
$ sudo supervisorctl status
test                             RUNNING   pid 5762, uptime 0:13:42

最後可以看Log檔會出現以下訊息. 有看到訊息就表示沒問題了.

$ cd /var/log/supervisor
$ tail -f test.err.log
WARNING:root:Watch out!
WARNING:root:Watch out!
WARNING:root:Watch out!
WARNING:root:Watch out!
WARNING:root:Watch out!
$ tail -f test.out.log
2018-04-27 05:19:14.531236
2018-04-27 05:19:15.532579
2018-04-27 05:19:16.533923
2018-04-27 05:19:17.535284
2018-04-27 05:19:18.536625
2018-04-27 05:19:19.537982

Reference