之前通过gensim和chatyuan部署了两个机器人,其中gensim用于提供检索机器人,chatyuan用于提供生成式机器人,为了提供web接口服务,又部署了FastAPI,FastAPI 是一个高性能 Web 框架,用于构建 API应用,FastAPI内置了一个uvicorn服务,uvicorn 是一个闪电般快速的 ASGI 服务器,基于 uvloop 和 httptools 构建。
但部署在centos7后,每天一次宕机,每天都得重启,让人挺烦的,今天决定无论如何做好应用的自动监控和重启工作,一劳永逸。
一般来说python的flask会内置一个uwsgi,fastapi内置uvicorn,大概uwsgi更适合web应用,uvicorn更适合接口应用吧,unicorn智商还有一个gunicorn,gunicorn可以管理运行多个uvicorn,也以达到并发与并行的最好效果。
nginx是目前非常成熟的代理Web服务,通常情况下一般都使用nginx,实现反向代理。本文暂不牵扯那么多。
supervisor是一个用python语言编写的进程管理工具,它可以很方便的监听、启动、停止、重启一个或多个进程。当一个进程意外被杀死,supervisor监听到进程死后,可以很方便的让进程自动恢复,不再需要程序员或系统管理员自己编写代码来控制。
因为uvicorn 是手动维护启动停止,所以我们使用 supervisor 工具维护uvicorn 。配置过程看起来不复杂,但会有很多坑。
一、安装supervisor
yum install epel-release
yum install -y supervisor
安装完成后,提供会自动创建以下几个目录
/run/supervisor --运行目录
/etc/supervisor --配置目录
/var/log/supervisor --日志目录
二、为避免覆盖supervisor配置文件,创建一个新文件夹和配置文件
cd /etc
echo_supervisord_conf > supervisord.conf
mkdir -p /etc/supervisord.d
三、编辑supervisord.conf
vi supervisord.conf
[include]
files = supervisord.d/*.ini
四、到supervisord.d目录下,创建和编辑hny.ini
[program:hny]
command=/usr/local/python3/bin/uvicorn main:app --host 0.0.0.0--port 8000--workers 4
directory=/usr/local/python3/hnyfastApiProject
numprocs=1
user=root
autostart=true
autorestart=true
startsecs=100
startretries=10
redirect_stderr=true
stopasgroup=true
killasgroup=true
loglevel=info
stdout_logfile=/var/log/supervisor/hny.log
五
五、启动supervisord,启动相关配置文件
[root@localhost supervisor]# systemctl enable supervisord
[root@localhost supervisor]# systemctl restart supervisord
[root@localhost supervisor]# supervisord -c /etc/supervisor/supervisord.conf
六、相关典型错误及处理
错误一、unix:///var/run/supervisor/supervisor.sock no such file;error: <class'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib64/python2.7/socket.py line: 224
创建supervisor.sock文件,并进行赋权
touch /var/run/supervisor/supervisor.sock
chmod 777 /var/run/supervisor/supervisor.sock
错误二、Error: Another program is already listening on a port that one of our HTTP servers is configured to
找到已经存在的进程,杀掉即可
ps -ef | grep supervisord
将XXX 进程关掉
kill -s SIGTERM XXX
错误三、Starting supervisor: Error: %(process_num) must be present within process_name when numprocs > 1 in section 'program:nginx' (file: '/etc/supervisor/conf.d/nginx.conf')For help, use /usr/bin/supervisord -h
这是配置文件格式不对,下面是格式简介
当numprocs=1时,process_name=%(program_name)s
当numprocs>=2时,%(program_name)s_%(process_num
错误四、pkg_resources.DistributionNotFound: The ‘supervisor==3.4.0‘的解决方法,Centos7在启动supervisor的过程中的问题;# 把相关文件头部的 #! /usr/bin/python 改成 #! /usr/bin/python2,这是因为supervisor依赖于python2,而python3和python3之间的版本冲突导致的。
vi /usr/bin/supervisord
vi /usr/bin/supervisorctl
vi /usr/bin/yum
vi /usr/libexec/urlgrabber-ext-down
错误五、INFO spawnerr: can't find command 'uvicorn',这是因为supervisor不认环境变量中的路径,在配置文件中需要使用绝对路径,其他办法还没想好
supervisor不认环境变量中的路径,
在hny.ini中使用绝对路径/usr/local/python3/bin/uvicorn
最后欢迎关注公众号:python与大数据分析