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
13 changes: 10 additions & 3 deletions kubernetes/informer/informer.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ class SharedInformer:
----------
list_func:
Bound API method used for the initial list **and** as the watch
source. It must accept a watch keyword argument (e.g.
CoreV1Api().list_namespaced_pod).
source. It must accept the same keyword arguments as a generated
list function, including watch-only ones such as watch and
allow_watch_bookmarks (e.g. CoreV1Api().list_namespaced_pod).
namespace:
Kubernetes namespace to watch. Pass None for cluster-scoped
or all-namespace list functions.
Expand Down Expand Up @@ -145,7 +146,8 @@ def add_event_handler(self, event_type, handler):
:data:`BOOKMARK` or :data:`ERROR`.
handler:
Callable invoked with the event object (or the raw exception for
ERROR events).
ERROR events). BOOKMARK handlers receive the raw bookmark dict,
whose ``metadata.resourceVersion`` is the new resource version.
"""
if event_type not in self._handlers:
raise ValueError(
Expand Down Expand Up @@ -302,6 +304,11 @@ def _run_loop(self):
self._watch = Watch()
kw = self._build_kwargs()
kw["resource_version"] = self._resource_version
# Ask for BOOKMARK events so that the resource version keeps
# advancing while no matching object changes. Otherwise, once
# 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
Expand Down
64 changes: 64 additions & 0 deletions kubernetes/test/test_informer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

"""Unit tests for kubernetes.informer."""

import json
import threading
import time
import unittest
Expand Down Expand Up @@ -494,6 +495,69 @@ def fake_stream(func, **kw):

self.assertEqual(informer._resource_version, "30")

def _run_bookmark_watch(self, rtype, list_resp, bookmark):
"""Run the informer with the real Watch; return it and its requests.

The first watch yields *bookmark* and then drops; the informer is
stopped when it watches again. *rtype* is the list function's
``:rtype:``.
"""
from urllib3.exceptions import ProtocolError

calls = []

def list_func(**kw):
calls.append(kw)
if not kw.get("watch"):
return list_resp
if len(calls) == 2:
def stream(*args, **kwargs):
yield json.dumps(
{"type": BOOKMARK, "object": bookmark}) + "\n"
raise ProtocolError("Connection broken")
return MagicMock(stream=stream)
informer._stop_event.set()
informer._watch.stop()
return MagicMock()
list_func.__doc__ = rtype

informer = SharedInformer(list_func=list_func)
bookmarks = []
informer.add_event_handler(BOOKMARK, bookmarks.append)
informer.start()
informer._thread.join(timeout=3)
self.assertFalse(informer._thread.is_alive())
return calls, bookmarks

def test_watch_requests_bookmarks_and_resumes_from_bookmark(self):
"""Watch requests ask for bookmarks; after a BOOKMARK and a dropped
connection the informer re-watches from the bookmark's RV without
re-listing, for typed and dict list responses and for a list
function without a return type.
"""
bookmark = {"kind": "Pod", "apiVersion": "v1",
"metadata": {"resourceVersion": "10"}}
cases = (
("typed", ":rtype: V1PodList",
MagicMock(items=[], metadata=MagicMock(resource_version="5"))),
("dict", ":rtype: object",
{"metadata": {"resourceVersion": "5"}, "items": []}),
("untyped", None,
{"metadata": {"resourceVersion": "5"}, "items": []}),
)
for name, rtype, list_resp in cases:
with self.subTest(name):
calls, bookmarks = self._run_bookmark_watch(
rtype, list_resp, bookmark)

self.assertEqual(bookmarks, [bookmark])
self.assertEqual(len(calls), 3)
self.assertEqual(calls[0], {})
for kw, rv in ((calls[1], "5"), (calls[2], "10")):
self.assertTrue(kw["watch"])
self.assertIs(kw.get("allow_watch_bookmarks"), True)
self.assertEqual(kw["resource_version"], rv)

def test_resync_period_triggers_full_list(self):
"""A full List call must be made to the API server on every resync_period.

Expand Down
24 changes: 14 additions & 10 deletions kubernetes/watch/watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,16 @@ def get_watch_argument_name(self, func):
else:
return 'watch'

def _track_raw_resource_version(self, event):
# Record the resource version of an event that was not
# deserialized, so that a reconnect resumes from the last event.
raw = event.get('object') if isinstance(event, dict) else None
metadata = raw.get('metadata') if isinstance(raw, dict) else None
rv = metadata.get('resourceVersion') \
if isinstance(metadata, dict) else None
if rv and event.get('type') != 'ERROR':
self.resource_version = rv

def unmarshal_event(self, data, return_type):
if not data or data.isspace():
return None
Expand All @@ -149,6 +159,9 @@ def unmarshal_event(self, data, return_type):
js['raw_object'] = js['object']

if not return_type:
# The object stays a raw dict, e.g. for a lambda wrapper
# around a list function; still track its resource version.
self._track_raw_resource_version(js)
return js

if js['type'] == 'BOOKMARK':
Expand Down Expand Up @@ -250,16 +263,7 @@ def stream(self, func, *args, **kwargs):
# Blank lines are not events.
event = json.loads(line) \
if line and not line.isspace() else None
# Track the resource version from the raw dict
# so that a reconnect resumes from the last event.
raw = event.get('object') \
if isinstance(event, dict) else None
metadata = raw.get('metadata') \
if isinstance(raw, dict) else None
rv = metadata.get('resourceVersion') \
if isinstance(metadata, dict) else None
if rv and event.get('type') != 'ERROR':
self.resource_version = rv
self._track_raw_resource_version(event)
if isinstance(event, dict) \
and event['type'] == 'ERROR':
# 'object' of an ERROR event is never
Expand Down
37 changes: 37 additions & 0 deletions kubernetes/watch/watch_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,43 @@ def test_watch_with_deserialize_false_tracks_resource_version(self):
])
self.assertEqual("4", w.resource_version)

def test_watch_without_return_type_tracks_resource_version(self):
"""A list function without a return type, e.g. a lambda wrapper."""
first_resp = Mock()
first_resp.stream = Mock(return_value=[
'{"type": "ADDED", "object": {"metadata": {"name": "test1", '
'"resourceVersion": "2"}}}\n',
'{"type": "BOOKMARK", "object": {"metadata": '
'{"resourceVersion": "3"}}}\n',
'{"type": "MODIFIED", "object": {"metadata": {"name": "test1", '
'"resourceVersion": ""}}}\n',
])
second_resp = Mock()
second_resp.stream = Mock(return_value=[
'{"type": "DELETED", "object": {"metadata": {"name": "test1", '
'"resourceVersion": "4"}}}\n',
])
fake_api = Mock()
fake_api.get_namespaces = Mock(side_effect=[first_resp, second_resp])
fake_api.get_namespaces.__doc__ = ':rtype: V1NamespaceList'

w = Watch()
events = []
for e in w.stream(lambda **kw: fake_api.get_namespaces(**kw),
resource_version="1"):
events.append(e)
if e['type'] == 'DELETED':
w.stop()

self.assertEqual(['ADDED', 'BOOKMARK', 'MODIFIED', 'DELETED'],
[e['type'] for e in events])
self.assertEqual("test1", events[0]['object']['metadata']['name'])
fake_api.get_namespaces.assert_has_calls([
call(_preload_content=False, watch=True, resource_version="1"),
call(_preload_content=False, watch=True, resource_version="3"),
])
self.assertEqual("4", w.resource_version)

def test_watch_with_deserialize_false_raises_on_error_event(self):
"""410 retries once from the last event's RV; ERROR RV is ignored."""
for code, expected_rvs in ((410, ["1", "5"]), (500, ["1"])):
Expand Down