<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[15780] twext/trunk/twext/who/ldap</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/15780">15780</a></dd>
<dt>Author</dt> <dd>sagen@apple.com</dd>
<dt>Date</dt> <dd>2016-08-02 16:24:05 -0700 (Tue, 02 Aug 2016)</dd>
</dl>

<h3>Log Message</h3>
<pre>Use a connection pool for the LDAP bind calls we use for authentication (in addition to the already existing pool used for other LDAP queries)</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#twexttrunktwextwholdap_servicepy">twext/trunk/twext/who/ldap/_service.py</a></li>
<li><a href="#twexttrunktwextwholdaptesttest_servicepy">twext/trunk/twext/who/ldap/test/test_service.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="twexttrunktwextwholdap_servicepy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/who/ldap/_service.py (15779 => 15780)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/ldap/_service.py        2016-07-27 21:50:59 UTC (rev 15779)
+++ twext/trunk/twext/who/ldap/_service.py        2016-08-02 23:24:05 UTC (rev 15780)
</span><span class="lines">@@ -203,7 +203,165 @@
</span><span class="cx"> })
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+class ConnectionPool(object):
</ins><span class="cx"> 
</span><ins>+    log = Logger()
+
+    def __init__(self, poolName, ds, credentials, connectionMax):
+        self.poolName = poolName
+        self.ds = ds
+        self.credentials = credentials
+        self.connectionQueue = Queue()
+        self.connectionCreateLock = RLock()
+        self.connections = []
+        self.activeCount = 0
+        self.connectionsCreated = 0
+        self.connectionMax = connectionMax
+
+    def getConnection(self):
+        &quot;&quot;&quot;
+        Get a connection from the connection pool.
+        This will retrieve a connection from the connection pool L{Queue}
+        object.
+        If the L{Queue} is empty, it will check to see whether a new connection
+        can be created (based on the connection limit), and if so create that
+        and use it.
+        If no new connections can be created, it will block on the L{Queue}
+        until an existing, in-use, connection is put back.
+        &quot;&quot;&quot;
+        try:
+            connection = self.connectionQueue.get(block=False)
+        except Empty:
+            # Note we use a lock here to prevent a race condition in which
+            # multiple requests for a new connection could succeed even though
+            # the connection counts starts out one less than the maximum.
+            # This can happen because self._connect() can take a while.
+            self.connectionCreateLock.acquire()
+            if len(self.connections) &lt; self.connectionMax:
+                connection = self._connect()
+                self.connections.append(connection)
+                self.connectionCreateLock.release()
+            else:
+                self.connectionCreateLock.release()
+                self.ds.poolStats[&quot;connection-blocked&quot;] += 1
+                connection = self.connectionQueue.get()
+
+
+        connectionID = &quot;connection-{}&quot;.format(
+            self.connections.index(connection)
+        )
+
+        self.ds.poolStats[connectionID] += 1
+        self.activeCount = len(self.connections) - self.connectionQueue.qsize()
+        self.ds.poolStats[&quot;connection-active&quot;] = self.activeCount
+        self.ds.poolStats[&quot;connection-max&quot;] = max(
+            self.ds.poolStats[&quot;connection-max&quot;], self.activeCount
+        )
+
+        if self.activeCount &gt; self.connectionMax:
+            self.log.error(
+                &quot;Active LDAP connections ({active}) exceeds maximum ({max})&quot;,
+                active=self.activeCount, max=self.connectionMax
+            )
+        return connection
+
+
+    def returnConnection(self, connection):
+        &quot;&quot;&quot;
+        A connection is no longer needed - return it to the pool.
+        &quot;&quot;&quot;
+        self.connectionQueue.put(connection)
+        self.activeCount = len(self.connections) - self.connectionQueue.qsize()
+
+
+    def failedConnection(self, connection):
+        &quot;&quot;&quot;
+        A connection has failed; remove it from the list of active connections.
+        A new one will be created if needed.
+        &quot;&quot;&quot;
+        self.ds.poolStats[&quot;connection-errors&quot;] += 1
+        self.connections.remove(connection)
+        self.activeCount = len(self.connections) - self.connectionQueue.qsize()
+
+
+    def _connect(self):
+        &quot;&quot;&quot;
+        Connect to the directory server.
+        This will always be called in a thread to prevent blocking.
+
+        @returns: The connection object.
+        @rtype: L{ldap.ldapobject.LDAPObject}
+
+        @raises: L{LDAPConnectionError} if unable to connect.
+        &quot;&quot;&quot;
+
+        self.log.debug(&quot;Connecting to LDAP at {log_source.url}&quot;)
+        connection = self._newConnection()
+
+        if self.credentials is not None:
+            if IUsernamePassword.providedBy(self.credentials):
+                try:
+                    connection.simple_bind_s(
+                        self.credentials.username,
+                        self.credentials.password,
+                    )
+                    self.log.debug(
+                        &quot;Bound to LDAP as {credentials.username}&quot;,
+                        credentials=self.credentials
+                    )
+                except (
+                    ldap.INVALID_CREDENTIALS, ldap.INVALID_DN_SYNTAX
+                ) as e:
+                    self.log.error(
+                        &quot;Unable to bind to LDAP as {credentials.username}&quot;,
+                        credentials=self.credentials
+                    )
+                    raise LDAPBindAuthError(
+                        self.credentials.username, e
+                    )
+
+            else:
+                raise LDAPConnectionError(
+                    &quot;Unknown credentials type: {0}&quot;
+                    .format(self.credentials)
+                )
+
+        return connection
+
+
+    def _newConnection(self):
+        &quot;&quot;&quot;
+        Create a new LDAP connection and initialize and start TLS if required.
+        This will always be called in a thread to prevent blocking.
+
+        @returns: The connection object.
+        @rtype: L{ldap.ldapobject.LDAPObject}
+
+        @raises: L{LDAPConnectionError} if unable to connect.
+        &quot;&quot;&quot;
+        connection = ldap.initialize(self.ds.url)
+
+        # FIXME: Use trace_file option to wire up debug logging when
+        # Twisted adopts the new logging stuff.
+
+        for option, value in (
+            (ldap.OPT_TIMEOUT, self.ds._timeout),
+            (ldap.OPT_X_TLS_CACERTFILE, self.ds._tlsCACertificateFile),
+            (ldap.OPT_X_TLS_CACERTDIR, self.ds._tlsCACertificateDirectory),
+            (ldap.OPT_DEBUG_LEVEL, self.ds._debug),
+        ):
+            if value is not None:
+                connection.set_option(option, value)
+
+        if self.ds._useTLS:
+            self.log.debug(&quot;Starting TLS for {log_source.url}&quot;)
+            connection.start_tls_s()
+
+        self.connectionsCreated += 1
+
+        return connection
+
+
</ins><span class="cx"> #
</span><span class="cx"> # Directory Service
</span><span class="cx"> #
</span><span class="lines">@@ -350,12 +508,14 @@
</span><span class="cx">             self.threadpool.adjustPoolsize(
</span><span class="cx">                 max(threadPoolMax, self.threadpool.max)
</span><span class="cx">             )
</span><del>-        self.connectionMax = connectionMax
-        self.connectionCreateLock = RLock()
-        self.connections = []
-        self.connectionQueue = Queue()
</del><ins>+
+        # Separate pools for LDAP queries and LDAP binds.  Note, they each get
+        # half of connectionMax.
+        self.connectionPools = {
+            &quot;query&quot;: ConnectionPool(&quot;query&quot;, self, credentials, connectionMax / 2),
+            &quot;auth&quot;: ConnectionPool(&quot;auth&quot;, self, None, connectionMax / 2),
+        }
</ins><span class="cx">         self.poolStats = collections.defaultdict(int)
</span><del>-        self.activeCount = 0
</del><span class="cx"> 
</span><span class="cx">         reactor.callWhenRunning(self.start)
</span><span class="cx">         reactor.addSystemEventTrigger(&quot;during&quot;, &quot;shutdown&quot;, self.stop)
</span><span class="lines">@@ -396,164 +556,23 @@
</span><span class="cx">         needed.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><del>-        def __init__(self, ds):
-            self.ds = ds
</del><ins>+        def __init__(self, ds, poolName):
+            self.pool = ds.connectionPools[poolName]
</ins><span class="cx"> 
</span><span class="cx">         def __enter__(self):
</span><del>-            self.connection = self.ds._getConnection()
</del><ins>+            self.connection = self.pool.getConnection()
</ins><span class="cx">             return self.connection
</span><span class="cx"> 
</span><span class="cx">         def __exit__(self, exc_type, exc_val, exc_tb):
</span><span class="cx">             if exc_type is None:
</span><del>-                self.ds._returnConnection(self.connection)
</del><ins>+                self.pool.returnConnection(self.connection)
</ins><span class="cx">                 return True
</span><span class="cx">             else:
</span><del>-                self.ds._failedConnection(self.connection)
</del><ins>+                self.pool.failedConnection(self.connection)
</ins><span class="cx">                 return False
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def _getConnection(self):
-        &quot;&quot;&quot;
-        Get a connection from the connection pool.
-        This will retrieve a connection from the connection pool L{Queue}
-        object.
-        If the L{Queue} is empty, it will check to see whether a new connection
-        can be created (based on the connection limit), and if so create that
-        and use it.
-        If no new connections can be created, it will block on the L{Queue}
-        until an existing, in-use, connection is put back.
-        &quot;&quot;&quot;
-        try:
-            connection = self.connectionQueue.get(block=False)
-        except Empty:
-            # Note we use a lock here to prevent a race condition in which
-            # multiple requests for a new connection could succeed even though
-            # the connection counts starts out one less than the maximum.
-            # This can happen because self._connect() can take a while.
-            self.connectionCreateLock.acquire()
-            if len(self.connections) &lt; self.connectionMax:
-                connection = self._connect()
-                self.connections.append(connection)
-                self.connectionCreateLock.release()
-            else:
-                self.connectionCreateLock.release()
-                self.poolStats[&quot;connection-blocked&quot;] += 1
-                connection = self.connectionQueue.get()
</del><span class="cx"> 
</span><del>-
-        connectionID = &quot;connection-{}&quot;.format(
-            self.connections.index(connection)
-        )
-
-        self.poolStats[connectionID] += 1
-        self.activeCount = len(self.connections) - self.connectionQueue.qsize()
-        self.poolStats[&quot;connection-active&quot;] = self.activeCount
-        self.poolStats[&quot;connection-max&quot;] = max(
-            self.poolStats[&quot;connection-max&quot;], self.activeCount
-        )
-
-        if self.activeCount &gt; self.connectionMax:
-            self.log.error(
-                &quot;Active LDAP connections ({active}) exceeds maximum ({max})&quot;,
-                active=self.activeCount, max=self.connectionMax
-            )
-        return connection
-
-
-    def _returnConnection(self, connection):
-        &quot;&quot;&quot;
-        A connection is no longer needed - return it to the pool.
-        &quot;&quot;&quot;
-        self.connectionQueue.put(connection)
-        self.activeCount = len(self.connections) - self.connectionQueue.qsize()
-
-
-    def _failedConnection(self, connection):
-        &quot;&quot;&quot;
-        A connection has failed; remove it from the list of active connections.
-        A new one will be created if needed.
-        &quot;&quot;&quot;
-        self.poolStats[&quot;connection-errors&quot;] += 1
-        self.connections.remove(connection)
-        self.activeCount = len(self.connections) - self.connectionQueue.qsize()
-
-
-    def _connect(self):
-        &quot;&quot;&quot;
-        Connect to the directory server.
-        This will always be called in a thread to prevent blocking.
-
-        @returns: The connection object.
-        @rtype: L{ldap.ldapobject.LDAPObject}
-
-        @raises: L{LDAPConnectionError} if unable to connect.
-        &quot;&quot;&quot;
-
-        self.log.debug(&quot;Connecting to LDAP at {log_source.url}&quot;)
-        connection = self._newConnection()
-
-        if self._credentials is not None:
-            if IUsernamePassword.providedBy(self._credentials):
-                try:
-                    connection.simple_bind_s(
-                        self._credentials.username,
-                        self._credentials.password,
-                    )
-                    self.log.debug(
-                        &quot;Bound to LDAP as {credentials.username}&quot;,
-                        credentials=self._credentials
-                    )
-                except (
-                    ldap.INVALID_CREDENTIALS, ldap.INVALID_DN_SYNTAX
-                ) as e:
-                    self.log.error(
-                        &quot;Unable to bind to LDAP as {credentials.username}&quot;,
-                        credentials=self._credentials
-                    )
-                    raise LDAPBindAuthError(
-                        self._credentials.username, e
-                    )
-
-            else:
-                raise LDAPConnectionError(
-                    &quot;Unknown credentials type: {0}&quot;
-                    .format(self._credentials)
-                )
-
-        return connection
-
-
-    def _newConnection(self):
-        &quot;&quot;&quot;
-        Create a new LDAP connection and initialize and start TLS if required.
-        This will always be called in a thread to prevent blocking.
-
-        @returns: The connection object.
-        @rtype: L{ldap.ldapobject.LDAPObject}
-
-        @raises: L{LDAPConnectionError} if unable to connect.
-        &quot;&quot;&quot;
-        connection = ldap.initialize(self.url)
-
-        # FIXME: Use trace_file option to wire up debug logging when
-        # Twisted adopts the new logging stuff.
-
-        for option, value in (
-            (ldap.OPT_TIMEOUT, self._timeout),
-            (ldap.OPT_X_TLS_CACERTFILE, self._tlsCACertificateFile),
-            (ldap.OPT_X_TLS_CACERTDIR, self._tlsCACertificateDirectory),
-            (ldap.OPT_DEBUG_LEVEL, self._debug),
-        ):
-            if value is not None:
-                connection.set_option(option, value)
-
-        if self._useTLS:
-            self.log.debug(&quot;Starting TLS for {log_source.url}&quot;)
-            connection.start_tls_s()
-
-        return connection
-
-
</del><span class="cx">     def _authenticateUsernamePassword(self, dn, password):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Open a secondary connection to the LDAP server and try binding to it
</span><span class="lines">@@ -587,30 +606,27 @@
</span><span class="cx">         @raises: L{LDAPConnectionError} if unable to connect.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         self.log.debug(&quot;Authenticating {dn}&quot;, dn=dn)
</span><del>-        connection = self._newConnection()
</del><ins>+        with DirectoryService.Connection(self, &quot;auth&quot;) as connection:
</ins><span class="cx"> 
</span><ins>+            try:
+                connection.simple_bind_s(dn, password)
+                self.log.debug(&quot;Authenticated {dn}&quot;, dn=dn)
+                return True
+            except (
+                ldap.INAPPROPRIATE_AUTH,
+                ldap.INVALID_CREDENTIALS,
+                ldap.INVALID_DN_SYNTAX,
+            ):
+                self.log.debug(&quot;Unable to authenticate {dn}&quot;, dn=dn)
+                return False
+            except ldap.CONSTRAINT_VIOLATION:
+                self.log.info(&quot;Account locked {dn}&quot;, dn=dn)
+                return False
+            except Exception as e:
+                self.log.error(&quot;Unexpected error {error} trying to authenticate {dn}&quot;, error=str(e), dn=dn)
+                return False
</ins><span class="cx"> 
</span><del>-        try:
-            connection.simple_bind_s(dn, password)
-            self.log.debug(&quot;Authenticated {dn}&quot;, dn=dn)
-            return True
-        except (
-            ldap.INAPPROPRIATE_AUTH,
-            ldap.INVALID_CREDENTIALS,
-            ldap.INVALID_DN_SYNTAX,
-        ):
-            self.log.debug(&quot;Unable to authenticate {dn}&quot;, dn=dn)
-            return False
-        except ldap.CONSTRAINT_VIOLATION:
-            self.log.info(&quot;Account locked {dn}&quot;, dn=dn)
-            return False
-        except Exception as e:
-            self.log.error(&quot;Unexpected error {error} trying to authenticate {dn}&quot;, error=str(e), dn=dn)
-            return False
-        finally:
-            connection.unbind()
</del><span class="cx"> 
</span><del>-
</del><span class="cx">     def _recordsFromQueryString(
</span><span class="cx">         self, queryString, recordTypes=None,
</span><span class="cx">         limitResults=None, timeoutSeconds=None
</span><span class="lines">@@ -654,7 +670,7 @@
</span><span class="cx"> 
</span><span class="cx">             try:
</span><span class="cx"> 
</span><del>-                with DirectoryService.Connection(self) as connection:
</del><ins>+                with DirectoryService.Connection(self, &quot;query&quot;) as connection:
</ins><span class="cx"> 
</span><span class="cx">                     for recordType in recordTypes:
</span><span class="cx"> 
</span><span class="lines">@@ -836,7 +852,7 @@
</span><span class="cx"> 
</span><span class="cx">             try:
</span><span class="cx"> 
</span><del>-                with DirectoryService.Connection(self) as connection:
</del><ins>+                with DirectoryService.Connection(self, &quot;query&quot;) as connection:
</ins><span class="cx"> 
</span><span class="cx">                     self.log.debug(&quot;Performing LDAP DN query: {dn}&quot;, dn=dn)
</span><span class="cx"> 
</span></span></pre></div>
<a id="twexttrunktwextwholdaptesttest_servicepy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/who/ldap/test/test_service.py (15779 => 15780)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/ldap/test/test_service.py        2016-07-27 21:50:59 UTC (rev 15779)
+++ twext/trunk/twext/who/ldap/test/test_service.py        2016-08-02 23:24:05 UTC (rev 15780)
</span><span class="lines">@@ -317,28 +317,27 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> class DirectoryServiceConnectionTestMixIn(object):
</span><del>-    @inlineCallbacks
</del><ins>+
</ins><span class="cx">     def test_connect_defaults(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Connect with default arguments.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         service = self.service()
</span><del>-        connection = yield service._connect()
</del><ins>+        with TestService.Connection(service, &quot;query&quot;) as connection:
</ins><span class="cx"> 
</span><del>-        self.assertEquals(connection.methods_called(), [&quot;initialize&quot;])
</del><ins>+            self.assertEquals(connection.methods_called(), [&quot;initialize&quot;])
</ins><span class="cx"> 
</span><del>-        for option in (
-            ldap.OPT_TIMEOUT,
-            ldap.OPT_X_TLS_CACERTFILE,
-            ldap.OPT_X_TLS_CACERTDIR,
-            ldap.OPT_DEBUG_LEVEL,
-        ):
-            self.assertRaises(KeyError, connection.get_option, option)
</del><ins>+            for option in (
+                ldap.OPT_TIMEOUT,
+                ldap.OPT_X_TLS_CACERTFILE,
+                ldap.OPT_X_TLS_CACERTDIR,
+                ldap.OPT_DEBUG_LEVEL,
+            ):
+                self.assertRaises(KeyError, connection.get_option, option)
</ins><span class="cx"> 
</span><del>-        self.assertFalse(connection.tls_enabled)
</del><ins>+            self.assertFalse(connection.tls_enabled)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><del>-    @inlineCallbacks
</del><span class="cx">     def test_connect_withUsernamePassword_invalid(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Connect with UsernamePassword credentials.
</span><span class="lines">@@ -349,14 +348,14 @@
</span><span class="cx">         )
</span><span class="cx">         service = self.service(credentials=credentials)
</span><span class="cx">         try:
</span><del>-            yield service._connect()
</del><ins>+            with TestService.Connection(service, &quot;query&quot;):
+                pass
</ins><span class="cx">         except LDAPBindAuthError:
</span><span class="cx">             pass
</span><span class="cx">         else:
</span><span class="cx">             self.fail(&quot;Should have raised LDAPBindAuthError&quot;)
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    @inlineCallbacks
</del><span class="cx">     def test_connect_withUsernamePassword_valid(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Connect with UsernamePassword credentials.
</span><span class="lines">@@ -366,15 +365,14 @@
</span><span class="cx">             u&quot;zehcnasw&quot;
</span><span class="cx">         )
</span><span class="cx">         service = self.service(credentials=credentials)
</span><del>-        connection = yield service._connect()
</del><span class="cx"> 
</span><del>-        self.assertEquals(
-            connection.methods_called(),
-            [&quot;initialize&quot;, &quot;simple_bind_s&quot;]
-        )
</del><ins>+        with TestService.Connection(service, &quot;query&quot;) as connection:
+            self.assertEquals(
+                connection.methods_called(),
+                [&quot;initialize&quot;, &quot;simple_bind_s&quot;]
+            )
</ins><span class="cx"> 
</span><span class="cx"> 
</span><del>-    @inlineCallbacks
</del><span class="cx">     def test_connect_withOptions(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Connect with default arguments.
</span><span class="lines">@@ -385,43 +383,42 @@
</span><span class="cx">             tlsCACertificateDirectory=FilePath(&quot;/path/to/certdir&quot;),
</span><span class="cx">             _debug=True,
</span><span class="cx">         )
</span><del>-        connection = yield service._connect()
</del><ins>+        with TestService.Connection(service, &quot;query&quot;) as connection:
</ins><span class="cx"> 
</span><del>-        self.assertEquals(
-            connection.methods_called(),
-            [
-                &quot;initialize&quot;,
-                &quot;set_option&quot;, &quot;set_option&quot;, &quot;set_option&quot;, &quot;set_option&quot;,
-            ]
-        )
</del><ins>+            self.assertEquals(
+                connection.methods_called(),
+                [
+                    &quot;initialize&quot;,
+                    &quot;set_option&quot;, &quot;set_option&quot;, &quot;set_option&quot;, &quot;set_option&quot;,
+                ]
+            )
</ins><span class="cx"> 
</span><del>-        opt = lambda k: connection.get_option(k)
</del><ins>+            opt = lambda k: connection.get_option(k)
</ins><span class="cx"> 
</span><del>-        self.assertEquals(opt(ldap.OPT_TIMEOUT), 18)
-        self.assertEquals(opt(ldap.OPT_X_TLS_CACERTFILE), &quot;/path/to/cert&quot;)
-        self.assertEquals(opt(ldap.OPT_X_TLS_CACERTDIR), &quot;/path/to/certdir&quot;)
-        self.assertEquals(opt(ldap.OPT_DEBUG_LEVEL), 255)
</del><ins>+            self.assertEquals(opt(ldap.OPT_TIMEOUT), 18)
+            self.assertEquals(opt(ldap.OPT_X_TLS_CACERTFILE), &quot;/path/to/cert&quot;)
+            self.assertEquals(opt(ldap.OPT_X_TLS_CACERTDIR), &quot;/path/to/certdir&quot;)
+            self.assertEquals(opt(ldap.OPT_DEBUG_LEVEL), 255)
</ins><span class="cx"> 
</span><del>-        # Tested in test_connect_defaults, but test again here since we're
-        # setting SSL options and we want to be sure they don't somehow enable
-        # SSL implicitly.
-        self.assertFalse(connection.tls_enabled)
</del><ins>+            # Tested in test_connect_defaults, but test again here since we're
+            # setting SSL options and we want to be sure they don't somehow enable
+            # SSL implicitly.
+            self.assertFalse(connection.tls_enabled)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><del>-    @inlineCallbacks
</del><span class="cx">     def test_connect_withTLS(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Connect with TLS enabled.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         service = self.service(useTLS=True)
</span><del>-        connection = yield service._connect()
</del><span class="cx"> 
</span><del>-        self.assertEquals(
-            connection.methods_called(),
-            [&quot;initialize&quot;, &quot;start_tls_s&quot;]
-        )
</del><ins>+        with TestService.Connection(service, &quot;query&quot;) as connection:
+            self.assertEquals(
+                connection.methods_called(),
+                [&quot;initialize&quot;, &quot;start_tls_s&quot;]
+            )
</ins><span class="cx"> 
</span><del>-        self.assertTrue(connection.tls_enabled)
</del><ins>+            self.assertTrue(connection.tls_enabled)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="lines">@@ -457,11 +454,11 @@
</span><span class="cx">         # still have a connection in the pool
</span><span class="cx">         service._recordsFromQueryString_inThread(&quot;(this=that)&quot;)
</span><span class="cx">         self.assertEquals(service._retryNumber, 0)
</span><del>-        self.assertEquals(len(service.connections), 1)
</del><ins>+        self.assertEquals(len(service.connectionPools[&quot;query&quot;].connections), 1)
</ins><span class="cx"> 
</span><span class="cx">         service._recordWithDN_inThread(&quot;cn=test&quot;)
</span><span class="cx">         self.assertEquals(service._retryNumber, 0)
</span><del>-        self.assertEquals(len(service.connections), 1)
</del><ins>+        self.assertEquals(len(service.connectionPools[&quot;query&quot;].connections), 1)
</ins><span class="cx"> 
</span><span class="cx">         # Force a search to raise SERVER_DOWN
</span><span class="cx">         def raiseServerDown(*args, **kwds):
</span><span class="lines">@@ -479,7 +476,7 @@
</span><span class="cx">             self.fail(&quot;Should have raised LDAPQueryError&quot;)
</span><span class="cx"> 
</span><span class="cx">         # Verify the connections are all closed
</span><del>-        self.assertEquals(len(service.connections), 0)
</del><ins>+        self.assertEquals(len(service.connectionPools[&quot;query&quot;].connections), 0)
</ins><span class="cx"> 
</span><span class="cx">         # Now try recordWithDN
</span><span class="cx">         try:
</span><span class="lines">@@ -491,10 +488,67 @@
</span><span class="cx">             self.fail(&quot;Should have raised LDAPQueryError&quot;)
</span><span class="cx"> 
</span><span class="cx">         # Verify the connections are all closed
</span><del>-        self.assertEquals(len(service.connections), 0)
</del><ins>+        self.assertEquals(len(service.connectionPools[&quot;query&quot;].connections), 0)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    @inlineCallbacks
+    def test_auth_pool(self):
+        &quot;&quot;&quot;
+        Verify acquiring connections from the LDAP connection pool will block
+        when connectionMax is reached,
+        and that
+        &quot;&quot;&quot;
</ins><span class="cx"> 
</span><ins>+        service = self.service(connectionMax=4)
+        pool = service.connectionPools[&quot;auth&quot;]
+
+        self.assertEquals(0, len(pool.connections))
+        self.assertEquals(0, pool.connectionsCreated)
+
+        # Ask for a connection and check the counts
+        with TestService.Connection(service, &quot;auth&quot;):
+            self.assertEquals(1, len(pool.connections))
+
+        self.assertEquals(1, len(pool.connections))
+        self.assertEquals(1, pool.connectionsCreated)
+
+        # Ask for two connections and check the counts
+        with TestService.Connection(service, &quot;auth&quot;):
+            self.assertEquals(1, len(pool.connections))
+            self.assertEquals(1, pool.connectionsCreated)
+            with TestService.Connection(service, &quot;auth&quot;):
+                self.assertEquals(2, len(pool.connections))
+                self.assertEquals(2, pool.connectionsCreated)
+
+        # Ask for three connections (one more than connectionMax/2) and
+        # the third will actually block until the returnConnection( ) call
+        with TestService.Connection(service, &quot;auth&quot;):
+            self.assertEquals(2, len(pool.connections))
+            self.assertEquals(2, pool.connectionsCreated)
+            with TestService.Connection(service, &quot;auth&quot;) as connection:
+                self.assertEquals(2, len(pool.connections))
+                self.assertEquals(2, pool.connectionsCreated)
+
+                # schedule a connection to be returned in 1 second
+                from twisted.internet import reactor
+                reactor.callLater(1, pool.returnConnection, connection)
+
+                # For the third connection, I'm using this method so it gets
+                # requested in a thread, otherwise we'd hang.
+                yield service._authenticateUsernamePassword(
+                    u&quot;uid=wsanchez,cn=user,{0}&quot;.format(self.baseDN),
+                    u&quot;zehcnasw&quot;
+                )
+
+        # Proof we bumped up against connection-max:
+        self.assertEquals(1, service.poolStats[&quot;connection-blocked&quot;])
+
+        self.assertEquals(2, len(pool.connections))
+        self.assertEquals(2, pool.connectionsCreated)
+        self.assertEquals(2, service.poolStats[&quot;connection-max&quot;])
+
+
+
</ins><span class="cx"> class ExtraFiltersTest(BaseTestCase, unittest.TestCase):
</span><span class="cx"> 
</span><span class="cx">     def test_extraFilters(self):
</span></span></pre>
</div>
</div>

</body>
</html>