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
21 changes: 14 additions & 7 deletions src/pyinfra/operations/apt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from __future__ import annotations

from datetime import timedelta
from datetime import datetime, timedelta, timezone
from urllib.parse import urlparse

from pyinfra import host
Expand Down Expand Up @@ -309,12 +309,19 @@ def update(cache_time: int | None = None):
# Ubuntu provides this handy file
cache_info = host.get_fact(File, path=APT_UPDATE_FILENAME)

# Time on files is not tz-aware, and will be the same tz as the server's time,
# so we can safely remove the tzinfo from the Date fact before comparison.
host_cache_time = host.get_fact(Date).replace(tzinfo=None) - timedelta(seconds=cache_time)
if cache_info and cache_info["mtime"] and cache_info["mtime"] > host_cache_time:
host.noop("apt is already up to date")
return
if cache_info and cache_info["mtime"]:
# The fact Date contains the date of the server in its timezone.
# cache_info["mtime"] ignores the timezone and consider the timestamp as UTC.
# So let's do the same here for the server current Date : ignore the
# timezone and consider it as UTC to have correct comparison with
# cache_info["mtime].
host_utc_current_time = datetime.fromtimestamp(
host.get_fact(Date).timestamp(), timezone.utc
).replace(tzinfo=None)
host_cache_time = host_utc_current_time - timedelta(seconds=cache_time)
if cache_info["mtime"] > host_cache_time:
host.noop("apt is already up to date")
return

yield "apt-get update"

Expand Down
17 changes: 17 additions & 0 deletions tests/operations/apt.packages/update_cached_tz.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"kwargs": {
"update": true,
"cache_time": 3600
},
"facts": {
"deb.DebPackages": {},
"server.Date": "datetime:2015-01-01T22:44:00+01:00",
"files.File": {
"path=/var/lib/apt/periodic/update-success-stamp": {
"mtime": "datetime:2015-01-01T21:40:00"
}
}
},
"commands": [],
"noop_description": "apt is already up to date"
}