记一次Celery的仇

背景:项目在公司的一台虚拟机上运行(32核+32G)。其他人的项目也在这台物理机上运行。。我的训练代码是单进程的,跑完一次需要大约10h(数据量大逮着一个核使劲跑。。);训练是一个Celery定时任务;我开始训练时就有人提出他们的项目慢的卡着了。。

改进:用多进程改进了训练过程中阻塞的地方。这时就出问题了,在Celery进程中运行创建子进程时报错:AssertionError: daemonic processes are not allowed to have children(“不允许在守护进程中创建子进程”)

解决办法:

1,在终端设置环境变量启用优化模式,export PYTHONOPTIMIZE=1,再执行celery -A app.celery.base worker -l info -n socwebai就行了

2,如果用的multiprocessing,重写一个Mypool:https://stackoverflow.com/questions/6974695/python-process-pool-non-daemonic(没试)

用方法1可以在本地测试运行了。

修改服务器上supervisor 

command = export PYTHONOPTIMIZE=1 && /home/ldy/workspace/socwebai/venv_socwebai/bin/celery -A app.celery.base worker -l info -n socwebai

supervisor报错找不到export

查资料发现可以指定Celery 的 -O参数:

there are two method to solve this problem ,disable assert:
1.where celery starts set export PYTHONOPTIMIZE=1 OR start celery with this parameter -O OPTIMIZATION
2.disable python packet multiprocessing process.py line 102:
assert not _current_process._config.get(‘daemon’), ‘daemonic processes are not allowed to have children’

试了下面几条命令,还是提示不能创建子进程

celery -A app.celery.base -Q worker -l info -n socwebai
celery -A app.celery.base worker -l info -n socwebai -Q
celery -A app.celery.base worker -l info -n socwebai -Q 1

  

不熟悉-O参数鸭!


今天,问题解决了。

放弃supervisor改用systemd开机自启celery,ubuntu18.04 systemd开机自启教程

将文中rc.local文件替换如下:

#!/bin/bash

echo "PowerBoot strating..." > /var/www/socwebai/PowerBoot.log

cd /var/www/socwebai/
source venv_socwebai/bin/activate

export PYTHONOPTIMIZE=1
echo "ok" >> /var/www/socwebai/PowerBoot.log
celery -A app.celery.base worker -l info -n socwebai >> /var/www/socwebai/PowerBoot.log 2>&1 &


echo "okk" >> /var/www/socwebai/PowerBoot.log
celery beat -A app.celery.tasks.train_model >> /var/www/socwebai/PowerBoot.log 2>&1 &

echo "finished!" >> /var/www/socwebai/PowerBoot.log

sudo reboot 重启后,任务就启动了。一个celery worker,一个celery beat.

重点提一下rc.local部分:“ >> /var/www/socwebai/PowerBoot.log 2>&1 &”

在没加该部分开机自启时,执行完celery -A app.celery.base worker -l info -n socwebai终端被占用,无法继续向下执行,该部分的作用是:把当前终端放到后台,继续向下执行。

原文地址:https://www.cnblogs.com/ldy-miss/p/10320495.html