Fix session handling in novaclient
Prior to this patch, novaclient was handling sessions in an inconsistent manner. Every time we created a client instance, it would use a global connection pool, which made it difficult to use in a process that is meant to be forked. Obviously sessions like the ones provided by the requests library that will automatically cause connections to be kept alive should not be implicit. This patch moves the novaclient back to the age of a single session-less request call by default, but also adds two more resource-reuse friendly options that a user needs to be explicit about. The first one is that both v1_1 and v3 clients can now be used as context managers,. where the session will be kept open (and thus the connection kept-alive) for the duration of the with block. This is far more ideal for a web worker use-case as the session can be made request-long. The second one is the per-instance session. This is very similar to what we had up until now, except it is not a global object so forking is possible as long as each child instantiates it's own client. The session once created will be kept open for the duration of the client object lifetime. Please note: client instances are not thread safe. As can be seen from above forking example - if you wish to use threading/multiprocessing, you *must not* share client instances. DocImpact Related-bug: #1247056 Closes-Bug: #1297796 Co-authored-by: Nikola Dipanov <ndipanov@redhat.com> Change-Id: Id59e48f61bb3f3c6223302355c849e1e99673410
This commit is contained in:
parent
9162a5fe8f
commit
98934d7bf1
@ -40,17 +40,19 @@ from novaclient import service_catalog
|
||||
from novaclient import utils
|
||||
|
||||
|
||||
_ADAPTERS = {}
|
||||
class _ClientConnectionPool(object):
|
||||
|
||||
def __init__(self):
|
||||
self._adapters = {}
|
||||
|
||||
def _adapter_pool(url):
|
||||
"""
|
||||
Store and reuse HTTP adapters per Service URL.
|
||||
"""
|
||||
if url not in _ADAPTERS:
|
||||
_ADAPTERS[url] = adapters.HTTPAdapter()
|
||||
def get(self, url):
|
||||
"""
|
||||
Store and reuse HTTP adapters per Service URL.
|
||||
"""
|
||||
if url not in self._adapters:
|
||||
self._adapters[url] = adapters.HTTPAdapter()
|
||||
|
||||
return _ADAPTERS[url]
|
||||
return self._adapters[url]
|
||||
|
||||
|
||||
class HTTPClient(object):
|
||||
@ -65,13 +67,17 @@ class HTTPClient(object):
|
||||
os_cache=False, no_cache=True,
|
||||
http_log_debug=False, auth_system='keystone',
|
||||
auth_plugin=None, auth_token=None,
|
||||
cacert=None, tenant_id=None, user_id=None):
|
||||
cacert=None, tenant_id=None, user_id=None,
|
||||
connection_pool=False):
|
||||
self.user = user
|
||||
self.user_id = user_id
|
||||
self.password = password
|
||||
self.projectid = projectid
|
||||
self.tenant_id = tenant_id
|
||||
|
||||
self._connection_pool = (_ClientConnectionPool()
|
||||
if connection_pool else None)
|
||||
|
||||
# This will be called by #_get_password if self.password is None.
|
||||
# EG if a password can only be obtained by prompting the user, but a
|
||||
# token is available, you don't want to prompt until the token has
|
||||
@ -120,8 +126,8 @@ class HTTPClient(object):
|
||||
|
||||
self.auth_system = auth_system
|
||||
self.auth_plugin = auth_plugin
|
||||
self._session = None
|
||||
self._current_url = None
|
||||
self._http = None
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
if self.http_log_debug and not self._logger.handlers:
|
||||
@ -182,19 +188,33 @@ class HTTPClient(object):
|
||||
'headers': resp.headers,
|
||||
'text': resp.text})
|
||||
|
||||
def http(self, url):
|
||||
magic_tuple = parse.urlsplit(url)
|
||||
scheme, netloc, path, query, frag = magic_tuple
|
||||
service_url = '%s://%s' % (scheme, netloc)
|
||||
if self._current_url != service_url:
|
||||
# Invalidate Session object in case the url is somehow changed
|
||||
if self._http:
|
||||
self._http.close()
|
||||
self._current_url = service_url
|
||||
self._logger.debug("New session created for: (%s)" % service_url)
|
||||
self._http = requests.Session()
|
||||
self._http.mount(service_url, _adapter_pool(service_url))
|
||||
return self._http
|
||||
def open_session(self):
|
||||
if not self._connection_pool:
|
||||
self._session = requests.Session()
|
||||
|
||||
def close_session(self):
|
||||
if self._session and not self._connection_pool:
|
||||
self._session.close()
|
||||
self._session = None
|
||||
|
||||
def _get_session(self, url):
|
||||
if self._connection_pool:
|
||||
magic_tuple = parse.urlsplit(url)
|
||||
scheme, netloc, path, query, frag = magic_tuple
|
||||
service_url = '%s://%s' % (scheme, netloc)
|
||||
if self._current_url != service_url:
|
||||
# Invalidate Session object in case the url is somehow changed
|
||||
if self._session:
|
||||
self._session.close()
|
||||
self._current_url = service_url
|
||||
self._logger.debug(
|
||||
"New session created for: (%s)" % service_url)
|
||||
self._session = requests.Session()
|
||||
self._session.mount(service_url,
|
||||
self._connection_pool.get(service_url))
|
||||
return self._session
|
||||
elif self._session:
|
||||
return self._session
|
||||
|
||||
def request(self, url, method, **kwargs):
|
||||
kwargs.setdefault('headers', kwargs.get('headers', {}))
|
||||
@ -209,7 +229,13 @@ class HTTPClient(object):
|
||||
kwargs['verify'] = self.verify_cert
|
||||
|
||||
self.http_log_req(method, url, kwargs)
|
||||
resp = self.http(url).request(
|
||||
|
||||
request_func = requests.request
|
||||
session = self._get_session(url)
|
||||
if session:
|
||||
request_func = session.request
|
||||
|
||||
resp = request_func(
|
||||
method,
|
||||
url,
|
||||
**kwargs)
|
||||
|
@ -92,7 +92,7 @@ class DeprecatedAuthPluginTest(utils.TestCase):
|
||||
|
||||
@mock.patch.object(pkg_resources, "iter_entry_points",
|
||||
mock_iter_entry_points)
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
plugin = auth_plugin.DeprecatedAuthPlugin("fake")
|
||||
cs = client.Client("username", "password", "project_id",
|
||||
@ -121,7 +121,7 @@ class DeprecatedAuthPluginTest(utils.TestCase):
|
||||
|
||||
@mock.patch.object(pkg_resources, "iter_entry_points",
|
||||
mock_iter_entry_points)
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
auth_plugin.discover_auth_systems()
|
||||
plugin = auth_plugin.DeprecatedAuthPlugin("notexists")
|
||||
@ -164,7 +164,7 @@ class DeprecatedAuthPluginTest(utils.TestCase):
|
||||
|
||||
@mock.patch.object(pkg_resources, "iter_entry_points",
|
||||
mock_iter_entry_points)
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
plugin = auth_plugin.DeprecatedAuthPlugin("fakewithauthurl")
|
||||
cs = client.Client("username", "password", "project_id",
|
||||
@ -197,7 +197,7 @@ class DeprecatedAuthPluginTest(utils.TestCase):
|
||||
|
||||
|
||||
class AuthPluginTest(utils.TestCase):
|
||||
@mock.patch.object(requests.Session, "request")
|
||||
@mock.patch.object(requests, "request")
|
||||
@mock.patch.object(pkg_resources, "iter_entry_points")
|
||||
def test_auth_system_success(self, mock_iter_entry_points, mock_request):
|
||||
"""Test that we can authenticate using the auth system."""
|
||||
|
@ -27,6 +27,16 @@ import novaclient.v3.client
|
||||
import json
|
||||
|
||||
|
||||
class ClientConnectionPoolTest(utils.TestCase):
|
||||
|
||||
@mock.patch("novaclient.client.adapters.HTTPAdapter")
|
||||
def test_get(self, mock_http_adapter):
|
||||
mock_http_adapter.side_effect = lambda: mock.Mock()
|
||||
pool = novaclient.client._ClientConnectionPool()
|
||||
self.assertEqual(pool.get("abc"), pool.get("abc"))
|
||||
self.assertNotEqual(pool.get("abc"), pool.get("def"))
|
||||
|
||||
|
||||
class ClientTest(utils.TestCase):
|
||||
|
||||
def test_client_with_timeout(self):
|
||||
@ -43,9 +53,9 @@ class ClientTest(utils.TestCase):
|
||||
'x-server-management-url': 'blah.com',
|
||||
'x-auth-token': 'blah',
|
||||
}
|
||||
with mock.patch('requests.Session.request', mock_request):
|
||||
with mock.patch('requests.request', mock_request):
|
||||
instance.authenticate()
|
||||
requests.Session.request.assert_called_with(mock.ANY, mock.ANY,
|
||||
requests.request.assert_called_with(mock.ANY, mock.ANY,
|
||||
timeout=2,
|
||||
headers=mock.ANY,
|
||||
verify=mock.ANY)
|
||||
@ -61,7 +71,7 @@ class ClientTest(utils.TestCase):
|
||||
instance.version = 'v2.0'
|
||||
mock_request = mock.Mock()
|
||||
mock_request.side_effect = novaclient.exceptions.Unauthorized(401)
|
||||
with mock.patch('requests.Session.request', mock_request):
|
||||
with mock.patch('requests.request', mock_request):
|
||||
try:
|
||||
instance.get('/servers/detail')
|
||||
except Exception:
|
||||
@ -197,6 +207,26 @@ class ClientTest(utils.TestCase):
|
||||
cs.authenticate()
|
||||
self.assertTrue(mock_authenticate.called)
|
||||
|
||||
@mock.patch('novaclient.client.HTTPClient')
|
||||
def test_contextmanager_v1_1(self, mock_http_client):
|
||||
fake_client = mock.Mock()
|
||||
mock_http_client.return_value = fake_client
|
||||
with novaclient.v1_1.client.Client("user", "password", "project_id",
|
||||
auth_url="foo/v2") as client:
|
||||
pass
|
||||
self.assertTrue(fake_client.open_session.called)
|
||||
self.assertTrue(fake_client.close_session.called)
|
||||
|
||||
@mock.patch('novaclient.client.HTTPClient')
|
||||
def test_contextmanager_v3(self, mock_http_client):
|
||||
fake_client = mock.Mock()
|
||||
mock_http_client.return_value = fake_client
|
||||
with novaclient.v3.client.Client("user", "password", "project_id",
|
||||
auth_url="foo/v2") as client:
|
||||
pass
|
||||
self.assertTrue(fake_client.open_session.called)
|
||||
self.assertTrue(fake_client.close_session.called)
|
||||
|
||||
def test_get_password_simple(self):
|
||||
cs = novaclient.client.HTTPClient("user", "password", "", "")
|
||||
cs.password_func = mock.Mock()
|
||||
@ -230,3 +260,63 @@ class ClientTest(utils.TestCase):
|
||||
self.assertEqual(cs.auth_token, "12345")
|
||||
self.assertEqual(cs.bypass_url, "compute/v100")
|
||||
self.assertEqual(cs.management_url, "compute/v100")
|
||||
|
||||
@mock.patch("novaclient.client.requests.Session")
|
||||
def test_session(self, mock_session):
|
||||
fake_session = mock.Mock()
|
||||
mock_session.return_value = fake_session
|
||||
cs = novaclient.client.HTTPClient("user", None, "", "")
|
||||
cs.open_session()
|
||||
self.assertEqual(cs._session, fake_session)
|
||||
cs.close_session()
|
||||
self.assertIsNone(cs._session)
|
||||
|
||||
def test_session_connection_pool(self):
|
||||
cs = novaclient.client.HTTPClient("user", None, "",
|
||||
"", connection_pool=True)
|
||||
cs.open_session()
|
||||
self.assertIsNone(cs._session)
|
||||
cs.close_session()
|
||||
self.assertIsNone(cs._session)
|
||||
|
||||
def test_get_session(self):
|
||||
cs = novaclient.client.HTTPClient("user", None, "", "")
|
||||
self.assertIsNone(cs._get_session("http://nooooooooo.com"))
|
||||
|
||||
@mock.patch("novaclient.client.requests.Session")
|
||||
def test_get_session_open_session(self, mock_session):
|
||||
fake_session = mock.Mock()
|
||||
mock_session.return_value = fake_session
|
||||
cs = novaclient.client.HTTPClient("user", None, "", "")
|
||||
cs.open_session()
|
||||
self.assertEqual(fake_session, cs._get_session("http://example.com"))
|
||||
|
||||
@mock.patch("novaclient.client.requests.Session")
|
||||
@mock.patch("novaclient.client._ClientConnectionPool")
|
||||
def test_get_session_connection_pool(self, mock_pool, mock_session):
|
||||
service_url = "http://example.com"
|
||||
|
||||
pool = mock.MagicMock()
|
||||
pool.get.return_value = "http_adapter"
|
||||
mock_pool.return_value = pool
|
||||
cs = novaclient.client.HTTPClient("user", None, "",
|
||||
"", connection_pool=True)
|
||||
cs._current_url = "http://another.com"
|
||||
|
||||
session = cs._get_session(service_url)
|
||||
self.assertEqual(session, mock_session.return_value)
|
||||
pool.get.assert_called_once_with(service_url)
|
||||
mock_session().mount.assert_called_once_with(service_url,
|
||||
'http_adapter')
|
||||
|
||||
def test_init_without_connection_pool(self):
|
||||
cs = novaclient.client.HTTPClient("user", None, "", "")
|
||||
self.assertIsNone(cs._connection_pool)
|
||||
|
||||
@mock.patch("novaclient.client._ClientConnectionPool")
|
||||
def test_init_with_proper_connection_pool(self, mock_pool):
|
||||
fake_pool = mock.Mock()
|
||||
mock_pool.return_value = fake_pool
|
||||
cs = novaclient.client.HTTPClient("user", None, "",
|
||||
connection_pool=True)
|
||||
self.assertEqual(cs._connection_pool, fake_pool)
|
||||
|
@ -64,7 +64,7 @@ class ClientTest(utils.TestCase):
|
||||
def test_get(self):
|
||||
cl = get_authed_client()
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
@mock.patch('time.time', mock.Mock(return_value=1234))
|
||||
def test_get_call():
|
||||
resp, body = cl.get("/hi")
|
||||
@ -86,7 +86,7 @@ class ClientTest(utils.TestCase):
|
||||
def test_post(self):
|
||||
cl = get_authed_client()
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_post_call():
|
||||
cl.post("/hi", body=[1, 2, 3])
|
||||
headers = {
|
||||
@ -118,7 +118,7 @@ class ClientTest(utils.TestCase):
|
||||
def test_connection_refused(self):
|
||||
cl = get_client()
|
||||
|
||||
@mock.patch.object(requests.Session, "request", refused_mock_request)
|
||||
@mock.patch.object(requests, "request", refused_mock_request)
|
||||
def test_refused_call():
|
||||
self.assertRaises(exceptions.ConnectionRefused, cl.get, "/hi")
|
||||
|
||||
@ -127,7 +127,7 @@ class ClientTest(utils.TestCase):
|
||||
def test_bad_request(self):
|
||||
cl = get_client()
|
||||
|
||||
@mock.patch.object(requests.Session, "request", bad_req_mock_request)
|
||||
@mock.patch.object(requests, "request", bad_req_mock_request)
|
||||
def test_refused_call():
|
||||
self.assertRaises(exceptions.BadRequest, cl.get, "/hi")
|
||||
|
||||
@ -142,7 +142,7 @@ class ClientTest(utils.TestCase):
|
||||
"auth_test", http_log_debug=True)
|
||||
self.assertEqual(len(cl2._logger.handlers), 1)
|
||||
|
||||
@mock.patch.object(requests.Session, 'request', unknown_error_mock_request)
|
||||
@mock.patch.object(requests, 'request', unknown_error_mock_request)
|
||||
def test_unknown_server_error(self):
|
||||
cl = get_client()
|
||||
# This would be cleaner with the context manager version of
|
||||
|
@ -57,7 +57,7 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
|
||||
|
||||
mock_request = mock.Mock(return_value=(auth_response))
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
cs.client.authenticate()
|
||||
headers = {
|
||||
@ -160,7 +160,7 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
|
||||
|
||||
mock_request = mock.Mock(side_effect=side_effect)
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
cs.client.authenticate()
|
||||
headers = {
|
||||
@ -248,7 +248,7 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
|
||||
|
||||
mock_request = mock.Mock(side_effect=side_effect)
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
cs.client.authenticate()
|
||||
headers = {
|
||||
@ -373,7 +373,7 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
|
||||
|
||||
mock_request = mock.Mock(return_value=(auth_response))
|
||||
|
||||
with mock.patch.object(requests.Session, "request", mock_request):
|
||||
with mock.patch.object(requests, "request", mock_request):
|
||||
cs.client.authenticate()
|
||||
headers = {
|
||||
'User-Agent': cs.client.USER_AGENT,
|
||||
@ -433,7 +433,7 @@ class AuthenticationTests(utils.TestCase):
|
||||
})
|
||||
mock_request = mock.Mock(return_value=(auth_response))
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
cs.client.authenticate()
|
||||
headers = {
|
||||
@ -462,7 +462,7 @@ class AuthenticationTests(utils.TestCase):
|
||||
auth_response = utils.TestResponse({'status_code': 401})
|
||||
mock_request = mock.Mock(return_value=(auth_response))
|
||||
|
||||
@mock.patch.object(requests.Session, "request", mock_request)
|
||||
@mock.patch.object(requests, "request", mock_request)
|
||||
def test_auth_call():
|
||||
self.assertRaises(exceptions.Unauthorized, cs.client.authenticate)
|
||||
|
||||
|
@ -61,6 +61,20 @@ class Client(object):
|
||||
>>> client.flavors.list()
|
||||
...
|
||||
|
||||
It is also possible to use an instance as a context manager in which
|
||||
case there will be a session kept alive for the duration of the with
|
||||
statement::
|
||||
|
||||
>>> with Client(USERNAME, PASSWORD, PROJECT_ID, AUTH_URL) as client:
|
||||
... client.servers.list()
|
||||
... client.flavors.list()
|
||||
...
|
||||
|
||||
It is also possible to have a permanent (process-long) connection pool,
|
||||
by passing a connection_pool=True::
|
||||
|
||||
>>> client = Client(USERNAME, PASSWORD, PROJECT_ID,
|
||||
... AUTH_URL, connection_pool=True)
|
||||
"""
|
||||
|
||||
# FIXME(jesse): project_id isn't required to authenticate
|
||||
@ -73,7 +87,8 @@ class Client(object):
|
||||
bypass_url=None, os_cache=False, no_cache=True,
|
||||
http_log_debug=False, auth_system='keystone',
|
||||
auth_plugin=None, auth_token=None,
|
||||
cacert=None, tenant_id=None, user_id=None):
|
||||
cacert=None, tenant_id=None, user_id=None,
|
||||
connection_pool=False):
|
||||
# FIXME(comstud): Rename the api_key argument above when we
|
||||
# know it's not being used as keyword argument
|
||||
password = api_key
|
||||
@ -147,7 +162,15 @@ class Client(object):
|
||||
bypass_url=bypass_url,
|
||||
os_cache=self.os_cache,
|
||||
http_log_debug=http_log_debug,
|
||||
cacert=cacert)
|
||||
cacert=cacert,
|
||||
connection_pool=connection_pool)
|
||||
|
||||
def __enter__(self):
|
||||
self.client.open_session()
|
||||
return self
|
||||
|
||||
def __exit__(self, t, v, tb):
|
||||
self.client.close_session()
|
||||
|
||||
def set_management_url(self, url):
|
||||
self.client.set_management_url(url)
|
||||
|
@ -46,6 +46,20 @@ class Client(object):
|
||||
>>> client.flavors.list()
|
||||
...
|
||||
|
||||
It is also possible to use an instance as a context manager in which
|
||||
case there will be a session kept alive for the duration of the with
|
||||
statement::
|
||||
|
||||
>>> with Client(USERNAME, PASSWORD, PROJECT_ID, AUTH_URL) as client:
|
||||
... client.servers.list()
|
||||
... client.flavors.list()
|
||||
...
|
||||
|
||||
It is also possible to have a permanent (process-long) connection pool,
|
||||
by passing a connection_pool=True::
|
||||
|
||||
>>> client = Client(USERNAME, PASSWORD, PROJECT_ID,
|
||||
... AUTH_URL, connection_pool=True)
|
||||
"""
|
||||
|
||||
# FIXME(jesse): project_id isn't required to authenticate
|
||||
@ -58,7 +72,8 @@ class Client(object):
|
||||
bypass_url=None, os_cache=False, no_cache=True,
|
||||
http_log_debug=False, auth_system='keystone',
|
||||
auth_plugin=None, auth_token=None,
|
||||
cacert=None, tenant_id=None, user_id=None):
|
||||
cacert=None, tenant_id=None, user_id=None,
|
||||
connection_pool=False):
|
||||
self.projectid = project_id
|
||||
self.tenant_id = tenant_id
|
||||
self.user_id = user_id
|
||||
@ -110,7 +125,15 @@ class Client(object):
|
||||
bypass_url=bypass_url,
|
||||
os_cache=os_cache,
|
||||
http_log_debug=http_log_debug,
|
||||
cacert=cacert)
|
||||
cacert=cacert,
|
||||
connection_pool=connection_pool)
|
||||
|
||||
def __enter__(self):
|
||||
self.client.open_session()
|
||||
return self
|
||||
|
||||
def __exit__(self, t, v, tb):
|
||||
self.client.close_session()
|
||||
|
||||
def set_management_url(self, url):
|
||||
self.client.set_management_url(url)
|
||||
|
Loading…
Reference in New Issue
Block a user