我需要强制重新加载应用程序以获取配置更改。我正在使用 systemd 来运行运行 flask 应用程序的 gunicorn。
我在/var/run/xx.conf 文件中获取配置更改,该文件由 systemd/service/app.path 监视:
[Path]
PathChanged=/var/run/app.conf
[Unit]
Description=app-restart
和相应的app.system:
[Unit]
Description=app-restart
After=network.target
[Service]
Type=oneshot
PIDFile=/run/app-restart/pid
User=root
Group=root
ExecStart=/usr/bin/app-reload.py
PrivateTmp=false
EnvironmentFile=-/etc/environment
[Install]
WantedBy=multi-user.target
问题是 - 如何优雅地终止每个 gunicorn flask 工作线程?
应用的 systemd 服务使用:
[Unit]
Description=app gunicorn daemon
After=network.target
[Service]
PIDFile=/run/app/pid
User=ubuntu
Group=www-data
WorkingDirectory=/opt/app
ExecStart=/usr/local/bin/gunicorn --bind unix:/var/tmp/app.sock -m 007 --workers=2 -t 400 --backlog 2048 --log-config=/etc/app/log.cfg --log-level=DEBUG app
Restart=always
RestartSec=15
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=false
EnvironmentFile=-/etc/environment
[Install]
WantedBy=multi-user.target
这样我就可以杀死 gunicorn 工作线程并重新启动它们。
我想避免杀死正在处理响应的线程。
理想情况下,在处理每个响应后,线程将检查它是否需要退出。我知道我可以在每个 flask API 方法中执行此操作,但是是否有更好的方法将所有工作线程一次一个地转换到新配置?
我不想 sysctl restart app.service 因为这会杀死所有线程并在没有工作人员事件的情况下创建死时间。 我希望每个胎面独立地终止和重新加载,所以总有一些活的 worker 。
我考虑过的一些选项:
使用 app-reload.py 获取应用程序 pids 的列表,并一次杀死一个。 Gunicorn 将在每个死亡时重新启动。可以终止正在进行的请求。
处理每个事件后,检查由 app-reload.py 创建的文件是否存在,如果存在,则终止。
我假设一定有一种方法可以将工作人员从一种配置迁移到另一种配置,而不会造成服务死角。
请您参考如下方法:
RTM 再次获胜。
http://docs.gunicorn.org/en/stable/signals.html
HUP: Reload the configuration, start the new worker processes with a new configuration and gracefully shutdown older workers. If the application is not preloaded (using the preload_app option), Gunicorn will also load the new version of it.
所以最终结果就是 systemd app.path 中的这个:
[Unit]
Description=app-restart
After=network.target
[Service]
Type=oneshot
User=root
Group=root
ExecStart=/bin/kill -s HUP $(cat /run/app/pid)
PrivateTmp=false
或者,也可以依赖于 app.system 包含 ExecReload 行这一事实并使用:
ExecReload=/bin/systemctl reload app
