Skip to content

Commit

Permalink
Spread out cert renew (#66)
Browse files Browse the repository at this point in the history
* Spread out renew

* fix test

* Finish comment
  • Loading branch information
balloob authored Jun 11, 2019
1 parent 9f1a020 commit 44f0bb6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
23 changes: 18 additions & 5 deletions hass_nabucasa/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@

_LOGGER = logging.getLogger(__name__)

RENEW_IF_EXPIRES_DAYS = 25
WARN_RENEW_FAILED_DAYS = 18


class RemoteError(Exception):
"""General remote error."""
Expand Down Expand Up @@ -307,15 +310,17 @@ async def _certificate_handler(self) -> None:
"""Handle certification ACME Tasks."""
try:
while True:
await asyncio.sleep(utils.next_midnight())
await asyncio.sleep(utils.next_midnight() + random.randint(1, 3600))

# Backend not initialize / No certificate issue now
if not self._snitun:
await self.load_backend()
continue

# Renew certificate?
if self._acme.expire_date > utils.utcnow() + timedelta(days=25):
if self._acme.expire_date > utils.utcnow() + timedelta(
days=RENEW_IF_EXPIRES_DAYS
):
continue

# Renew certificate
Expand All @@ -327,9 +332,17 @@ async def _certificate_handler(self) -> None:
await asyncio.sleep(5)
await self.load_backend()
except AcmeClientError:
_LOGGER.warning(
"Renewal of ACME certificate failed. Please try again later."
)
# Only log as warning if we have a certain amount of days left
if (
self._acme.expire_date
> utils.utcnow()
< timedelta(days=WARN_RENEW_FAILED_DAYS)
):
meth = _LOGGER.warning
else:
meth = _LOGGER.debug

meth("Renewal of ACME certificate failed. Please try again later.")

except asyncio.CancelledError:
pass
Expand Down
8 changes: 6 additions & 2 deletions tests/test_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,9 @@ async def test_certificate_task_no_backend(

acme_mock.expire_date = valid

with patch("hass_nabucasa.utils.next_midnight", return_value=0) as mock_midnight:
with patch(
"hass_nabucasa.utils.next_midnight", return_value=0
) as mock_midnight, patch("random.randint", return_value=0):
remote._acme_task = loop.create_task(remote._certificate_handler())

await asyncio.sleep(0.1)
Expand Down Expand Up @@ -457,7 +459,9 @@ async def test_certificate_task_renew_cert(

acme_mock.expire_date = utcnow() + timedelta(days=-40)

with patch("hass_nabucasa.utils.next_midnight", return_value=0) as mock_midnight:
with patch("hass_nabucasa.utils.next_midnight", return_value=0), patch(
"random.randint", return_value=0
):
remote._acme_task = loop.create_task(remote._certificate_handler())

await remote.load_backend()
Expand Down

0 comments on commit 44f0bb6

Please sign in to comment.