Skip to content

Commit

Permalink
Cleanup ThreadPool with atexit rather than __del__
Browse files Browse the repository at this point in the history
This removes the __del__ function from the generated Python client,
and replaces it with a cleanup function. When a ThreadPool is created,
the cleanup function is registered with the atexit module.

This PR also allows the client to be used as a context manager, which
will automatically clean up after itself rather than having to wait til
process exit.

This fixes #1037, where the API client could hang indefinitely at
garbage collection.
  • Loading branch information
fabianvf committed Feb 6, 2020
1 parent 5181d23 commit 9a5138a
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion kubernetes/client/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from __future__ import absolute_import

import atexit
import datetime
import json
import mimetypes
Expand Down Expand Up @@ -77,18 +78,27 @@ def __init__(self, configuration=None, header_name=None, header_value=None,
# Set default User-Agent.
self.user_agent = 'OpenAPI-Generator/11.0.0-snapshot/python'

def __del__(self):
def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self.close()

def close(self):
if self._pool:
self._pool.close()
self._pool.join()
self._pool = None
if hasattr(atexit, 'unregister'):
atexit.unregister(self.close)

@property
def pool(self):
"""Create thread pool on first request
avoids instantiating unused threadpool for blocking clients.
"""
if self._pool is None:
atexit.register(self.close)
self._pool = ThreadPool(self.pool_threads)
return self._pool

Expand Down

0 comments on commit 9a5138a

Please # to comment.