Skip to content

Commit 2ea2c0a

Browse files
Merge pull request #2820 from ilcm96/informer-stop-hang
Fix SharedInformer.stop() hang during initial list, spurious watch errors, and calls from event handlers
2 parents e3afbb1 + b47c043 commit 2ea2c0a

2 files changed

Lines changed: 131 additions & 3 deletions

File tree

‎kubernetes/informer/informer.py‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,12 +224,25 @@ def start(self):
224224
self._thread.start()
225225

226226
def stop(self):
227-
"""Ask the background watch loop to stop and join the thread."""
227+
"""Ask the background watch loop to stop and join the thread.
228+
229+
When called from an event handler, it returns without waiting for
230+
the thread to exit, and start() has no effect until the thread
231+
exits; call stop() from another thread to wait for it.
232+
"""
233+
# Set the event before reading _watch: _run_loop publishes _watch
234+
# before re-checking the event. Read _watch once because the loop
235+
# may reset it to None concurrently.
228236
self._stop_event.set()
229237
with self._sync_cond:
230238
self._sync_cond.notify_all()
231-
if self._watch is not None:
232-
self._watch.stop()
239+
watch = self._watch
240+
if watch is not None:
241+
watch.stop()
242+
if self._thread is threading.current_thread():
243+
# Keep _thread so that start() does not run a second loop
244+
# while this one is still exiting.
245+
return
233246
if self._thread is not None:
234247
self._thread.join()
235248
self._thread = None
@@ -345,6 +358,13 @@ def _run_loop(self):
345358
# Watch loop
346359
last_resync = time.monotonic()
347360
self._watch = Watch()
361+
# stop() may have run during the list above, when there was no
362+
# Watch to stop. Check again after publishing self._watch so
363+
# that such a stop() does not open a watch; a stop() that sees
364+
# the new Watch relies on Watch.stop().
365+
if self._stop_event.is_set():
366+
self._watch = None
367+
break
348368
kw = self._build_kwargs()
349369
kw["resource_version"] = self._resource_version
350370
# Ask for BOOKMARK events so that the resource version keeps
@@ -406,6 +426,10 @@ def _run_loop(self):
406426
)
407427
self._fire(ERROR, exc)
408428
except Exception as exc:
429+
if self._stop_event.is_set():
430+
# An error after stop was requested is not a failure:
431+
# stop() shuts the connection down, so the read fails.
432+
break
409433
stream_closed = isinstance(exc, _WATCH_CLOSED_ERRORS)
410434
watch_end = time.monotonic()
411435
logger.exception("Unexpected error in watch loop; reconnecting")

‎kubernetes/test/test_informer.py‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1495,6 +1495,110 @@ def fake_stream(func, **kw):
14951495
# Still in cache.
14961496
self.assertIsNotNone(informer.cache.get_by_key("default/stable-pod"))
14971497

1498+
def test_stop_during_initial_list_does_not_open_watch(self):
1499+
"""stop() during the initial list returns without opening a watch."""
1500+
list_started = threading.Event()
1501+
release_list = threading.Event()
1502+
release_watch = threading.Event()
1503+
self.addCleanup(release_watch.set)
1504+
self.addCleanup(release_list.set)
1505+
1506+
list_resp = MagicMock()
1507+
list_resp.items = []
1508+
list_resp.metadata = MagicMock(resource_version="1")
1509+
1510+
def list_func(**kw):
1511+
list_started.set()
1512+
release_list.wait(timeout=10)
1513+
return list_resp
1514+
1515+
informer = SharedInformer(list_func=list_func)
1516+
1517+
with patch("kubernetes.informer.informer.Watch") as MockWatch:
1518+
mock_w = MagicMock()
1519+
1520+
def fake_stream(func, **kw):
1521+
# A quiet resource: the stream blocks without yielding events.
1522+
release_watch.wait(timeout=10)
1523+
return iter([])
1524+
1525+
mock_w.stream.side_effect = fake_stream
1526+
MockWatch.return_value = mock_w
1527+
1528+
informer.start()
1529+
self.assertTrue(list_started.wait(timeout=3))
1530+
worker = informer._thread
1531+
stopper = threading.Thread(target=informer.stop, daemon=True)
1532+
stopper.start()
1533+
self.assertTrue(informer._stop_event.wait(timeout=3))
1534+
1535+
release_list.set()
1536+
stopper.join(timeout=3)
1537+
stop_returned = not stopper.is_alive()
1538+
# Unblock a watch opened by mistake so the worker can exit.
1539+
release_watch.set()
1540+
worker.join(timeout=3)
1541+
1542+
self.assertTrue(stop_returned, "stop() did not return after the list")
1543+
mock_w.stream.assert_not_called()
1544+
self.assertFalse(worker.is_alive())
1545+
1546+
def test_stop_during_watch_does_not_report_read_error(self):
1547+
"""The read error caused by stop() is not reported as a failure."""
1548+
from urllib3.exceptions import ProtocolError
1549+
1550+
list_func = MagicMock(return_value=MagicMock(
1551+
items=[], metadata=MagicMock(resource_version="1")))
1552+
informer = SharedInformer(list_func=list_func)
1553+
errors = []
1554+
informer.add_event_handler(ERROR, errors.append)
1555+
watching = threading.Event()
1556+
shut_down = threading.Event()
1557+
self.addCleanup(shut_down.set)
1558+
1559+
def fake_stream(func, **kw):
1560+
# Watch.stop() shuts the connection down, so the read fails.
1561+
watching.set()
1562+
shut_down.wait(timeout=10)
1563+
raise ProtocolError("Response ended prematurely")
1564+
1565+
with patch("kubernetes.informer.informer.Watch") as MockWatch, \
1566+
self.assertNoLogs("kubernetes.informer.informer", "WARNING"):
1567+
MockWatch.return_value.stream.side_effect = fake_stream
1568+
MockWatch.return_value.stop.side_effect = shut_down.set
1569+
informer.start()
1570+
self.assertTrue(watching.wait(timeout=3))
1571+
informer.stop()
1572+
1573+
self.assertEqual(errors, [])
1574+
1575+
def test_stop_from_handler_returns_to_handler(self):
1576+
"""stop() called from a handler returns, and start() works again."""
1577+
pod = _make_pod("default", "p")
1578+
list_func = MagicMock(return_value=MagicMock(
1579+
items=[], metadata=MagicMock(resource_version="1")))
1580+
informer = SharedInformer(list_func=list_func)
1581+
after_stop = []
1582+
1583+
def handler(obj):
1584+
informer.stop()
1585+
after_stop.append(obj)
1586+
1587+
informer.add_event_handler(ADDED, handler)
1588+
1589+
with patch("kubernetes.informer.informer.Watch") as MockWatch, \
1590+
self.assertNoLogs("kubernetes.informer.informer", "WARNING"):
1591+
MockWatch.return_value.stream.side_effect = \
1592+
lambda func, **kw: iter([{"type": ADDED, "object": pod}])
1593+
informer.start()
1594+
informer._thread.join(timeout=3)
1595+
informer.start()
1596+
second = informer._thread
1597+
second.join(timeout=3)
1598+
1599+
self.assertEqual(after_stop, [pod, pod])
1600+
self.assertFalse(second.is_alive())
1601+
14981602

14991603
if __name__ == "__main__":
15001604
unittest.main()

0 commit comments

Comments
 (0)