Skip to content

Commit bb887bb

Browse files
archy-rock3t-cloudyliaog
authored andcommitted
Fix leader election worker thread not running as daemon
Signed-off-by: Artem Muterko <artem@sopho.tech>
1 parent 675392c commit bb887bb

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

kubernetes/base/leaderelection/leaderelection.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,7 @@ def run(self):
5555
logger.info("{} successfully acquired lease".format(self.election_config.lock.identity))
5656

5757
# Start leading and call OnStartedLeading()
58-
threading.daemon = True
59-
threading.Thread(target=self.election_config.onstarted_leading).start()
58+
threading.Thread(target=self.election_config.onstarted_leading, daemon=True).start()
6059

6160
self.renew_loop()
6261

kubernetes/base/leaderelection/leaderelection_test.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import json
2323
import time
2424
import pytest
25+
from unittest.mock import patch
2526

2627
thread_lock = threading.RLock()
2728

@@ -194,6 +195,33 @@ def on_stopped_leading():
194195

195196
self.assert_history(leadership_history, ["get leadership", "start leading", "stop leading"])
196197

198+
def test_onstarted_leading_runs_in_daemon_thread(self):
199+
captured = {}
200+
real_thread = threading.Thread
201+
202+
def record_thread(*args, **kwargs):
203+
thread = real_thread(*args, **kwargs)
204+
captured["daemon"] = thread.daemon
205+
return thread
206+
207+
started = threading.Event()
208+
209+
mock_lock = MockResourceLock("mock", "mock_namespace", "mock", thread_lock,
210+
lambda: None, lambda: None, lambda: None, None)
211+
mock_lock.renew_count_max = 1
212+
213+
config = electionconfig.Config(lock=mock_lock, lease_duration=2,
214+
renew_deadline=1.5, retry_period=1,
215+
onstarted_leading=started.set,
216+
onstopped_leading=lambda: None)
217+
218+
with patch.object(leaderelection.threading, "Thread", new=record_thread):
219+
leaderelection.LeaderElection(config).run()
220+
221+
self.assertTrue(started.wait(1), "onstarted_leading callback did not run")
222+
self.assertIn("daemon", captured)
223+
self.assertTrue(captured["daemon"])
224+
197225
def assert_history(self, history, expected):
198226
self.assertIsNotNone(expected)
199227
self.assertIsNotNone(history)

0 commit comments

Comments
 (0)