Blob Blame History Raw
From 9d2d572eaa0c4fbc48588b103a176a132e0476d9 Mon Sep 17 00:00:00 2001
From: Boris Pavlovic <boris@pavlovic.me>
Date: Wed, 26 Mar 2014 15:22:03 +0400
Subject: [PATCH] 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

Conflicts:
	novaclient/client.py
	novaclient/tests/test_client.py
	novaclient/tests/test_http.py
	novaclient/v1_1/client.py
	novaclient/v3/client.py
---
 novaclient/client.py                  |  74 +++++++++++++++--------
 novaclient/tests/test_auth_plugins.py |   8 +--
 novaclient/tests/test_client.py       | 110 +++++++++++++++++++++++++++++++++-
 novaclient/tests/test_http.py         |   8 +--
 novaclient/tests/v1_1/test_auth.py    |  12 ++--
 novaclient/v1_1/client.py             |  27 ++++++++-
 novaclient/v3/client.py               |  27 ++++++++-
 7 files changed, 221 insertions(+), 45 deletions(-)

diff --git a/novaclient/client.py b/novaclient/client.py
index 0b9aeee..7f5032b 100644
--- a/novaclient/client.py
+++ b/novaclient/client.py
@@ -39,17 +39,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):
@@ -64,12 +66,16 @@ 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):
+                 cacert=None, tenant_id=None,
+                 connection_pool=False):
         self.user = user
         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
@@ -118,8 +124,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:
@@ -180,19 +186,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', {}))
@@ -207,7 +227,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)
diff --git a/novaclient/tests/test_auth_plugins.py b/novaclient/tests/test_auth_plugins.py
index a084594..1761b98 100644
--- a/novaclient/tests/test_auth_plugins.py
+++ b/novaclient/tests/test_auth_plugins.py
@@ -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."""
diff --git a/novaclient/tests/test_client.py b/novaclient/tests/test_client.py
index d586702..96901b9 100644
--- a/novaclient/tests/test_client.py
+++ b/novaclient/tests/test_client.py
@@ -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()
@@ -216,3 +246,77 @@ class ClientTest(utils.TestCase):
         cs.password_func = mock.Mock()
         self.assertEqual(cs._get_password(), "password")
         self.assertFalse(cs.password_func.called)
+
+    def test_auth_url_rstrip_slash(self):
+        cs = novaclient.client.HTTPClient("user", "password", "project_id",
+                                          auth_url="foo/v2/")
+        self.assertEqual(cs.auth_url, "foo/v2")
+
+    def test_token_and_bypass_url(self):
+        cs = novaclient.client.HTTPClient(None, None, None,
+                                          auth_token="12345",
+                                          bypass_url="compute/v100/")
+        self.assertIsNone(cs.auth_url)
+        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)
diff --git a/novaclient/tests/test_http.py b/novaclient/tests/test_http.py
index e2fc4fa..aaa3a46 100644
--- a/novaclient/tests/test_http.py
+++ b/novaclient/tests/test_http.py
@@ -56,7 +56,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")
@@ -78,7 +78,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 = {
@@ -110,7 +110,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")
 
@@ -119,7 +119,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")
 
diff --git a/novaclient/tests/v1_1/test_auth.py b/novaclient/tests/v1_1/test_auth.py
index 7344bc7..7877145 100644
--- a/novaclient/tests/v1_1/test_auth.py
+++ b/novaclient/tests/v1_1/test_auth.py
@@ -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,
@@ -432,7 +432,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 = {
@@ -460,7 +460,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)
 
diff --git a/novaclient/v1_1/client.py b/novaclient/v1_1/client.py
index efeb5c9..ce4aea1 100644
--- a/novaclient/v1_1/client.py
+++ b/novaclient/v1_1/client.py
@@ -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):
+                  cacert=None, tenant_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
@@ -145,7 +160,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)
diff --git a/novaclient/v3/client.py b/novaclient/v3/client.py
index f26fdcf..214ba57 100644
--- a/novaclient/v3/client.py
+++ b/novaclient/v3/client.py
@@ -47,6 +47,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
@@ -59,7 +73,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):
+                  cacert=None, tenant_id=None,
+                  connection_pool=False):
         self.projectid = project_id
         self.tenant_id = tenant_id
         self.os_cache = os_cache or not no_cache
@@ -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)