diff --git a/kubernetes/informer/informer.py b/kubernetes/informer/informer.py index 5cc79c5474..3ce56ef1f2 100644 --- a/kubernetes/informer/informer.py +++ b/kubernetes/informer/informer.py @@ -20,6 +20,7 @@ """ import logging +import math import random import threading import time @@ -92,7 +93,13 @@ class SharedInformer: Kubernetes namespace to watch. Pass None for cluster-scoped or all-namespace list functions. resync_period: - How often (seconds) to perform a full re-list from the API server. + How often (seconds) to perform a full re-list from the API server, + counted from the end of the previous list, or from the restart when + :meth:`start` resumes after :meth:`stop` without a re-list. On a + healthy watch the resync runs when the watch ends on its server-side + timeout, which has whole-second granularity, so it can run up to a + second late and a fractional period is effectively rounded up. After + a watch failure it runs once the reconnect backoff wait ends. Defaults to 0 which disables periodic resyncs. label_selector: Optional label selector string forwarded to the API server. @@ -341,9 +348,16 @@ def _run_loop(self): reconnects the most recent ``resourceVersion`` is reused so that no events are missed and the API server does not need to send a full object snapshot. + + A periodic resync is due ``resync_period`` seconds after the last + list, or after the loop starts if it resumes without a list. Watch + reconnects do not restart this deadline; a resync that falls due + during a backoff wait runs when the wait ends. """ backoff_duration = _WATCH_BACKOFF_INITIAL last_backoff_at = time.monotonic() + resync_period = float(self._resync_period) + next_resync = time.monotonic() + resync_period while not self._stop_event.is_set(): # Full re-list only when we have no resource version to resume from. if self._resource_version is None: @@ -354,9 +368,9 @@ def _run_loop(self): self._fire(ERROR, exc) self._stop_event.wait(timeout=5) continue + next_resync = time.monotonic() + resync_period # Watch loop - last_resync = time.monotonic() self._watch = Watch() # stop() may have run during the list above, when there was no # Watch to stop. Check again after publishing self._watch so @@ -372,13 +386,15 @@ def _run_loop(self): # other changes push that version out of the server's watch # history, a reconnect gets 410 Gone and forces a full re-list. kw["allow_watch_bookmarks"] = True - # When a resync period is configured, set a matching server-side - # watch timeout so that the stream exits after resync_period seconds - # even if no events arrive. Without this, a quiet period longer - # than resync_period would never trigger a resync because the check - # below only runs when the generator yields an event. + # When a resync period is configured, set a server-side watch + # timeout so that the stream ends when the next resync is due even + # if no events arrive. Otherwise the stream never returns to this + # loop, because Watch.stream reconnects a closed stream by itself. + # Round up so that the stream does not end before the resync is + # due. if self._resync_period > 0: - kw["timeout_seconds"] = max(1, int(self._resync_period)) + kw["timeout_seconds"] = max( + 1, math.ceil(next_resync - time.monotonic())) stream_closed = False got_event = False watch_start = time.monotonic() @@ -465,11 +481,15 @@ def _run_loop(self): # server-side timeout_seconds, a stop request, or an error) check if # a resync is due. This path is what actually fires the resync when # the cluster is quiet and no events arrive for resync_period seconds. + # When the loop backed off above, the check runs once the wait + # ends, so the list request is throttled by the same backoff. The + # wait counts towards the deadline and every list sets a new one, + # so periodic resync lists are still at least resync_period apart. if ( not self._stop_event.is_set() and self._resource_version is not None # 410 already schedules a re-list and self._resync_period > 0 - and (time.monotonic() - last_resync) >= self._resync_period + and time.monotonic() >= next_resync ): logger.debug("Informer resync triggered") try: @@ -477,3 +497,4 @@ def _run_loop(self): except Exception as exc: logger.exception("Error during resync list; continuing") self._fire(ERROR, exc) + next_resync = time.monotonic() + resync_period diff --git a/kubernetes/test/test_informer.py b/kubernetes/test/test_informer.py index ac385f0901..f148f4f607 100644 --- a/kubernetes/test/test_informer.py +++ b/kubernetes/test/test_informer.py @@ -18,6 +18,7 @@ import threading import time import unittest +from decimal import Decimal from unittest.mock import MagicMock, patch from kubernetes.informer.cache import ObjectCache, _meta_namespace_key @@ -561,10 +562,10 @@ def test_watch_requests_bookmarks_and_resumes_from_bookmark(self): def test_resync_period_triggers_full_list(self): """A full List call must be made to the API server on every resync_period. - With the new implementation the watch stream is given a server-side - timeout equal to resync_period (via timeout_seconds). When the stream - exits, the elapsed-time check fires the resync even if no events - arrived – this is exactly the scenario this test exercises. + The watch stream is given a server-side timeout equal to the time left + until the next resync (via timeout_seconds). When the stream exits, + the deadline check fires the resync even if no events arrived – this + is exactly the scenario this test exercises. """ pod = _make_pod("default", "resync-pod") @@ -608,6 +609,133 @@ def fake_stream(func, **kw): # list_func called once for the initial list + once for the resync = 2 self.assertEqual(list_func.call_count, 2) + def _run_resync_on_fake_clock(self, resync_period, run_for, + watch_seconds=None, watch_error_at=(), + list_error_at=(), restart=None): + """Run the informer on a fake clock; return lists, timeouts and waits. + + The informer stops at the first watch it opens once the fake time is + *run_for* or later, so a resync due at that point still runs. Each + watch lasts *watch_seconds* (default: the requested + timeout_seconds, as the server honours it) and then ends cleanly, or + raises a 500 if its 1-based number is in *watch_error_at*. List calls + whose number is in *list_error_at* raise a 500. Backoff waits advance + the clock without sleeping. With *restart* = (at, run_for), the + stopped informer is started again at fake time *at* and runs until the + new *run_for*. + """ + from kubernetes.client.exceptions import ApiException + + now = [0.0] + stop_at = [run_for] + list_times, timeouts = [], [] + + def list_func(**kw): + list_times.append(now[0]) + if len(list_times) in list_error_at: + raise ApiException(status=500) + return MagicMock( + items=[], metadata=MagicMock(resource_version="1")) + + informer = SharedInformer(list_func=list_func, + resync_period=resync_period) + informer._stop_event = stop_event = _RecordingStopEvent(now) + + def fake_stream(func, **kw): + if now[0] >= stop_at[0]: + stop_event.set() + return iter([]) + timeouts.append(kw["timeout_seconds"]) + now[0] += (kw["timeout_seconds"] if watch_seconds is None + else watch_seconds) + if len(timeouts) in watch_error_at: + raise ApiException(status=500) + return iter([]) + + with patch("kubernetes.informer.informer.Watch") as MockWatch, \ + patch("kubernetes.informer.informer.time") as mock_time, \ + patch("random.random", return_value=0.0): + mock_time.monotonic.side_effect = lambda: now[0] + MockWatch.return_value.stream.side_effect = fake_stream + MockWatch.return_value.resource_version = "1" + + informer.start() + informer._thread.join(timeout=3) + if restart: + informer.stop() + now[0], stop_at[0] = restart + informer.start() + informer._thread.join(timeout=3) + + self.assertFalse(informer._thread.is_alive()) + return [round(t, 3) for t in list_times], timeouts, stop_event.waits + + def test_resync_period_counts_from_last_list(self): + """A full List runs every resync_period, counted from the last list. + + The watch timeout is rounded up to whole seconds, so a fractional + period resyncs at the next whole second. A watch that closes after + 1s is not a very short watch, so it reconnects without backoff. + """ + cases = ( + ("integer period", 2, None, [0, 2, 4, 6], [2, 2, 2]), + ("fractional period", 1.5, None, [0, 2, 4, 6], [2, 2, 2]), + ("Decimal period", Decimal("1.5"), None, [0, 2, 4, 6], [2, 2, 2]), + ("watch closes early", 3, 1, [0, 3, 6], [3, 2, 1] * 2), + ) + for name, period, watch_seconds, expected_lists, \ + expected_timeouts in cases: + with self.subTest(name): + list_times, timeouts, waits = self._run_resync_on_fake_clock( + period, run_for=6, watch_seconds=watch_seconds) + + self.assertEqual(list_times, expected_lists) + self.assertEqual(timeouts, expected_timeouts) + self.assertEqual(waits, []) + + def test_resync_after_failure(self): + """Failures neither starve the resync nor list more than once a period. + + After a failed watch the due resync is sent once the backoff wait + ends, and the watch reconnects without another wait. Backoff waits + count towards the period, so a watch that keeps failing right away + lists once per wait once the waits exceed the period. A failed + resync list is retried one period later, as a successful one is. + """ + cases = ( + ("watch fails when resync is due", + dict(resync_period=2, run_for=4.5, watch_error_at={1}), + [0, 2.8, 4.8], [2, 2], [0.8]), + ("watch keeps failing right away", + dict(resync_period=1, run_for=11, watch_seconds=0, + watch_error_at=range(1, 10)), + [0, 2.4, 5.6, 12], [1, 1, 1, 1], [0.8, 1.6, 3.2, 6.4]), + ("resync list fails", + dict(resync_period=2, run_for=4.5, list_error_at={2}), + [0, 2, 4, 6], [2, 2, 2], []), + ) + for name, kwargs, expected_lists, expected_timeouts, \ + expected_waits in cases: + with self.subTest(name): + list_times, timeouts, waits = self._run_resync_on_fake_clock( + **kwargs) + + self.assertEqual(list_times, expected_lists) + self.assertEqual(timeouts, expected_timeouts) + self.assertEqual(waits, expected_waits) + + def test_restart_resyncs_one_period_after_start(self): + """stop() then start() resumes the watch and keeps resyncing. + + The resource version is kept, so the restart skips the list and the + first resync is due one period after the restart. + """ + list_times, timeouts, _ = self._run_resync_on_fake_clock( + 2, run_for=2, restart=(100, 104)) + + self.assertEqual(list_times, [0, 2, 102, 104]) + self.assertEqual(timeouts, [2, 2, 2]) + # ------------------------------------------------------------------ # Tests analogous to the JavaScript cache_test.ts and Java # DefaultSharedIndexInformerWireMockTest scenarios.