Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions celery/app/amqp.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from celery.utils.nodenames import anon_nodename
from celery.utils.saferepr import saferepr
from celery.utils.text import indent as textindent
from celery.utils.time import maybe_make_aware, to_utc
from celery.utils.time import maybe_make_aware

from . import routes as _routes

Expand Down Expand Up @@ -407,17 +407,11 @@ def as_task_v1(self, task_id, name, args=None, kwargs=None,
if countdown: # convert countdown to ETA
self._verify_seconds(countdown, 'countdown')
now = now or self.app.now()
timezone = timezone or self.app.timezone
eta = now + timedelta(seconds=countdown)
if utc:
eta = to_utc(eta).astimezone(timezone)
if isinstance(expires, numbers.Real):
self._verify_seconds(expires, 'expires')
now = now or self.app.now()
timezone = timezone or self.app.timezone
expires = now + timedelta(seconds=expires)
if utc:
expires = to_utc(expires).astimezone(timezone)
eta = eta and eta.isoformat()
expires = expires and expires.isoformat()

Expand Down
18 changes: 13 additions & 5 deletions celery/app/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,8 @@ def prepare_config(self, c):

def now(self):
"""Return the current time and date as a datetime."""
return self.loader.now(utc=self.conf.enable_utc)
from datetime import datetime
return datetime.utcnow().replace(tzinfo=self.timezone)

@Chronial Chronial Aug 12, 2018 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is wrong. This will not return the current time in self.timezone. Let's say for example that self.timezone is +8 and it is currently 12:00 UTC. This method will return 12:00 +8, which is the same point in time as 04:00 UTC – not 12:00 UTC.
Note that this current implementation might even return nonsensical times, like 2017-03-25 02:30 for a Europe/Berlin timezone – a time that doesn't exist.

The correct way to get the current time in a local timezone is datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(self.timezone). See the same functionality in django and the pytz docs.

But you can't just make a function that used to return utc times return times from timezones that observe DST. If the caller code is not aware of that, things might break. Example: You return 2017-03-24 03:30 Europe/Berlin. The caller adds 24h to this and then checks if the time is before 04:00. Adding 24h crosses a DST boundary, so the above +24h is actually 2017-03-25 04:30. But if you add 24h to a 2017-03-24 03:30 Europe/Berlin datetime object, you get 2017-03-25 03:30 Europe/Berlin [NON-DST]. You need to call timezone.normalize on that to turn that into a sensible datetime object – see the pytz docs.

Hope this helps.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Chronial would you mind sending a pr with your suggestions?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Providing a correct implementation using timezones is not easy. Since I moved away from using celery (its broken timzone handling beeing one of the reasons ^^), I unfortunately do not have the time to provide a full PR for this.

Just wanted to report this bug, since I stumbled upon it while browsing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Chronial you are right, this has already been corrected by other contributors in master/latest release.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, sorry for digging up this old PR. I came here via the mention on #4006 and didn't realize how old this PR was.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem @Chronial thanks for the feedback.


def select_queues(self, queues=None):
"""Select subset of queues.
Expand Down Expand Up @@ -1231,6 +1232,10 @@ def tasks(self):
def producer_pool(self):
return self.amqp.producer_pool

def uses_utc_timezone(self):
"""Check if the application uses the UTC timezone."""
return self.conf.timezone == 'UTC' or self.conf.timezone is None

@cached_property
def timezone(self):
"""Current timezone for this app.
Expand All @@ -1239,9 +1244,12 @@ def timezone(self):
:setting:`timezone` setting.
"""
conf = self.conf
tz = conf.timezone
tz = conf.timezone or 'UTC'
if not tz:
return (timezone.get_timezone('UTC') if conf.enable_utc
else timezone.local)
return timezone.get_timezone(conf.timezone)
if conf.enable_utc:
return timezone.get_timezone('UTC')
else:
if not conf.timezone:
return timezone.local
return timezone.get_timezone(tz)
App = Celery # noqa: E305 XXX compat
4 changes: 2 additions & 2 deletions celery/worker/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def task_message_handler(message, body, ack, reject, callbacks,
to_timestamp=to_timestamp):
if body is None:
body, headers, decoded, utc = (
message.body, message.headers, False, True,
message.body, message.headers, False, app.uses_utc_timezone(),
)
if not body_can_be_buffer:
body = bytes(body) if isinstance(body, buffer_t) else body
Expand Down Expand Up @@ -126,7 +126,7 @@ def task_message_handler(message, body, ack, reject, callbacks,
if req.utc:
eta = to_timestamp(to_system_tz(req.eta))
else:
eta = to_timestamp(req.eta, timezone.local)
eta = to_timestamp(req.eta, app.timezone)
except (OverflowError, ValueError) as exc:
error("Couldn't convert ETA %r to timestamp: %r. Task: %r",
req.eta, exc, req.info(safe=True), exc_info=True)
Expand Down
46 changes: 44 additions & 2 deletions t/unit/app/test_app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import absolute_import, unicode_literals

from datetime import datetime, timedelta
import gc
import itertools
import os
Expand All @@ -23,7 +24,7 @@
from celery.platforms import pyimplementation
from celery.utils.collections import DictAttribute
from celery.utils.serialization import pickle
from celery.utils.time import timezone
from celery.utils.time import timezone, to_utc, localize
from celery.utils.objects import Bunch

THIS_IS_A_KEY = 'this is a value'
Expand Down Expand Up @@ -73,6 +74,36 @@ class test_App:
def setup(self):
self.app.add_defaults(deepcopy(self.CELERY_TEST_CONFIG))

def test_now(self):
timezone_setting_value = 'US/Eastern'
tz_utc = timezone.get_timezone('UTC')
tz_us_eastern = timezone.get_timezone(timezone_setting_value)

now = datetime.utcnow().replace(tzinfo=tz_utc)
app_now = self.app.now()

assert app_now.tzinfo == tz_utc
assert app_now - now <= timedelta(seconds=1)

# Check that timezone conversion is applied from configuration
self.app.conf.enable_utc = False
self.app.conf.timezone = timezone_setting_value
# timezone is a cached property
del self.app.timezone

app_now = self.app.now()
assert app_now.tzinfo == tz_us_eastern

diff = to_utc(datetime.utcnow()) - localize(app_now, tz_utc)
assert diff <= timedelta(seconds=1)

# Verify that timezone setting overrides enable_utc=on setting
self.app.conf.enable_utc = True
del self.app.timezone
app_now = self.app.now()
assert self.app.timezone == tz_us_eastern
assert app_now.tzinfo == tz_us_eastern

@patch('celery.app.base.set_default_app')
def test_set_default(self, set_default_app):
self.app.set_default()
Expand Down Expand Up @@ -647,7 +678,8 @@ def test_setting__broker_transport_options(self):
_args = {'foo': 'bar', 'spam': 'baz'}

self.app.config_from_object(Bunch())
assert self.app.conf.broker_transport_options == {}
assert self.app.conf.broker_transport_options == \
{'polling_interval': 0.1}

self.app.config_from_object(Bunch(broker_transport_options=_args))
assert self.app.conf.broker_transport_options == _args
Expand Down Expand Up @@ -797,6 +829,16 @@ def test_timezone__none_set(self):
tz = self.app.timezone
assert tz == timezone.get_timezone('UTC')

def test_uses_utc_timezone(self):
self.app.conf.timezone = None
assert self.app.uses_utc_timezone() is True

self.app.conf.timezone = 'US/Eastern'
assert self.app.uses_utc_timezone() is False

self.app.conf.timezone = 'UTC'
assert self.app.uses_utc_timezone() is True

def test_compat_on_configure(self):
_on_configure = Mock(name='on_configure')

Expand Down
14 changes: 10 additions & 4 deletions t/unit/backends/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,19 +357,25 @@ def test_get_many(self):
ids = {uuid(): i for i in range(10)}
for id, i in items(ids):
self.b.mark_as_done(id, i)
it = self.b.get_many(list(ids))
it = self.b.get_many(list(ids), interval=0.01)
for i, (got_id, got_state) in enumerate(it):
assert got_state['result'] == ids[got_id]
assert i == 9
assert list(self.b.get_many(list(ids)))
assert list(self.b.get_many(list(ids), interval=0.01))

self.b._cache.clear()
callback = Mock(name='callback')
it = self.b.get_many(list(ids), on_message=callback)
it = self.b.get_many(
list(ids),
on_message=callback,
interval=0.05
)
for i, (got_id, got_state) in enumerate(it):
assert got_state['result'] == ids[got_id]
assert i == 9
assert list(self.b.get_many(list(ids)))
assert list(
self.b.get_many(list(ids), interval=0.01)
)
callback.assert_has_calls([
call(ANY) for id in ids
])
Expand Down
4 changes: 3 additions & 1 deletion t/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ class WindowsError(Exception):
def celery_config():
return {
'broker_url': 'memory://',
'broker_transport_options': {
'polling_interval': 0.1
},
'result_backend': 'cache+memory://',

'task_default_queue': 'testcelery',
'task_default_exchange': 'testcelery',
'task_default_routing_key': 'testcelery',
Expand Down
10 changes: 6 additions & 4 deletions t/unit/contrib/test_migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,11 @@ def test_removes_compression_header(self):
class test_migrate_tasks:

def test_migrate(self, app, name='testcelery'):
x = Connection('memory://foo')
y = Connection('memory://foo')
connection_kwargs = dict(
transport_options={'polling_interval': 0.01}
)
x = Connection('memory://foo', **connection_kwargs)
y = Connection('memory://foo', **connection_kwargs)
# use separate state
x.default_channel.queues = {}
y.default_channel.queues = {}
Expand All @@ -281,7 +284,6 @@ def test_migrate(self, app, name='testcelery'):
Producer(x).publish('baz', exchange=name, routing_key=name)
assert x.default_channel.queues
assert not y.default_channel.queues

migrate_tasks(x, y, accept=['text/plain'], app=app)

yq = q(y.default_channel)
Expand Down Expand Up @@ -309,7 +311,7 @@ def effect(*args, **kwargs):
qd.side_effect = effect
migrate_tasks(x, y, app=app)

x = Connection('memory://')
x = Connection('memory://', **connection_kwargs)
x.default_channel.queues = {}
y.default_channel.queues = {}
callback = Mock()
Expand Down
10 changes: 10 additions & 0 deletions t/unit/tasks/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,16 @@ def test_autoretry(self):
self.autoretry_task.apply((1, 0))
assert self.autoretry_task.iterations == 6

def test_retry_wrong_eta_when_not_enable_utc(self):
"""Issue #3753"""
self.app.conf.enable_utc = False
self.app.conf.timezone = 'US/Eastern'
self.autoretry_task.iterations = 0
self.autoretry_task.default_retry_delay = 2

self.autoretry_task.apply((1, 0))
assert self.autoretry_task.iterations == 6


class test_canvas_utils(TasksCase):

Expand Down