Celery error no nodes replied within time constraint

I'm trying to deploy a simple example of celery in my production server, I've followed the tutorial in the celery website about running celery as daemon http://docs.celeryproject.org/en/latest/tuto...

I’m trying to deploy a simple example of celery in my production server, I’ve followed the tutorial in the celery website about running celery as daemon http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html#daemonizing, and I got the config file in /etc/default/celeryd

  1 # Name of nodes to start
  2 # here we have a single node
  3 CELERYD_NODES="w1"
  4 # or we could have three nodes:
  5 #CELERYD_NODES="w1 w2 w3"
  6 
  7 # Where to chdir at start.
  8 CELERYD_CHDIR="/home/audiwime/cidec_sw"
  9 
 10 # Python interpreter from environment.
 11 ENV_PYTHON="/usr/bin/python26"
 12 
 13 # How to call "manage.py celeryd_multi"
 14 CELERYD_MULTI="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryd_multi"
 15 
 16 # # How to call "manage.py celeryctl"
 17 CELERYCTL="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryctl"
 18 
 19 # Extra arguments to celeryd
 20 CELERYD_OPTS="--time-limit=300 --concurrency=8"
 21 
 22 # Name of the celery config module.
 23 CELERY_CONFIG_MODULE="celeryconfig"
 24 
 25 # %n will be replaced with the nodename.
 26 CELERYD_LOG_FILE="/var/log/celery/%n.log"
 27 CELERYD_PID_FILE="/var/run/celery/%n.pid"
 28 
 29 # Workers should run as an unprivileged user.
 30 CELERYD_USER="audiwime"
 31 CELERYD_GROUP="audiwime"
 32 
 33 export DJANGO_SETTINGS_MODULE="cidec_sw.settings"

but if I run

celery status

in the terminal, i got this response:

Error: No nodes replied within time constraint

I can restart celery via the celeryd script provided in https://github.com/celery/celery/tree/3.0/extra/generic-init.d/

/etc/init.d/celeryd restart
celeryd-multi v3.0.12 (Chiastic Slide)
> w1.one.cloudwime.com: DOWN
> Restarting node w1.one.cloudwime.com: OK

I can run python26 manage.py celeryd -l info and my tasks in django run fine, but if I let the daemon do its work I don’t get any results, don’t even errors in /var/log/celery/w1.log

I know that my task has been registered because I did this

from celery import current_app
def call_celery_delay(request):
    print current_app.tasks
    run.delay(request.GET['age'])
    return HttpResponse(content="celery task set",content_type="text/html")

and I get a dictionary in which my task appear

{'celery.chain': <@task: celery.chain>, 'celery.chunks': <@task: celery.chunks>, 'celery.chord': <@task: celery.chord>, 'tasks.add2': <@task: tasks.add2>, 'celery.chord_unlock': <@task: celery.chord_unlock>, **'tareas.tasks.run': <@task: tareas.tasks.run>**, 'tareas.tasks.add': <@task: tareas.tasks.add>, 'tareas.tasks.test_two_minute': <@task: tareas.tasks.test_two_minute>, 'celery.backend_cleanup': <@task: celery.backend_cleanup>, 'celery.map': <@task: celery.map>, 'celery.group': <@task: celery.group>, 'tareas.tasks.test_one_minute': <@task: tareas.tasks.test_one_minute>, 'celery.starmap': <@task: celery.starmap>}

but besides that I get nothing else, no result from my task, no error in the logs, nothing.
What can be wrong?

I found this traceback

[2018-11-27 01:50:22,949: CRITICAL/MainProcess] Unrecoverable error: AttributeError("'float' object has no attribute 'items'",)
Traceback (most recent call last):
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/worker/worker.py", line 205, in start
    self.blueprint.start(self)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/bootsteps.py", line 119, in start
    step.start(parent)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/bootsteps.py", line 369, in start
    return self.obj.start()
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 317, in start
    blueprint.start(self)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/bootsteps.py", line 119, in start
    step.start(parent)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 593, in start
    c.loop(*c.loop_args())
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/celery/worker/loops.py", line 91, in asynloop
    next(loop)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/asynchronous/hub.py", line 354, in create_loop
    cb(*cbargs)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/transport/redis.py", line 1040, in on_readable
    self.cycle.on_readable(fileno)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/transport/redis.py", line 337, in on_readable
    chan.handlers[type]()
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/transport/redis.py", line 724, in _brpop_read
    self.connection._deliver(loads(bytes_to_str(item)), dest)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/transport/virtual/base.py", line 983, in _deliver
    callback(message)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/transport/virtual/base.py", line 632, in _callback
    self.qos.append(message, message.delivery_tag)
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/kombu/transport/redis.py", line 149, in append
    pipe.zadd(self.unacked_index_key, time(), delivery_tag) 
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/redis/client.py", line 2263, in zadd
    for pair in iteritems(mapping):
  File "/home/ubuntu/sixnexus/.env/lib/python3.5/site-packages/redis/_compat.py", line 123, in iteritems
    return iter(x.items())
AttributeError: 'float' object has no attribute 'items'


Содержание

  1. Error: No nodes replied within time constraint [Py3, Redis] #1456
  2. Comments
  3. Celery «Ни один узел не ответил в течение ограниченного времени»
  4. Can not work in gevent/eventlet model #6225
  5. Comments
  6. Mandatory Debugging Information
  7. Optional Debugging Information
  8. Related Issues and Possible Duplicates
  9. Related Issues
  10. Possible Duplicates
  11. Environment & Settings
  12. Steps to Reproduce
  13. Required Dependencies
  14. Python Packages
  15. Other Dependencies
  16. Minimally Reproducible Test Case
  17. Expected Behavior
  18. Actual Behavior
  19. Почему flower не показывает задачи django celery?
  20. There is no data when using redis broker. #253
  21. Comments

Error: No nodes replied within time constraint [Py3, Redis] #1456

I have celery (git master) set up on ubuntu 13.04 using python 3.3 and it seems to work fine using a sample worker: it accepts tasks and produces correct results.

But when I run celery —app=tasks.celery status or any other control/inspect command from the second shell window, it only does this:

The text was updated successfully, but these errors were encountered:

Are you sure it’s communicating with the same broker?

Can you try using celery -b redis://127.0.0.1:6379/0 status ?

Same error, but worker still accepts and executes tasks. Is there anything I can debug from the redis side?

I managed to reproduce using redis + Python3 actually. Must be some weird bug, will investigate further

i have the same bug i think — i have workers executing tasks but very slowly and i also cant use any commands like status or inspect stuff — in addition flower shows me the executed tasks but when i look at the worker list flower does not recognize any of em ..

it looks as if the workers dont ‘register’ in a sane way .. i could really use some help here ó.Ò

I’m not able to reproduce here using Redis, so I would need some more details.

An example project that reproduces the issue would be perfect!

plz read this: https://groups.google.com/forum/#!topic/celery-users/RUoTNmiLC_o
maybe u got an idea .. i will try to create a reproducable project during the weekend .. that may take some time .. i hope it works (not) 😛

it just keeps me wondering .. maybe the redis password breaks communication between queue and workers?

i did a lil more research and found some strange stuff!

Celery was filling the result storage with some like 50k results and that kinda broke the proper communication between worker and broker/result storage .. dont know what exactly, but what i did see is that all the stored results where transferred to my local worker and since im just on dialup the 10s between the servers just took forever for me .. and my screen was filling with thousands of result keys.

So id like to know why all those stored keys might be transfered without any task fetching the results?

As for now i cleaned the result storage and set the celery settings to dont write any new results.
This restored the proper communication between worker and backend to get the jobs done again.

Do you have an explanation for this phenomenon?
cheers

Results are stored regardless of anything fetching the result. The results expire after 1 day by default, you can change this setting: http://docs.celeryproject.org/en/latest/configuration.html#celery-task-result-expires

I guess the database could have been over capacity and so operation takes a very long time (50k results is not a lot, but it depends on the size of the results).

You can increase the timeout for how long it will wait for a reply:

but this not ideal and it’s better to optimize the system so that the replies arrive within a second.

Источник

Celery «Ни один узел не ответил в течение ограниченного времени»

Я создаю веб-приложение django для дневной торговли, и мне нужно управлять множеством рабочих процессов celery, которые будут выполнять сделки для пользователей. Рабочие процессы Celery создаются как отделенный процесс оболочки с помощью модуля python subprocess. В директории django app я создаю фиктивные .sh bash-файлы в качестве целей, которые будут инициализировать celery workers непосредственно после запуска окна терминала. f»celery -A MyDjangoServer4_0_4 worker —pool solo -Q bot_queue -n bot -l INFO -E» запускает celery worker на терминале, а cmd /k в конце предотвращает немедленное закрытие окна терминала для отладки. Каждый celery worker получает свое уникальное имя и уникальную очередь, поэтому они должны работать независимо и параллельно друг от друга. Я могу порождать и создавать celery worker с новыми именами и даже успешно передавать им задания. Но я не могу воссоздать или повторно инициализировать их, используя то же имя цели, даже после закрытия окна подпроцесса. Я полагаю, что мне нужно как-то выключить/прервать узел, чтобы я мог перезапустить/реинициализировать рабочий подпроцесс, но я получаю ошибку при использовании команды celery control terminate , которая мешает мне это сделать.

Приведенный ниже код start_process запустит окно подпроцесса, используя параметр ID для назначения имени/очереди в целевом сценарии .sh . Он запустит celery worker в новом окне, если имя не было использовано ранее.

Если я пытаюсь воссоздать celery worker, я получаю следующую ошибку:

Когда я набираю celery -A MyDjangoServer4_0_4 status , я вижу, что некоторые рабочие инициализированы и работают, несмотря на уничтожение подпроцессов.

НО у меня нет способа сказать узлам, чтобы они закрылись или завершились. Каждый вызов типа celery control terminate celery@bot1 или celery control shutdown celery@bot2 приводит к следующему:

Раскрытие платформы: Я разрабатываю в среде windows, но позже буду развертывать на дистрибутиве linux, так как большинство веб-хостингов используют именно его. Моей программой по умолчанию при открытии .sh файлов является git bash, который, похоже, отлично поддерживает запуск python и celery, так что пока я придерживаюсь этого. Предоставленный код должен быть переносимым и отлично работать на unix-системе, но я не тестировал фрагмент этого кода для подпроцессов на других платформах. Я не могу представить, что «отсоединение» терминала может вызвать какие-либо помехи в проблеме отключения связи с узлом, но подумал, что об этом стоит упомянуть.

Источник

Can not work in gevent/eventlet model #6225

  • I have verified that the issue exists against the master branch of Celery.
  • This has already been asked to the discussion group first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the master branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • I have verified that the issue exists against the master branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.

Possible Duplicates

Environment & Settings

Celery version: 4.4.6

celery report Output:

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: 3.6
  • Minimal Celery Version: 4.4.6
  • Minimal Kombu Version: 4.6.11
  • Minimal Broker Version: N/A or Unknown
  • Minimal Result Backend Version: N/A or Unknown
  • Minimal OS and/or Kernel Version: Ubuntu18.04 LTS (WSL2)
  • Minimal Broker Client Version: N/A or Unknown
  • Minimal Result Backend Client Version: N/A or Unknown

Python Packages

Other Dependencies

Minimally Reproducible Test Case

Just a simple app with ‘add’ function to return the sum of two number. Run this app by ‘celery -A proj -P=gevent -c=10 -l debug’.And than open anonther shell, call the ‘add’ function by ‘res = add.delay(2,2)’ and ‘res.get()’

Expected Behavior

‘res.get()’ should return ‘4’ as result

Actual Behavior

‘res.get()’ seems block forever and never return, it can be seen from the log that the task was indeed accepted’

When use ‘celery -A worker inspect ping’, it just return ‘Error: No nodes replied within time constraint.Error: No nodes replied within time constraint’. If I start multiple different worker(all in gevent model), they can not find each other. But if I start a worker in prefork model, it just works perfectly. Another strange thing is that if press crtl+c, the worker can not warm shutdown completely, ‘pidbox: Connected to amqp://myuser:**@127.0.0.1:5672/myvhost.’will appear. If use ‘celery -A worker inspect ping’ again, it will return a ‘pong’.
I have already tried py3.6 and py3.7/redis as broker/rabbitmq as broker/gevent/eventlet/ubutnu18/ubuntu16, the results are basically the same.

The text was updated successfully, but these errors were encountered:

Источник

Почему flower не показывает задачи django celery?

Перебровал кучу туториалов по запуску django celery, так и не сложилось единой картинки в голове. В общем, сейчас django celery исправно работает. Отсылает задачи в очередь, выполняет их, и в самой views.py приложения я могу по id запросить состояние задачи, посмотреть выполнилось таска или нет.

Но запуск flower не показывает ни воркеров, ни задач.

Собственно при запуске flower уже видно, что оно криво запустилось

Зарегистрированные задачи flower увидел, смог подключиться к базе но почему то ожидаемые методы оказались в нерабочем состоянии

Также команда пинг тоже не выполняется

Как запускал воркер

python manage.py celerycam —frequency=5.0
возможно дело в settings.py в котором накопился венегрет настроек из разных туториалов, приведу его на всякий случай почти полностью. Для меня важно чтобы работали в первую очередь юзерена, селери, вместо флауэр могу изобрести свой велосипед, благо во views.py могу сохранять пиды запущенных задач и мониторить их состояние. Но буду рад, если коллективный разум подскажет способы диагностики проблем с флауэрс, толковые туториалы

Когда то флауэр работал, но воркер при этом задачи принимал, но не хотел их выполнять, теперь воркер работает, но флауэр отказывается.

  • Вопрос задан более трёх лет назад
  • 3181 просмотр

Ты у flower указал -A, а у воркера нет.
Ну и вообще ты как-то странно запускешь через manage.py
Попробуй типа этого
celery -A proj worker -l info
celery -A proj flower

хм, заработало 😀

сделал по рекомендованному Вами туториалу, воркер теперь работает и при указании проекта (до этого работал только без явного указания имени проекта)

подведу итоги для себя:
запуск воркера
celery -A prod_web_site worker -l info
пинг тоже заработал

C:Python27python.exe manage.py celerycam —frequency=5.0
Теперь воркер пингуется через
celery.exe -A prod_web_site inspect ping
отображается статус онлайн через
C:Python27python.exe manage.py celery status -A prod_web_site

для успешного запуска flower еще понадобился запуск селерикам, правда не уверен, что это обязательно, вроде потом и без нее работало
C:Python27python.exe manage.py celerycam —frequency=5.0

ну и сам флауэр
K:swprod_web_site3>celery flower -A prod_web_site worker
c:python27libsite-packagesceleryappdefaults.py:251: CPendingDeprecationWa
ning:
The ‘BROKER_VHOST’ setting is scheduled for deprecation in version 2.5
nd removal in version v4.0. Use the BROKER_URL setting instead

alternative=’Use the <0.alt>instead’.format(opt))
c:python27libsite-packagesceleryappdefaults.py:251: CPendingDeprecationWa
ning:
The ‘BROKER_HOST’ setting is scheduled for deprecation in version 2.5 a
d removal in version v4.0. Use the BROKER_URL setting instead

alternative=’Use the <0.alt>instead’.format(opt))
[I 160512 07:37:12 command:136] Visit me at localhost:5555
[I 160512 07:37:12 command:141] Broker: redis://localhost:6379/0
[I 160512 07:37:12 command:144] Registered tasks:
[‘accounts.tasks.auto_upgrade_mob’,
‘accounts.tasks.just_print’,
‘accounts.tasks.test’,
‘celery.backend_cleanup’,
‘celery.chain’,
‘celery.chord’,
‘celery.chord_unlock’,
‘celery.chunks’,
‘celery.group’,
‘celery.map’,
‘celery.starmap’,
‘prod_web_site.celery.debug_task’]
[I 160512 07:37:12 mixins:231] Connected to redis://localhost:6379/0
[W 160512 07:37:14 control:45] ‘active_queues’ inspect method failed
[W 160512 07:37:14 control:45] ‘active’ inspect method failed
[W 160512 07:37:14 control:45] ‘reserved’ inspect method failed
[W 160512 07:37:14 control:45] ‘revoked’ inspect method failed

показывает ворнинги в меньшем количестве, но работает

Источник

There is no data when using redis broker. #253

celery report
software -> celery:3.1.13 (Cipater) kombu:3.0.21 py:3.4.0
billiard:3.3.0.18 py-amqp:1.4.5
platform -> system:Linux arch:64bit, ELF imp:CPython
loader -> celery.loaders.default.Loader
settings -> transport:amqp results:disabled

redis-server —version
Redis server v=2.8.9 sha=00000000:0 malloc=jemalloc-3.2.0 bits=64 build=6183a7cf6dbec67f

pip list
amqp (1.4.5)
anyjson (0.3.3)
billiard (3.3.0.18)
celery (3.1.13)
cement (2.2.2)
certifi (14.05.14)
flower (0.7.2)
hiredis (0.1.4)
humanize (0.5)
kombu (3.0.21)
msgpack-python (0.4.2)
Pillow (2.5.1)
pip (1.5.4)
pycket (0.3.0)
pymongo (2.7.2)
pytz (2014.4)
redis (2.10.1)
requests (2.3.0)
setuptools (2.1)
tornado (4.0)
WTForms (2.0.1)
wtforms-tornado (0.0.1)

supervisord.conf
[program:lusir-server-celery-worker-storage]
command=celery worker -A celeryapp.celeryapp -l info -E -Q storage -I lusir.storage.task -n storage@%%n
directory=%(ENV_HOME)s/projects/longyuan/lusir-server/src
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=30

[program:lusir-server-celery-worker-message]
command=celery worker -A celeryapp.celeryapp -l info -E -Q message -I lusir.message.task -n message@%%n
directory=%(ENV_HOME)s/projects/longyuan/lusir-server/src
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=30

[program:lusir-server-celery-worker-face]
command=celery worker -A celeryapp.celeryapp -l info -E -Q face -I lusir.face.task -n face@%%n
directory=%(ENV_HOME)s/projects/longyuan/lusir-server/src
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=30

[program:lusir-server-celery-worker-star]
command=celery worker -A celeryapp.celeryapp -l info -E -Q star -I lusir.star.task -n star@%%n
directory=%(ENV_HOME)s/projects/longyuan/lusir-server/src
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=30

[program:lusir-server-celery-flower]
command=flower —address=0.0.0.0 —port=8110 —broker=redis://lusir-redis-test:6379/12 —broker_api=redis://lusir-redis-test:6379/12 —url_prefix=flower
directory=%(ENV_HOME)s/projects/longyuan/lusir-server/src
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=30

The text was updated successfully, but these errors were encountered:

Something is wrong in your configuration. Can you create a simple project which demonstrates the problem?

You can overmmit celery works, just focus on flower. There is no worker, no task, and I searched by google, there are many other people says the same question.

Couldn’t reproduce this. My flower setup with redis broker worked as expected.

I have the same issue. I am assuming I have done something wrong but I see absolutely no workers, tasks etc. It is the same both localhost and heroku which is why I assume I have done something wrong!

flower —broker=redis://localhost:6379/0 —broker_api=redis://localhost:6379/0 —debug

celery -A myapp worker -l debug -E

Celery is working but I have complete blank on flower. Am I missing something totally obvious.

@7wonders can you show the debug log?

/projects/flower $ flower —broker=redis://localhost:6379/0 —broker_api=redis://localhost:6379/0 —debug
[I 140824 22:18:49 command:106] Visit me at http://localhost:5555
[I 140824 22:18:49 command:107] Broker: redis://localhost:6379/0
[D 140824 22:18:49 command:109] Registered tasks:
[‘celery.backend_cleanup’,
‘celery.chain’,
‘celery.chord’,
‘celery.chord_unlock’,
‘celery.chunks’,
‘celery.group’,
‘celery.map’,
‘celery.starmap’]
[D 140824 22:18:49 command:110] Settings: <‘cookie_secret’: ‘$$$’,
‘debug’: True,
‘login_url’: ‘/login’,
‘static_path’: ‘/mnt/raid/projects/flower/venv/local/lib/python2.7/site-packages/flower/static’,
‘template_path’: ‘/mnt/raid/projects/flower/venv/local/lib/python2.7/site-packages/flower/templates’>
[D 140824 22:18:49 state:83] Inspecting workers.
[I 140824 22:18:49 mixins:225] Connected to redis://localhost:6379/0
[D 140824 22:18:50 state:85] Stats: None
[D 140824 22:18:52 state:87] Registered: None
[D 140824 22:18:54 state:89] Scheduled: None
[D 140824 22:18:54 events:116] Enabling events
[D 140824 22:18:56 state:91] Active: None
[D 140824 22:18:58 state:93] Reserved: None
[D 140824 22:18:59 events:116] Enabling events
[D 140824 22:19:00 state:95] Revoked: None
[D 140824 22:19:02 state:97] Ping: None
[D 140824 22:19:04 state:99] Active queues: None
[D 140824 22:19:04 events:116] Enabling events
[D 140824 22:19:06 state:102] Conf: None
[D 140824 22:19:06 state:109] Broker queues: []
[D 140824 22:19:06 state:83] Inspecting workers.
[D 140824 22:19:08 state:85] Stats: None
[D 140824 22:19:09 events:116] Enabling events
[D 140824 22:19:10 state:87] Registered: None
[D 140824 22:19:12 state:89] Scheduled: None
[D 140824 22:19:14 state:91] Active: None
[D 140824 22:19:14 events:116] Enabling events
[D 140824 22:19:16 state:93] Reserved: None
[D 140824 22:19:18 state:95] Revoked: None
[D 140824 22:19:19 events:116] Enabling events
[D 140824 22:19:20 state:97] Ping: None
[D 140824 22:19:22 state:99] Active queues: None
[D 140824 22:19:24 state:102] Conf: None
[D 140824 22:19:24 state:109] Broker queues: []

Your workers don’t reply to celery inspect commands. It can happen if your workers are busy. Try to increase the timeout with —inspect_timeout option.

Tried with/without broker_api, db. Tried waiting for a while, tried hammering celery with tasks. I should mention that I also use the same redis instance for cache, but that shouldnt make any difference?? I have all the _kombu.binding.celery (pidbox, celeryv, reply.celery.pidbox) and many celery-task-meta-xxx in redis. Anything else?

What is the output of ‘celery inspect stats —broker=redis://localhost:6379/0’ command?

inspect_timeout=100 didnt seem to help.
celery inspect stats —broker=redis://localhost:6379/0
Error: No nodes replied within time constraint

Try —inspect_timeout=10000. The default value is 1000. 100 shouldn’t have any positive effect.

«Error: No nodes replied within time constraint» means celery workers don’t reply inspect commands and they timeout.

I thought you meant increase frequency 🙂

Tried cranking it up to 1000, 10000, 100000, 1000000 but no effect. Anything missing from my celery setup?

[2014-08-24 20:15:00,056: DEBUG/MainProcess] | Worker: Preparing bootsteps.
[2014-08-24 20:15:00,057: DEBUG/MainProcess] | Worker: Building graph.
[2014-08-24 20:15:00,057: DEBUG/MainProcess] | Worker: New boot order:
[2014-08-24 20:15:00,061: DEBUG/MainProcess] | Consumer: Preparing bootsteps.
[2014-08-24 20:15:00,061: DEBUG/MainProcess] | Consumer: Building graph.
[2014-08-24 20:15:00,066: DEBUG/MainProcess] | Consumer: New boot order:

————— celery@scott-main v3.1.13 (Cipater)
—- **** ——
— * *** * — Linux-3.11.0-12-generic-x86_64-with-LinuxMint-16-petra
— * — **** —

Источник

In this post, we will see how to resolve Error: No nodes replied within time constraint

Question:

I’m running a worker on Celery [version 5.1.0 (sun-harmonics)] like this:

the worker seems to run fine and responds to requests. here’s a partial log:

[2022-11-06 03:02:15,913: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2022-11-06 03:02:15,918: DEBUG/MainProcess] | Worker: Building graph… [2022-11-06 03:02:15,919: DEBUG/MainProcess] | Worker: New boot order: {StateDB, Beat, Timer, Hub, Pool, Autoscaler, Consumer} [2022-11-06 03:02:15,933: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2022-11-06 03:02:15,934: DEBUG/MainProcess] | Consumer: Building graph… [2022-11-06 03:02:16,033: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Heart, Mingle, Gossip, Tasks, Control, Agent, event loop} [2022-11-06 03:02:16,034: INFO/MainProcess] LIQUIDITY PROVISION TASK_SCHEDULER – Genesis Subscribe Started [2022-11-06 03:02:16,046: DEBUG/MainProcess] http://vault.gitlab-managed-apps.svc.cluster.local:8200 «GET /v1/auth/token/lookup-self HTTP/1.1» 200 908 [2022-11-06 03:02:16,100: DEBUG/MainProcess] http://vault.gitlab-managed-apps.svc.cluster.local:8200 «GET /v1/site/data/prod/site HTTP/1.1» 200 None [2022-11-06 03:02:16,105: DEBUG/MainProcess] http://vault.gitlab-managed-apps.svc.cluster.local:8200 «GET /v1/auth/token/lookup-self HTTP/1.1» 200 908 [2022-11-06 03:02:16,111: DEBUG/MainProcess] http://vault.gitlab-managed-apps.svc.cluster.local:8200 «GET /v1/site/data/prod/site HTTP/1.1» 200 None

but when I try to get a status:

it fails:

Error: No nodes replied within time constraint

I’ve googled a lot and there’s precious little out there that can help. We’re running Celery with a Redis (v7.0.5) backend. any help on how to troubleshoot would be greatly appreciated

I’m expecting to see a list of the worker nodes

Addendum I

it appears report works and I get something like this:

Best Answer:

ok, I figured it out. we had configured a task:

which, due to a failure in a foreign system, never returned:

so this implementation would sleep on failure ad infinitum, which I guess meant the worker could never get started as it was just waiting. once that code was removed I can now get a proper status from celery

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com

Я создаю веб-приложение django для дневной торговли, и мне нужно управлять множеством рабочих процессов celery, которые будут выполнять сделки для пользователей. Рабочие процессы Celery создаются как отделенный процесс оболочки с помощью модуля python subprocess. В директории django app я создаю фиктивные .sh bash-файлы в качестве целей, которые будут инициализировать celery workers непосредственно после запуска окна терминала. f"celery -A MyDjangoServer4_0_4 worker --pool solo -Q bot{id}_queue -n bot{id} -l INFO -E" запускает celery worker на терминале, а cmd /k в конце предотвращает немедленное закрытие окна терминала для отладки. Каждый celery worker получает свое уникальное имя и уникальную очередь, поэтому они должны работать независимо и параллельно друг от друга. Я могу порождать и создавать celery worker с новыми именами и даже успешно передавать им задания. Но я не могу воссоздать или повторно инициализировать их, используя то же имя цели, даже после закрытия окна подпроцесса. Я полагаю, что мне нужно как-то выключить/прервать узел, чтобы я мог перезапустить/реинициализировать рабочий подпроцесс, но я получаю ошибку при использовании команды celery control terminate, которая мешает мне это сделать.

Приведенный ниже код start_process запустит окно подпроцесса, используя параметр ID для назначения имени/очереди в целевом сценарии .sh. Он запустит celery worker в новом окне, если имя не было использовано ранее.

def start_process(id, args=None):
    # https://stackoverflow.com/questions/11585168/launch-an-independent-process-with-python
    kwargs = {}

    if platform.system() == 'Windows':
        DETACHED_PROCESS = 0x00000008
        kwargs.update(creationflags=DETACHED_PROCESS)
        kwargs.update(shell=True)
        kwargs.update(close_fds=True)
    elif sys.version_info < (3, 2):  # assume posix
        kwargs.update(preexec_fn=os.setsid)
    else:  # Python 3.2+ and Unix
        kwargs.update(start_new_session=True)

    f = open(f'start_celery_consumer{id}.sh', 'w')
    f.write(f"""
    celery -A MyDjangoServer4_0_4 worker --pool solo -Q bot{id}_queue -n bot{id} -l INFO -E
    cmd /k
    """)
    f.close()

    process = subprocess.Popen([f'start_celery_consumer{id}.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
    CryptoBotsApp.shared.console_ids.append(process)

Если я пытаюсь воссоздать celery worker, я получаю следующую ошибку:

[2022-08-13 18:00:17,927: WARNING/MainProcess] C:UsersadminPycharmProjectsMyDjangoServer4_0_4venvlibsite-packageskombupidbox.py:70: UserWarning: A node named celery@bot1 is already using this process mailbox!

Maybe you forgot to shutdown the other node or did not do so properly?
Or if you meant to start multiple nodes on the same host please make sure
you give each node a unique node name!

  warnings.warn(W_PIDBOX_IN_USE.format(node=self))

Когда я набираю celery -A MyDjangoServer4_0_4 status, я вижу, что некоторые рабочие инициализированы и работают, несмотря на уничтожение подпроцессов.

->  celery@bot2: OK
->  celery@bot1: OK
->  celery@JOHN-WORKSTATION: OK

НО у меня нет способа сказать узлам, чтобы они закрылись или завершились. Каждый вызов типа celery control terminate celery@bot1 или celery control shutdown celery@bot2 приводит к следующему:

Error: No nodes replied within time constraint

Раскрытие платформы:
Я разрабатываю в среде windows, но позже буду развертывать на дистрибутиве linux, так как большинство веб-хостингов используют именно его. Моей программой по умолчанию при открытии .sh файлов является git bash, который, похоже, отлично поддерживает запуск python и celery, так что пока я придерживаюсь этого. Предоставленный код должен быть переносимым и отлично работать на unix-системе, но я не тестировал фрагмент этого кода для подпроцессов на других платформах. Я не могу представить, что «отсоединение» терминала может вызвать какие-либо помехи в проблеме отключения связи с узлом, но подумал, что об этом стоит упомянуть.

Вернуться на верх

Перебровал кучу туториалов по запуску django celery, так и не сложилось единой картинки в голове. В общем, сейчас django celery исправно работает. Отсылает задачи в очередь, выполняет их, и в самой views.py приложения я могу по id запросить состояние задачи, посмотреть выполнилось таска или нет.

Но запуск flower не показывает ни воркеров, ни задач.

Собственно при запуске flower уже видно, что оно криво запустилось

K:swprod_web_site3>C:Python27python.exe manage.py celery flower -A prod_web
site.celeryapp:app_celery worker
[I 160511 20:35:08 command:136] Visit me at http://localhost:5555
[I 160511 20:35:08 command:141] Broker: redis://localhost:6379/0
[I 160511 20:35:08 command:144] Registered tasks:
    ['accounts.tasks.just_print',
     'accounts.tasks.test',
     'celery.backend_cleanup',
     'celery.chain',
     'celery.chord',
     'celery.chord_unlock',
     'celery.chunks',
     'celery.group',
     'celery.map',
     'celery.starmap']
[I 160511 20:35:08 mixins:231] Connected to redis://localhost:6379/0
[W 160511 20:35:11 control:44] 'stats' inspect method failed
[W 160511 20:35:11 control:44] 'active_queues' inspect method failed
[W 160511 20:35:11 control:44] 'registered' inspect method failed
[W 160511 20:35:11 control:44] 'scheduled' inspect method failed
[W 160511 20:35:11 control:44] 'active' inspect method failed
[W 160511 20:35:11 control:44] 'reserved' inspect method failed
[W 160511 20:35:11 control:44] 'revoked' inspect method failed
[W 160511 20:35:11 control:44] 'conf' inspect method failed

Зарегистрированные задачи flower увидел, смог подключиться к базе но почему то ожидаемые методы оказались в нерабочем состоянии

Также команда пинг тоже не выполняется

K:swprod_web_site3>C:Python27Scriptscelery.exe -A prod_web_site.celeryapp:app_celery inspect ping
Error: No nodes replied within time constraint.

Как запускал воркер

K:swprod_web_site3>python manage.py celery worker -l debug --pythonpath=C:Python27

селерикам

python manage.py celerycam --frequency=5.0
возможно дело в settings.py в котором накопился венегрет настроек из разных туториалов, приведу его на всякий случай почти полностью. Для меня важно чтобы работали в первую очередь юзерена, селери, вместо флауэр могу изобрести свой велосипед, благо во views.py могу сохранять пиды запущенных задач и мониторить их состояние. Но буду рад, если коллективный разум подскажет способы диагностики проблем с флауэрс, толковые туториалы

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'userena',
    'guardian',
    'easy_thumbnails',
    'accounts',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ru'
TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'
AUTHENTICATION_BACKENDS = (
    'userena.backends.UserenaAuthenticationBackend',
    'guardian.backends.ObjectPermissionBackend',
    'django.contrib.auth.backends.ModelBackend',
)
ANONYMOUS_USER_ID = -1

AUTH_PROFILE_MODULE = 'accounts.UserProfile'
USERENA_SIGNIN_REDIRECT_URL = '/accounts/%(username)s/'
LOGIN_URL = '/accounts/signin/'
LOGOUT_URL = '/accounts/signout/'
SITE_ID = 2

EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = '***'
EMAIL_HOST_PASSWORD = '***'

#
import djcelery
djcelery.setup_loader()

INSTALLED_APPS += ('djcelery', 'djkombu',)

BROKER_URL = 'redis://localhost:6379/0'

CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'

BROKER_HOST = "localhost"
BROKER_BACKEND="redis"
REDIS_PORT=6379
REDIS_HOST = "localhost"
BROKER_USER = ""
BROKER_PASSWORD =""
BROKER_VHOST = "0"
REDIS_DB = 0
REDIS_CONNECT_RETRY = True
CELERY_SEND_EVENTS=True
#CELERY_RESULT_BACKEND='redis'
CELERY_TASK_RESULT_EXPIRES =  10
CELERYBEAT_SCHEDULER="djcelery.schedulers.DatabaseScheduler"
CELERY_ALWAYS_EAGER=False
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600}

CELERY_TASK_RESULT_EXPIRES = 7*86400  # 7 days
CELERY_SEND_EVENTS = True
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
#CELERY_ACCEPT_CONTENT = ['application/json']
#CELERY_TASK_SERIALIZER = 'json'
#CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Kiev'

from datetime import timedelta

CELERY_ALWAYS_EAGER=False
BROKER_BACKEND = "djkombu.transport.DatabaseTransport"

CELERYCAM_EXPIRE_SUCCESS = timedelta(days=30)
CELERYCAM_EXPIRE_ERROR = timedelta(days=7)
CELERYCAM_EXPIRE_PENDING = timedelta(days=7)

Когда то флауэр работал, но воркер при этом задачи принимал, но не хотел их выполнять, теперь воркер работает, но флауэр отказывается.

I’m trying to deploy a simple example of celery in my production server, I’ve followed the tutorial in the celery website about running celery as daemon http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html#daemonizing, and I got the config file in /etc/default/celeryd

  1 # Name of nodes to start
  2 # here we have a single node
  3 CELERYD_NODES="w1"
  4 # or we could have three nodes:
  5 #CELERYD_NODES="w1 w2 w3"
  6 
  7 # Where to chdir at start.
  8 CELERYD_CHDIR="/home/audiwime/cidec_sw"
  9 
 10 # Python interpreter from environment.
 11 ENV_PYTHON="/usr/bin/python26"
 12 
 13 # How to call "manage.py celeryd_multi"
 14 CELERYD_MULTI="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryd_multi"
 15 
 16 # # How to call "manage.py celeryctl"
 17 CELERYCTL="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryctl"
 18 
 19 # Extra arguments to celeryd
 20 CELERYD_OPTS="--time-limit=300 --concurrency=8"
 21 
 22 # Name of the celery config module.
 23 CELERY_CONFIG_MODULE="celeryconfig"
 24 
 25 # %n will be replaced with the nodename.
 26 CELERYD_LOG_FILE="/var/log/celery/%n.log"
 27 CELERYD_PID_FILE="/var/run/celery/%n.pid"
 28 
 29 # Workers should run as an unprivileged user.
 30 CELERYD_USER="audiwime"
 31 CELERYD_GROUP="audiwime"
 32 
 33 export DJANGO_SETTINGS_MODULE="cidec_sw.settings"

but if I run

celery status

in the terminal, i got this response:

Error: No nodes replied within time constraint

I can restart celery via the celeryd script provided in https://github.com/celery/celery/tree/3.0/extra/generic-init.d/

/etc/init.d/celeryd restart
celeryd-multi v3.0.12 (Chiastic Slide)
> w1.one.cloudwime.com: DOWN
> Restarting node w1.one.cloudwime.com: OK

I can run python26 manage.py celeryd -l info and my tasks in django run fine, but if I let the daemon do its work I don’t get any results, don’t even errors in /var/log/celery/w1.log

I know that my task has been registered because I did this

from celery import current_app
def call_celery_delay(request):
    print current_app.tasks
    run.delay(request.GET['age'])
    return HttpResponse(content="celery task set",content_type="text/html")

and I get a dictionary in which my task appear

{'celery.chain': <@task: celery.chain>, 'celery.chunks': <@task: celery.chunks>, 'celery.chord': <@task: celery.chord>, 'tasks.add2': <@task: tasks.add2>, 'celery.chord_unlock': <@task: celery.chord_unlock>, **'tareas.tasks.run': <@task: tareas.tasks.run>**, 'tareas.tasks.add': <@task: tareas.tasks.add>, 'tareas.tasks.test_two_minute': <@task: tareas.tasks.test_two_minute>, 'celery.backend_cleanup': <@task: celery.backend_cleanup>, 'celery.map': <@task: celery.map>, 'celery.group': <@task: celery.group>, 'tareas.tasks.test_one_minute': <@task: tareas.tasks.test_one_minute>, 'celery.starmap': <@task: celery.starmap>}

but besides that I get nothing else, no result from my task, no error in the logs, nothing.
What can be wrong?

Я пытаюсь развернуть простой пример сельдерея на моем рабочем сервере, я следил за учебником на веб-сайте сельдерея о запуске сельдерея в качестве демона http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html#daemonizing, и я получил файл конфигурации в /etc/default/celeryd

  1 # Name of nodes to start
  2 # here we have a single node
  3 CELERYD_NODES="w1"
  4 # or we could have three nodes:
  5 #CELERYD_NODES="w1 w2 w3"
  6 
  7 # Where to chdir at start.
  8 CELERYD_CHDIR="/home/audiwime/cidec_sw"
  9 
 10 # Python interpreter from environment.
 11 ENV_PYTHON="/usr/bin/python26"
 12 
 13 # How to call "manage.py celeryd_multi"
 14 CELERYD_MULTI="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryd_multi"
 15 
 16 # # How to call "manage.py celeryctl"
 17 CELERYCTL="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryctl"
 18 
 19 # Extra arguments to celeryd
 20 CELERYD_OPTS="--time-limit=300 --concurrency=8"
 21 
 22 # Name of the celery config module.
 23 CELERY_CONFIG_MODULE="celeryconfig"
 24 
 25 # %n will be replaced with the nodename.
 26 CELERYD_LOG_FILE="/var/log/celery/%n.log"
 27 CELERYD_PID_FILE="/var/run/celery/%n.pid"
 28 
 29 # Workers should run as an unprivileged user.
 30 CELERYD_USER="audiwime"
 31 CELERYD_GROUP="audiwime"
 32 
 33 export DJANGO_SETTINGS_MODULE="cidec_sw.settings"

но если я запустил

celery status

в терминале, я получил этот ответ:

Error: No nodes replied within time constraint

Я могу перезапустить сельдерей через celeryd script, представленный в https://github.com/celery/celery/tree/3.0/extra/generic-init.d/

/etc/init.d/celeryd restart
celeryd-multi v3.0.12 (Chiastic Slide)
> w1.one.cloudwime.com: DOWN
> Restarting node w1.one.cloudwime.com: OK

Я могу запустить

python26 manage.py celeryd -l info

и мои задачи в django работают нормально, но если я позволю демонам выполнить свою работу, я не получу никаких результатов, даже ошибки в /var/log/celery/w1.log

Я знаю, что моя задача была зарегистрирована, потому что я сделал это

from celery import current_app
def call_celery_delay(request):
    print current_app.tasks
    run.delay(request.GET['age'])
    return HttpResponse(content="celery task set",content_type="text/html")

и я получаю словарь, в котором появляется моя задача

{'celery.chain': <@task: celery.chain>, 'celery.chunks': <@task: celery.chunks>, 'celery.chord': <@task: celery.chord>, 'tasks.add2': <@task: tasks.add2>, 'celery.chord_unlock': <@task: celery.chord_unlock>, **'tareas.tasks.run': <@task: tareas.tasks.run>**, 'tareas.tasks.add': <@task: tareas.tasks.add>, 'tareas.tasks.test_two_minute': <@task: tareas.tasks.test_two_minute>, 'celery.backend_cleanup': <@task: celery.backend_cleanup>, 'celery.map': <@task: celery.map>, 'celery.group': <@task: celery.group>, 'tareas.tasks.test_one_minute': <@task: tareas.tasks.test_one_minute>, 'celery.starmap': <@task: celery.starmap>}

но кроме того, я ничего не получаю, никакого результата из моей задачи, ошибок в журналах, ничего.
Может ли кто-нибудь сказать мне, что может быть неправильно?
Ты моя единственная надежда…

Понравилась статья? Поделить с друзьями:
  • Cef error gta 5 что делать
  • Ce97 ошибка бмв
  • Ce620d32 moulinex ошибка е2
  • Ce363293 ошибка ps4
  • Ce 44004 2 ошибка пс4