Supervisor 入坑指南

介绍

Supervisor 是一个由 Python 实现,基于 client/server 模型的系统,用于监控和管理进程。目前,只支持在 *inx 系统下运行。

它主要由四个组件组成,分别是:

  • supervisord(server 端)
  • supervisorctl(client 端)
  • XML-RPC API (client 端)
  • Web UI(client 端)

使用场景

  • 保证服务的可用(autostart=true,autorestart=unexpected)
  • 多进程(numprocs=num,num>1)
  • 后台进程(没使用 supervisord 之前,一般通过 nohup command & 实现)

安装

这里使用 pip 安装 supervisor。没有安装 pip 的话,使用下面的步骤安装。已有请忽略。

# 安装 pip
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

# 使用 pip 安装 supervisor
$ sudo pip install supervisor

使用

配置及启动 supervisord

# 创建需要的目录结构
$ sudo mkdir -pv /etc/supervisor.d/conf.d

# 生成默认的配置文件
$ sudo echo_supervisord_conf > /etc/supervisor.d/supervisord.conf

# 添加示例配置
$ sudo cat > /etc/supervisor.d/conf.d/example.conf << "EOF"[program:example]
process_name=%(program_name)s_%(process_num)02d
command=/path/to/command
autostart=true
autorestart=true
user=www
numprocs=4
redirect_stderr=true
stdout_logfile=/var/log/supervisor/example.log
EOF

# 启动 supervisord
$ sudo supervisord -c /etc/supervisor.d/supervisord.conf

启动 supervisord 之后,会产生如下的进程:

$ pstree -auns `pgrep supervisor`
systemd
  └─/usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
      ├─/path/to/command
      ├─/path/to/command
      ├─/path/to/command
      └─/path/to/command

Supervisorctl 的简单使用

supervisorctl -c /etc/supervisord.conf

上面这个命令会进入 supervisorctl 的 shell 界面,然后可以执行不同的命令了:

# 查看程序状态
> status 

# 关闭 usercenter 程序
> stop usercenter 

 # 启动 usercenter 程序
> start usercenter       

 # 重启 usercenter 程序
> restart usercenter   

# 读取有更新(增加)的配置文件,不会启动新添加的程序
> reread                     

# 重启配置文件修改过的程序
> update                    

事件

Supervisord 示例配置

[eventlistener:event_listener]
command=php /path/to/examples/log.php
process_name=%(program_name)s_%(process_num)02d
numprocs=1
events=PROCESS_STATE_STARTING,TICK_5
autostart=true
autorestart=unexpected

事件处理脚本

<?php

require_once __DIR__ . '/vendor/autoload.php';

use Mtdowling\Supervisor\EventListener;
use Mtdowling\Supervisor\EventNotification;

$listener = new EventListener();
$listener->listen(function(EventListener $listener, EventNotification $event) {
    $listener->log($event->getEventName());
    $listener->log($event->getServer());
    $listener->log($event->getPool());
    // Try messing around with supervisorctl to restart processes and see what
    // data is available
    $listener->log(var_export($event->getData(), true));
    return true;
});

注意问题

1. 子进程不能是守护进程

对应错误: Exited too quickly

子进程在退出时,Supervisord 会收到 SIGCHLD 信号,接着去执行相应的操作。
而守护进程一般会在 fork 之后,exit 掉父进程。

2. 内存泄漏

  • valgrind
  • max_requests

附录

Handle SIGCHLD in C

// Via http://www.linuxquestions.org/questions/programming-9/how-a-father-process-know-which-child-process-send-the-signal
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void handler(int sig)
{
  pid_t pid;

  pid = wait(NULL);

  printf("Pid %d exited.\n", pid);
}

int main(void)
{
  signal(SIGCHLD, handler);

  if(!fork())
  {
    printf("Child pid is %d\n", getpid());
    exit(0);
  }
  printf("Parent pid is %d\n", getpid());

  getchar();
  return 0;
}

daemon.c

#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include "config.h"

#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif /* HAVE_SYS_FILE_H */

/*---------------------------------------------------------------------------*\
                              Static Routines
\*---------------------------------------------------------------------------*/

/* redirect_fds(): redirect stdin, stdout, and stderr to /dev/NULL */

static void redirect_fds()
{
   (void) close(0);
   (void) close(1);
   (void) close(2);

   if (open("/dev/null", O_RDWR) != 0)
   {
       syslog(LOG_ERR, "Unable to open /dev/null: %s", strerror(errno));
       exit(1);
   }

   (void) dup(0);
   (void) dup(0);
}

static int do_fork(void)
{
    int status = 0;

    switch(fork())
    {
        case 0:
            /* This is the child that will become the daemon. */
            break;

        case -1:
            /* Fork failure. */
            status = -1;
            break;

        default:
            /* Parent: Exit. */
            _exit(0);
    }

    return status;
}

/*---------------------------------------------------------------------------*\
                              Public Routines
\*---------------------------------------------------------------------------*/

int daemon(int nochdir, int noclose)
{
    int status = 0;

    openlog("daemonize", LOG_PID, LOG_DAEMON);

    /* Fork once to go into the background. */
    if((status = do_fork()) < 0 )
        ;

    /* Create new session */
    else if(setsid() < 0)               /* shouldn't fail */
        status = -1;

    /* Fork again to ensure that daemon never reacquires a control terminal. */
    else if((status = do_fork()) < 0 )
        ;

    else
    {
        /* clear any inherited umask(2) value */

        umask(0);

        /* We're there. */

        if(! nochdir)
        {
            /* Go to a neutral corner. */
            chdir("/");
        }

        if(! noclose)
            redirect_fds();
    }

    return status;
}

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,941评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,397评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,345评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,851评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,868评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,688评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,414评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,319评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,775评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,945评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,096评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,789评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,437评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,993评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,107评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,308评论 3 372
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,037评论 2 355

推荐阅读更多精彩内容