您的位置 首页 golang

Golang服务器热重启 – 基于Shutdown和Supervisor

所谓 热重启, 就是当关闭一个正在运行的进程时,该进程并不会立即停止,而是会等待所有当前逻辑继续执行完毕,才会中断。这就要求我们的服务需要支持一条重启命令,通过该命令我们可以重启服务,并同时保证重启过程中正在执行的逻辑不会中断,且重启后可以继续正常服务。

在go 1.8.x后,golang在http.Server里加入了Shutdown方法,用来控制优雅退出。什么是优雅退出? 简单说就是不处理新请求,但是会处理正在进行的请求,把旧请求都处理完再退出。

我的项目更新代码流程为:使用http.server.Shutdown停机,Supervisor守护进程进行更新后的重启,shell脚本执行编译、copy到远程,重启Supervisor。在此记录以备日后查阅。

一、版本要求

  • Centos 7.0
  • Golang > 1.8

二、Shutdown Demo

新建文件 /home/www/test/shutdown-simple.go,写入如下代码:

package mainimport (    "context"    "fmt"    "log"    "net/http"    "os"    "os/signal"    "syscall"    "time")func main() {    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        time.Sleep(time.Second * 5)        fmt.Fprint(w, "hello world...")    })    var srv = http.Server{        Addr: ":8080",    }    idleConnsClosed := make(chan struct{})    go func() {        sigint := make(chan os.Signal, 1)        // kill (no param) default send syscall.SIGTERM        // kill -2 is syscall.SIGINT        // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it        signal.Notify(sigint,  syscall.SIGINT, syscall.SIGTERM)        <-sigint        // We received an interrupt signal, shut down.        if err := srv.Shutdown(context.Background()); err != nil {            // Error from closing listeners, or context timeout:            log.Printf("HTTP server Shutdown: %v", err)        }        close(idleConnsClosed)    }()    if err := srv.ListenAndServe(); err != http.ErrServerClosed {        // Error starting or closing listener:        log.Fatalf("HTTP server ListenAndServe: %v", err)    }    <-idleConnsClosed}

执行 go build shutdown-simple.go, 浏览器访问8080端口或终端执行 curl http://127.0.0.1:8080,立刻通过kill终止程序,依然会在5秒后返回'hello world…'。

三、Supervisor

Supervisor (http://supervisord.org) 是一个用 Python 写的进程管理工具,可以很方便的用来启动、重启、关闭进程(不仅仅是 Python 进程)。除了对单个进程的控制,还可以同时启动、关闭多个进程,比如很不幸的服务器出问题导致所有应用程序都被杀死,此时可以用 supervisor 同时启动所有应用程序而不是一个一个地敲命令启动。在本项目中,更新golang程序后,使用supervisor重启应用。

3.1 检查安装epel源

  • 检查 epel 是否已安装,如下已存在epel源,则不需要安装:
➜ yum repolist | grep epel!epel/x86_64               Extra Packages for Enterprise Linux 7 - x86_64 13,242
  • 如果不存在,则需要安装 epel
➜  yum -y install epel-release

3.2 安装Supervisor

//  安装➜ yum install supervisor// 开机启动➜ systemctl start supervisord.service// 重启➜ systemctl restart supervisord

3.3 配置Supervisor

Supervisor 的配置文件为:/etc/supervisord.conf ,打开配置文件在末尾可以看到:

...[include]files = supervisord.d/*.ini

即 Supervisor 所管理的应用的配置文件 /etc/supervisord.d/目录中,文件名以.ini结尾。
创建文件/etc/supervisord.d/test.ini

# 其中 [program:test] 中的 test 是应用程序的唯一标识,不能重复。# 对该程序的所有操作(start, restart 等)都通过名字来实现。[program:test]# 用哪个用户启动user=root# 启动的命令command=/home/www/test/shutdown-simple# 在 supervisord 启动的时候也自动启动autostart=true# 程序异常退出后自动重启autorestart=true# 启动 10 秒后没有异常退出,就当作已经正常启动了startsecs=10# 启动失败自动重试次数,默认是 3startretries = 3# stdout 日志文件名# stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)stdout_logfile=/home/logs/test.log# stdout 日志文件大小,默认 50MBstdout_logfile_maxbytes=1MB# stdout 日志文件备份数stdout_logfile_backups=10stdout_capture_maxbytes=1MBstderr_logfile=/home/logs/test.logstderr_logfile_maxbytes=1MBstderr_logfile_backups=10stderr_capture_maxbytes=1MBstopsignal=INT[supervisord]

添加 ini文件后,使用 supervisorctl 使配置生效。此时再次访问8080端口,并立刻kill进程,请求不会因为kill而中断,并且kill后使用lsof -i:8080发现又启动了新的进程。

3.4 使用 supervisorctl

Supervisorctl 是 supervisord 的一个命令行客户端工具,启动时需要指定与 supervisord 使用同一份配置文件,否则与 supervisord 一样按照顺序查找配置文件。supervisorctl 命令会进入 supervisorctl 的 shell 界面,进入界面后可以执行如下指令:

> status    # 查看程序状态> stop test   # 关闭 test 程序> start test  # 启动 test 程序> restart test    # 重启 test 程序> reread # 读取有更新(增加)的配置文件,不会启动新添加的程序> update    # 重启配置文件修改过的程序

上面这些命令都有相应的输出,除了进入 supervisorctl 的 shell 界面,也可以直接在终端运行:

➜ supervisorctl status➜ supervisorctl stop test➜ supervisorctl start test➜ supervisorctl restart test➜ supervisorctl reread➜ supervisorctl update

`

三、基于Shell脚本更新云服务器代码

代码更新流程:

  • 本地更新程序代码
  • 执行脚本/home/www/test/toremote.sh,完成编译并更新到云服务器
  • 触发云服务器上/home/www/test/codemonitor.sh,通过supervisor重启程序完成更新

PS:

  • supervisor 安装在云服务器上
  • 默认已开启ssh登录,配置了ssh config,dev为远程config中的别名
代码更新流程

本地脚本 /home/www/test/toremote.sh

#!/bin/bashCGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build shutdown-simple.goecho "build finished"scp ./shutdown-simple dev:/home/www/test/shutdown-simple_newecho "copy finished"ssh dev "/home/www/test/codemonitor.sh"echo "code updated"
# 增加可执行权限➜ chmod +x /home/www/test/toremote.sh

服务器脚本 /home/www/test/codemonitor.sh

#!/bin/bashdiff /home/www/test/shutdown-simple_new /home/www/test/shutdown-simpleif [ $? -ne 0 ]then        mv /home/www/test/shutdown-simple_new /home/www/test/shutdown-simple        echo "mv success"        supervisorctl restart test        echo "code restart success"fi
# 增加可执行权限➜ chmod +x /home/www/test/codemonitor.sh

测试

  • 更新本地代码:
...    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        time.Sleep(time.Second * 5)        fmt.Fprint(w, "bye~ bye~")    })...
  • 在本地执行编译更新 /home/www/test/toremote.sh
  • 云端执行
➜ curl 127.0.0.1:8080# 响应# bye~ bye~

附:基于gin框架项目的热重启

gin底层使用的是net/http, gin的优雅退出就等于http.Server.Shutdown函数。更新gin框架的项目只需搭建supervisor结合shell脚本实现更新。


文章来源:智云一二三科技

文章标题:Golang服务器热重启 – 基于Shutdown和Supervisor

文章地址:https://www.zhihuclub.com/813.shtml

关于作者: 智云科技

热门文章

网站地图