-
Notifications
You must be signed in to change notification settings - Fork 304
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
avoids creating a kubernetes client for each Spawner, which creates a bunch of threads in kubernetes 4.0. uses weakref to avoid breaking garbage collection
- Loading branch information
Showing
3 changed files
with
33 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import weakref | ||
|
||
import kubernetes.client | ||
|
||
_client_cache = {} | ||
|
||
|
||
def shared_client(ClientType, *args, **kwargs): | ||
"""Return a single shared kubernetes client instance | ||
A weak reference to the instance is cached, | ||
so that concurrent calls to shared_client | ||
will all return the same instance until | ||
all references to the client are cleared. | ||
""" | ||
kwarg_key = tuple((key, kwargs[key]) for key in sorted(kwargs)) | ||
cache_key = (ClientType, args, kwarg_key) | ||
client = None | ||
if cache_key in _client_cache: | ||
client = _client_cache[cache_key]() | ||
|
||
if client is None: | ||
Client = getattr(kubernetes.client, ClientType) | ||
client = Client(*args, **kwargs) | ||
# cache weakref so that clients can be garbage collected | ||
_client_cache[cache_key] = weakref.ref(client) | ||
return client |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters