Skip to content

Commit

Permalink
Merge pull request kubernetes-client#1073 from fabianvf/fix-py3-hang
Browse files Browse the repository at this point in the history
Cleanup ThreadPool with atexit rather than __del__

(cherry picked from commit 0976d59)
  • Loading branch information
k8s-ci-robot authored and fabianvf committed Feb 11, 2020
1 parent df6fdd2 commit 59f4bfd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
14 changes: 12 additions & 2 deletions kubernetes/client/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import os
import re
import json
import atexit
import mimetypes
import tempfile
from multiprocessing.pool import ThreadPool
Expand Down Expand Up @@ -74,19 +75,28 @@ def __init__(self, configuration=None, header_name=None, header_value=None,
self.cookie = cookie
# Set default User-Agent.
self.user_agent = 'Swagger-Codegen/10.0.1/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
25 changes: 25 additions & 0 deletions kubernetes/test/test_api_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# coding: utf-8


import atexit
import weakref
import unittest

import kubernetes


class TestApiClient(unittest.TestCase):

def test_context_manager_closes_threadpool(self):
with kubernetes.client.ApiClient() as client:
self.assertIsNotNone(client.pool)
pool_ref = weakref.ref(client._pool)
self.assertIsNotNone(pool_ref())
self.assertIsNone(pool_ref())

def test_atexit_closes_threadpool(self):
client = kubernetes.client.ApiClient()
self.assertIsNotNone(client.pool)
self.assertIsNotNone(client._pool)
atexit._run_exitfuncs()
self.assertIsNone(client._pool)

0 comments on commit 59f4bfd

Please sign in to comment.