Skip to content
Open
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
3 changes: 1 addition & 2 deletions kubernetes/base/leaderelection/leaderelection.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ def run(self):
logger.info("{} successfully acquired lease".format(self.election_config.lock.identity))

# Start leading and call OnStartedLeading()
threading.daemon = True
threading.Thread(target=self.election_config.onstarted_leading).start()
threading.Thread(target=self.election_config.onstarted_leading, daemon=True).start()

self.renew_loop()

Expand Down
28 changes: 28 additions & 0 deletions kubernetes/base/leaderelection/leaderelection_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import json
import time
import pytest
from unittest.mock import patch

thread_lock = threading.RLock()

Expand Down Expand Up @@ -194,6 +195,33 @@ def on_stopped_leading():

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

def test_onstarted_leading_runs_in_daemon_thread(self):
captured = {}
real_thread = threading.Thread

def record_thread(*args, **kwargs):
thread = real_thread(*args, **kwargs)
captured["daemon"] = thread.daemon
return thread

started = threading.Event()

mock_lock = MockResourceLock("mock", "mock_namespace", "mock", thread_lock,
lambda: None, lambda: None, lambda: None, None)
mock_lock.renew_count_max = 1

config = electionconfig.Config(lock=mock_lock, lease_duration=2,
renew_deadline=1.5, retry_period=1,
onstarted_leading=started.set,
onstopped_leading=lambda: None)

with patch.object(leaderelection.threading, "Thread", new=record_thread):
leaderelection.LeaderElection(config).run()

self.assertTrue(started.wait(1), "onstarted_leading callback did not run")
self.assertIn("daemon", captured)
self.assertTrue(captured["daemon"])

def assert_history(self, history, expected):
self.assertIsNotNone(expected)
self.assertIsNotNone(history)
Expand Down