Skip to content

Commit

Permalink
Fix session handling in novaclient
Browse files Browse the repository at this point in the history
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
  • Loading branch information
boris-42 and djipko committed Apr 7, 2014
1 parent 9162a5f commit 98934d7
Show file tree
Hide file tree
Showing 7 changed files with 208 additions and 46 deletions.
74 changes: 50 additions & 24 deletions novaclient/client.py
Expand Up @@ -40,17 +40,19 @@
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):
Expand All @@ -65,13 +67,17 @@ def __init__(self, user, password, projectid=None, auth_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.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
Expand Down Expand Up @@ -120,8 +126,8 @@ def __init__(self, user, password, projectid=None, auth_url=None,

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:
Expand Down Expand Up @@ -182,19 +188,33 @@ def http_log_resp(self, resp):
'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', {}))
Expand All @@ -209,7 +229,13 @@ def request(self, url, method, **kwargs):
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)
Expand Down
8 changes: 4 additions & 4 deletions novaclient/tests/test_auth_plugins.py
Expand Up @@ -92,7 +92,7 @@ def mock_iter_entry_points(_type, name):

@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",
Expand Down Expand Up @@ -121,7 +121,7 @@ def mock_iter_entry_points(_t, name=None):

@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")
Expand Down Expand Up @@ -164,7 +164,7 @@ def mock_iter_entry_points(_type, name):

@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",
Expand Down Expand Up @@ -197,7 +197,7 @@ def auth_url(self):


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."""
Expand Down
96 changes: 93 additions & 3 deletions novaclient/tests/test_client.py
Expand Up @@ -27,6 +27,16 @@
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):
Expand All @@ -43,9 +53,9 @@ def test_client_with_timeout(self):
'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)
Expand All @@ -61,7 +71,7 @@ def test_client_reauth(self):
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:
Expand Down Expand Up @@ -197,6 +207,26 @@ def test_authenticate_call_v3(self, mock_authenticate):
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()
Expand Down Expand Up @@ -230,3 +260,63 @@ def test_token_and_bypass_url(self):
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)
10 changes: 5 additions & 5 deletions novaclient/tests/test_http.py
Expand Up @@ -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")
Expand All @@ -86,7 +86,7 @@ def test_get_call():
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 = {
Expand Down Expand Up @@ -118,7 +118,7 @@ def test_auth_call():
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")

Expand All @@ -127,7 +127,7 @@ def test_refused_call():
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")

Expand All @@ -142,7 +142,7 @@ def test_client_logger(self):
"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
Expand Down
12 changes: 6 additions & 6 deletions novaclient/tests/v1_1/test_auth.py
Expand Up @@ -57,7 +57,7 @@ def test_authenticate_success(self):

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 = {
Expand Down Expand Up @@ -160,7 +160,7 @@ def side_effect(*args, **kwargs):

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 = {
Expand Down Expand Up @@ -248,7 +248,7 @@ def side_effect(*args, **kwargs):

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 = {
Expand Down Expand Up @@ -373,7 +373,7 @@ def test_authenticate_with_token_success(self):

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,
Expand Down Expand Up @@ -433,7 +433,7 @@ def test_authenticate_success(self):
})
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 = {
Expand Down Expand Up @@ -462,7 +462,7 @@ def test_authenticate_failure(self):
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)

Expand Down

0 comments on commit 98934d7

Please sign in to comment.