Skip to content

Commit 75402e9

Browse files
authored
feat: Warn when the SDK is used in a forked process without postfork (#512)
1 parent e734558 commit 75402e9

2 files changed

Lines changed: 317 additions & 2 deletions

File tree

‎ldclient/client.py‎

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
This submodule contains the client class that provides most of the SDK functionality.
33
"""
44

5+
import os
56
import threading
67
import traceback
7-
from typing import Any, Callable, List, Optional, Tuple
8+
from typing import Any, Callable, Dict, List, Optional, Tuple
89
from uuid import uuid4
910

1011
from ldclient.config import Config
@@ -50,6 +51,11 @@
5051

5152
from .impl import AnyNum
5253

54+
_FORK_WARNING_MESSAGE = (
55+
"This process was forked after the LDClient was created. Background threads do not survive a fork, "
56+
"so flag updates and analytics events will not work in this process. Call LDClient.postfork() after forking."
57+
)
58+
5359

5460
class LDClient:
5561
"""The LaunchDarkly SDK client object.
@@ -84,6 +90,9 @@ def __init__(self, config: Config, start_wait: float = 5):
8490
self._eval_cached_data_warned = False
8591
self._all_flags_cached_data_warned = False
8692

93+
self._owner_pid = os.getpid()
94+
self._fork_warned_pids: Dict[int, object] = {}
95+
8796
self.__start_up(start_wait)
8897

8998
def postfork(self, start_wait: float = 5):
@@ -106,10 +115,50 @@ def postfork(self, start_wait: float = 5):
106115
that any listener or hook integrations be added postfork unless you are
107116
certain it can survive the forking process.
108117
118+
If the SDK is used in a forked child process before this method is
119+
called, it logs a warning once per process. Calling this method clears
120+
that condition for the current process.
121+
109122
:param start_wait: the number of seconds to wait for a successful connection to LaunchDarkly
110123
"""
124+
self._owner_pid = os.getpid()
125+
self._fork_warned_pids = {}
111126
self.__start_up(start_wait)
112127

128+
def _check_forked(self):
129+
"""
130+
Log a warning once per process if this client is used in a process that was forked after
131+
the client was created.
132+
133+
The "already warned" state is keyed by pid, not stored as a boolean. A boolean would be
134+
copied into every child on fork, so a grandchild process would never get its own warning.
135+
136+
The state is a dict written with ``dict.setdefault``, not a ``threading.Lock``. A lock held
137+
at the moment of a fork is inherited locked by the child and would hang its first
138+
evaluation. ``dict.setdefault`` is atomic in CPython, so many threads log exactly one warning.
139+
"""
140+
pid = os.getpid()
141+
if pid == self._owner_pid:
142+
return
143+
if not self._fork_breaks_client():
144+
return
145+
146+
token = object()
147+
if self._fork_warned_pids.setdefault(pid, token) is token:
148+
log.warning(_FORK_WARNING_MESSAGE)
149+
150+
def _fork_breaks_client(self) -> bool:
151+
"""
152+
Return true if this configuration needs background threads. Offline mode has none. LDD mode
153+
with events disabled reads flags from the persistent store and sends nothing, so a fork does
154+
not break it.
155+
"""
156+
if self._config.offline:
157+
return False
158+
if self._config.use_ldd and not self._config.send_events:
159+
return False
160+
return True
161+
113162
def __start_up(self, start_wait: float):
114163
environment_metadata = get_environment_metadata(self._config, "python-server-sdk")
115164
plugin_hooks = get_plugin_hooks(self._config.plugins, environment_metadata)
@@ -226,6 +275,7 @@ def close(self):
226275
227276
Do not attempt to use the client after calling this method.
228277
"""
278+
self._check_forked()
229279
log.info("Closing LaunchDarkly client..")
230280
self._event_processor.stop()
231281
self._data_system.stop()
@@ -253,6 +303,7 @@ def track_migration_op(self, tracker: OpTracker):
253303
Customers not using the builder should provide this method with the
254304
tracker returned from calling :func:`migration_variation`.
255305
"""
306+
self._check_forked()
256307
event = tracker.build()
257308

258309
if isinstance(event, str):
@@ -277,6 +328,7 @@ def track(self, event_name: str, context: Context, data: Optional[Any] = None, m
277328
:param metric_value: a numeric value used by the LaunchDarkly experimentation feature in
278329
numeric custom metrics; can be omitted if this event is used by only non-numeric metrics
279330
"""
331+
self._check_forked()
280332
if not context.valid:
281333
log.warning("Invalid context for track (%s)" % context.error)
282334
else:
@@ -295,7 +347,7 @@ def identify(self, context: Context):
295347
296348
:param context: the context to register
297349
"""
298-
350+
self._check_forked()
299351
if not context.valid:
300352
log.warning("Invalid context for identify (%s)" % context.error)
301353
else:
@@ -337,6 +389,7 @@ def flush(self):
337389
schedules the next event delivery to be as soon as possible; however, the delivery still
338390
happens asynchronously on a worker thread, so this method will return immediately.
339391
"""
392+
self._check_forked()
340393
if self._config.offline:
341394
return
342395
return self._event_processor.flush()
@@ -490,6 +543,8 @@ def all_flags_state(self, context: Context, **kwargs) -> FeatureFlagsState:
490543
log.warning("all_flags_state() called, but client is in offline mode. Returning empty state")
491544
return FeatureFlagsState(False)
492545

546+
self._check_forked()
547+
493548
availability = self._data_system.data_availability
494549
if availability != DataAvailability.REFRESHED:
495550
if availability == DataAvailability.CACHED:
@@ -586,6 +641,10 @@ def __evaluate_with_hooks(self, key: str, context: Context, default_value: Any,
586641
# :param block:
587642
# :return:
588643
"""
644+
# variation, variation_detail, and migration_variation all pass through here, so this one
645+
# check covers every evaluation entry point.
646+
self._check_forked()
647+
589648
hooks = [] # type: List[Hook]
590649
with self.__hooks_lock.read():
591650
if len(self.__hooks) == 0:

0 commit comments

Comments
 (0)