Supervisor可以很好的實現(xiàn)Python的進程管理外遇,但是新增進程時需要配置文件,對于需要動態(tài)創(chuàng)建進程的場景不是很友好,supervisor_twiddler插件可以幫助實現(xiàn)上述功能。本文就supervisor_twiddler的使用做簡單的demo械拍,詳細內(nèi)容可以查閱https://github.com/mnaberez/supervisor_twiddler
1. 安裝
pip install supervisor_twiddler
2. 準備待管理的進程
這里使用一個faskapi的demo做為稍后supervisor管理的進程
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def hello():
return "hello world, guoxingyu"
3. 修改supervisord.conf
supervisord.conf的改動有兩個:第一是目前看supervisor_twiddler推薦給已有的組添加進程,所以需要在supervisord.conf中添加組名射沟;第二是添加[rpcinterface:twiddler]殊者,內(nèi)容如下:
[group:test]
[rpcinterface:twiddler]
supervisor.rpcinterface_factory = supervisor_twiddler.rpcinterface:make_twiddler_rpcinterface
4. 通過supervisor_twiddler實現(xiàn)進程管理
from xmlrpc.client import ServerProxy
if __name__ == '__main__':
# 通過user、passwd連接supervisor的RPC服務(wù)
server = ServerProxy("http://user:123@localhost:9001/RPC2")
# 打印目前的Group list
print(server.twiddler.getGroupNames())
# 動態(tài)新增process
server.twiddler.addProgramToGroup('test', 'helloworld', \
{'command': 'gunicorn fastapidemo:app -b 0.0.0.0:8088 -w 1 -k uvicorn.workers.UvicornWorker', 'autostart':'true', 'autorestart':'true'})
# 停止process并刪除
server.supervisor.stopProcess("test:helloworld")
server.twiddler.removeProcessFromGroup("test", "helloworld")
# 查看process日志
print(server.supervisor.tailProcessStderrLog("test:helloworld",0,512))
這里主要實現(xiàn)了動態(tài)新增進程验夯,關(guān)閉進程猖吴,查看日志三個子功能。
其中addProgramToGroup的具體參數(shù)可以看Github原文挥转,第一個是Group名海蔽、第二個是process名,第三個是dict绑谣,包括supervisor配置的一些參數(shù)党窜。
效果:
1597413548058.jpg
1597413609608.jpg
不過supervisor_twiddler管理的進程不能持久化保存,當supervisor重啟后借宵,進程就不在了幌衣,需要重新動態(tài)添加進程。