<!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>[15477] twext/trunk/twext/who/ldap/_service.py</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/15477">15477</a></dd>
<dt>Author</dt> <dd>wsanchez@apple.com</dd>
<dt>Date</dt> <dd>2016-03-17 15:16:13 -0700 (Thu, 17 Mar 2016)</dd>
</dl>
<h3>Log Message</h3>
<pre>lint</pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#twexttrunktwextwholdap_servicepy">twext/trunk/twext/who/ldap/_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 (15476 => 15477)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/ldap/_service.py        2016-03-16 22:56:28 UTC (rev 15476)
+++ twext/trunk/twext/who/ldap/_service.py        2016-03-17 22:16:13 UTC (rev 15477)
</span><span class="lines">@@ -15,12 +15,12 @@
</span><span class="cx"> # limitations under the License.
</span><span class="cx"> ##
</span><span class="cx">
</span><del>-from __future__ import print_function
-
</del><span class="cx"> """
</span><span class="cx"> LDAP directory service implementation.
</span><span class="cx"> """
</span><span class="cx">
</span><ins>+from __future__ import print_function
+
</ins><span class="cx"> from Queue import Queue, Empty
</span><span class="cx"> from threading import RLock
</span><span class="cx"> from uuid import UUID
</span><span class="lines">@@ -115,6 +115,9 @@
</span><span class="cx"> #
</span><span class="cx">
</span><span class="cx"> class FieldName(Names):
</span><ins>+ """
+ LDAP field names.
+ """
</ins><span class="cx"> dn = NamedConstant()
</span><span class="cx"> dn.description = u"distinguished name"
</span><span class="cx">
</span><span class="lines">@@ -271,9 +274,7 @@
</span><span class="cx"> @param extraFilters: A dict (keyed off recordType) of extra filter
</span><span class="cx"> fragments to AND in to any generated queries.
</span><span class="cx"> @type extraFilters: L{dicts} of L{unicode}
</span><del>-
</del><span class="cx"> """
</span><del>-
</del><span class="cx"> self.url = url
</span><span class="cx"> self._baseDN = baseDN
</span><span class="cx"> self._credentials = credentials
</span><span class="lines">@@ -325,14 +326,21 @@
</span><span class="cx"> attributesToFetch.add(attribute.encode("utf-8"))
</span><span class="cx"> self._attributesToFetch = list(attributesToFetch)
</span><span class="cx">
</span><del>- # Threaded connection pool. The connection size limit here is the size for connections doing queries.
- # There will also be one-off connections for authentications which also run in their own threads. Thus
- # the threadpool max ought to be larger than the connection max to allow for both pooled query connections
- # and one-off auth-only connections.
</del><ins>+ # Threaded connection pool.
+ # The connection size limit here is the size for connections doing
+ # queries.
+ # There will also be one-off connections for authentications which also
+ # run in their own threads.
+ # Thus the threadpool max ought to be larger than the connection max to
+ # allow for both pooled query connections and one-off auth-only
+ # connections.
</ins><span class="cx">
</span><span class="cx"> self.ownThreadpool = ownThreadpool
</span><span class="cx"> if self.ownThreadpool:
</span><del>- self.threadpool = ThreadPool(minthreads=1, maxthreads=threadPoolMax, name="LDAPDirectoryService")
</del><ins>+ self.threadpool = ThreadPool(
+ minthreads=1, maxthreads=threadPoolMax,
+ name="LDAPDirectoryService",
+ )
</ins><span class="cx"> else:
</span><span class="cx"> # Use the default threadpool but adjust its size to fit our needs
</span><span class="cx"> self.threadpool = reactor.getThreadPool()
</span><span class="lines">@@ -347,7 +355,7 @@
</span><span class="cx"> self.activeCount = 0
</span><span class="cx">
</span><span class="cx"> reactor.callWhenRunning(self.start)
</span><del>- reactor.addSystemEventTrigger('during', 'shutdown', self.stop)
</del><ins>+ reactor.addSystemEventTrigger("during", "shutdown", self.stop)
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def start(self):
</span><span class="lines">@@ -360,12 +368,14 @@
</span><span class="cx">
</span><span class="cx"> def stop(self):
</span><span class="cx"> """
</span><del>- Stop the service. Stop the threadpool if we own it and do other clean-up.
</del><ins>+ Stop the service.
+ Stop the threadpool if we own it and do other clean-up.
</ins><span class="cx"> """
</span><span class="cx"> if self.ownThreadpool:
</span><span class="cx"> self.threadpool.stop()
</span><span class="cx">
</span><del>- # FIXME: we should probably also close the pool of active connections too
</del><ins>+ # FIXME: we should probably also close the pool of active connections
+ # too.
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> @property
</span><span class="lines">@@ -375,10 +385,12 @@
</span><span class="cx">
</span><span class="cx"> class Connection(object):
</span><span class="cx"> """
</span><del>- ContextManager object for getting a connection from the pool. On exit the connection
- will be put back in the pool if no exception was raised. Otherwise, the connection will be
- removed from the active connection list, which will allow a new "clean" connection to
- be created later if needed.
</del><ins>+ ContextManager object for getting a connection from the pool.
+ On exit the connection will be put back in the pool if no exception was
+ raised.
+ Otherwise, the connection will be removed from the active connection
+ list, which will allow a new "clean" connection to be created later if
+ needed.
</ins><span class="cx"> """
</span><span class="cx">
</span><span class="cx"> def __init__(self, ds):
</span><span class="lines">@@ -399,18 +411,22 @@
</span><span class="cx">
</span><span class="cx"> def _getConnection(self):
</span><span class="cx"> """
</span><del>- 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.
</del><ins>+ 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.
</ins><span class="cx"> """
</span><span class="cx"> try:
</span><span class="cx"> connection = self.connectionQueue.get(block=False)
</span><span class="cx"> except Empty:
</span><del>- # 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.
</del><ins>+ # 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.
</ins><span class="cx"> self.connectionCreateLock.acquire()
</span><span class="cx"> if len(self.connections) < self.connectionMax:
</span><span class="cx"> connection = self._connect()
</span><span class="lines">@@ -421,9 +437,16 @@
</span><span class="cx"> self.poolStats["connection-blocked"] += 1
</span><span class="cx"> connection = self.connectionQueue.get()
</span><span class="cx">
</span><del>- self.poolStats["connection-{}".format(self.connections.index(connection))] += 1
</del><ins>+
+ connectionID = "connection-{}".format(
+ self.connections.index(connection)
+ )
+
+ self.poolStats[connectionID] += 1
</ins><span class="cx"> self.activeCount += 1
</span><del>- self.poolStats["connection-max"] = max(self.poolStats["connection-max"], self.activeCount)
</del><ins>+ self.poolStats["connection-max"] = max(
+ self.poolStats["connection-max"], self.activeCount
+ )
</ins><span class="cx"> return connection
</span><span class="cx">
</span><span class="cx">
</span><span class="lines">@@ -437,8 +460,8 @@
</span><span class="cx">
</span><span class="cx"> def _failedConnection(self, connection):
</span><span class="cx"> """
</span><del>- A connection has failed - remove it from the list of active connections. A new
- one will be created if needed.
</del><ins>+ A connection has failed; remove it from the list of active connections.
+ A new one will be created if needed.
</ins><span class="cx"> """
</span><span class="cx"> self.activeCount -= 1
</span><span class="cx"> self.poolStats["connection-errors"] += 1
</span><span class="lines">@@ -455,7 +478,6 @@
</span><span class="cx">
</span><span class="cx"> @raises: L{LDAPConnectionError} if unable to connect.
</span><span class="cx"> """
</span><del>-
</del><span class="cx"> # FIXME: ldap connection objects are not thread safe, so let's set up
</span><span class="cx"> # a connection pool
</span><span class="cx">
</span><span class="lines">@@ -568,12 +590,14 @@
</span><span class="cx"> return False
</span><span class="cx"> finally:
</span><span class="cx"> # TODO: should we explicitly "close" the connection in a finally
</span><del>- # clause rather than just let it go out of scope and be garbage collected
- # at some indeterminate point in the future? Up side is that we won't hang
- # on to the connection or other resources for longer than needed. Down side
- # is we will take a little bit of extra time in this call to close it down.
- # If we do decide to "close" then we probably have to use one of the "unbind"
- # methods on the L{LDAPObject}.
</del><ins>+ # clause rather than just let it go out of scope and be garbage
+ # collected at some indeterminate point in the future?
+ # Up side is that we won't hang on to the connection or other
+ # resources for longer than needed.
+ # Down side is we will take a little bit of extra time in this call
+ # to close it down.
+ # If we do decide to "close" then we probably have to use one of
+ # the "unbind" methods on the L{LDAPObject}.
</ins><span class="cx"> connection = None
</span><span class="cx">
</span><span class="cx">
</span><span class="lines">@@ -603,9 +627,8 @@
</span><span class="cx"> self, queryString, recordTypes=None,
</span><span class="cx"> limitResults=None, timeoutSeconds=None
</span><span class="cx"> ):
</span><del>- """
- This method is always called in a thread.
- """
</del><ins>+ # This method is always called in a thread.
+
</ins><span class="cx"> if recordTypes is None:
</span><span class="cx"> recordTypes = list(self.recordTypes())
</span><span class="cx">
</span><span class="lines">@@ -634,14 +657,23 @@
</span><span class="cx"> ldap.dn.str2dn(rdn.lower()) +
</span><span class="cx"> ldap.dn.str2dn(self._baseDN.lower())
</span><span class="cx"> )
</span><del>- filteredQuery = self._addExtraFilter(recordType, queryString)
</del><ins>+ filteredQuery = self._addExtraFilter(
+ recordType, queryString
+ )
</ins><span class="cx"> self.log.debug(
</span><del>- "Performing LDAP query: {rdn} {query} {recordType}{limit}{timeout}",
</del><ins>+ "Performing LDAP query: "
+ "{rdn} {query} {recordType}{limit}{timeout}",
</ins><span class="cx"> rdn=rdn,
</span><span class="cx"> query=filteredQuery,
</span><span class="cx"> recordType=recordType,
</span><del>- limit=" limit={}".format(limitResults) if limitResults else "",
- timeout=" timeout={}".format(timeoutSeconds) if timeoutSeconds else "",
</del><ins>+ limit=(
+ " limit={}".format(limitResults)
+ if limitResults else ""
+ ),
+ timeout=(
+ " timeout={}".format(timeoutSeconds)
+ if timeoutSeconds else ""
+ ),
</ins><span class="cx"> )
</span><span class="cx"> try:
</span><span class="cx"> s = ldap.async.List(connection)
</span><span class="lines">@@ -650,8 +682,14 @@
</span><span class="cx"> ldap.SCOPE_SUBTREE,
</span><span class="cx"> filteredQuery,
</span><span class="cx"> attrList=self._attributesToFetch,
</span><del>- timeout=timeoutSeconds if timeoutSeconds else -1,
- sizelimit=limitResults if limitResults else 0
</del><ins>+ timeout=(
+ timeoutSeconds
+ if timeoutSeconds else -1
+ ),
+ sizelimit=(
+ limitResults
+ if limitResults else 0
+ ),
</ins><span class="cx"> )
</span><span class="cx"> s.processResults()
</span><span class="cx">
</span><span class="lines">@@ -669,7 +707,9 @@
</span><span class="cx"> raise LDAPQueryError("Unable to perform query", e)
</span><span class="cx">
</span><span class="cx"> except ldap.NO_SUCH_OBJECT as e:
</span><del>- # self.log.warn("RDN {rdn} does not exist, skipping", rdn=rdn)
</del><ins>+ # self.log.warn(
+ # "RDN {rdn} does not exist, skipping", rdn=rdn
+ # )
</ins><span class="cx"> continue
</span><span class="cx">
</span><span class="cx"> except ldap.INVALID_SYNTAX as e:
</span><span class="lines">@@ -690,12 +730,19 @@
</span><span class="cx"> )
</span><span class="cx"> raise LDAPQueryError("Unable to perform query", e)
</span><span class="cx">
</span><del>- reply = [resultItem for _ignore_resultType, resultItem in s.allResults]
</del><ins>+ reply = [
+ resultItem
+ for _ignore_resultType, resultItem
+ in s.allResults
+ ]
</ins><span class="cx">
</span><del>- newRecords = self._recordsFromReply(reply, recordType=recordType)
</del><ins>+ newRecords = self._recordsFromReply(
+ reply, recordType=recordType
+ )
</ins><span class="cx">
</span><span class="cx"> self.log.debug(
</span><del>- "Records from LDAP query ({rdn} {query} {recordType}): {count}",
</del><ins>+ "Records from LDAP query "
+ "({rdn} {query} {recordType}): {count}",
</ins><span class="cx"> rdn=rdn,
</span><span class="cx"> query=queryString,
</span><span class="cx"> recordType=recordType,
</span><span class="lines">@@ -708,18 +755,16 @@
</span><span class="cx"> records.extend(newRecords)
</span><span class="cx">
</span><span class="cx"> except ldap.SERVER_DOWN as e:
</span><del>- self.log.error(
- "LDAP server unavailable"
- )
</del><ins>+ self.log.error("LDAP server unavailable")
</ins><span class="cx"> if self._retryNumber + 1 == self._tries:
</span><del>- # We've hit SERVER_DOWN self._tries times, giving up
</del><ins>+ # We've hit SERVER_DOWN self._tries times, giving up.
</ins><span class="cx"> raise LDAPQueryError("LDAP server down", e)
</span><span class="cx"> else:
</span><span class="cx"> self.log.error("LDAP connection failure; retrying...")
</span><span class="cx">
</span><span class="cx"> else:
</span><span class="cx"> # Only retry if we got ldap.SERVER_DOWN, otherwise break out of
</span><del>- # loop
</del><ins>+ # loop.
</ins><span class="cx"> break
</span><span class="cx">
</span><span class="cx"> self.log.debug(
</span><span class="lines">@@ -740,11 +785,10 @@
</span><span class="cx">
</span><span class="cx"> def _recordWithDN_inThread(self, dn):
</span><span class="cx"> """
</span><del>- This method is always called in a thread.
-
</del><span class="cx"> @param dn: The DN of the record to search for
</span><span class="cx"> @type dn: C{str}
</span><span class="cx"> """
</span><ins>+ # This method is always called in a thread.
</ins><span class="cx">
</span><span class="cx"> records = []
</span><span class="cx">
</span><span class="lines">@@ -819,7 +863,9 @@
</span><span class="cx"> # Populate a fields dictionary
</span><span class="cx"> fields = {}
</span><span class="cx">
</span><del>- for fieldName, attributeRules in self._fieldNameToAttributesMap.iteritems():
</del><ins>+ for fieldName, attributeRules in (
+ self._fieldNameToAttributesMap.iteritems()
+ ):
</ins><span class="cx"> valueType = self.fieldName.valueType(fieldName)
</span><span class="cx">
</span><span class="cx"> for attributeRule in attributeRules:
</span><span class="lines">@@ -845,8 +891,10 @@
</span><span class="cx"> newValues = [valueType(v) for v in values]
</span><span class="cx"> except Exception, e:
</span><span class="cx"> self.log.warn(
</span><del>- "Can't parse value {name} {values} ({error})",
- name=fieldName, values=values, error=str(e)
</del><ins>+ "Can't parse value {name} {values} "
+ "({error})",
+ name=fieldName, values=values,
+ error=str(e)
</ins><span class="cx"> )
</span><span class="cx"> continue
</span><span class="cx">
</span><span class="lines">@@ -879,13 +927,17 @@
</span><span class="cx"> if not isinstance(values, list):
</span><span class="cx"> values = [values]
</span><span class="cx">
</span><del>- _ignore_attribute, attributeValue, fieldValue = attributeRule.split(":")
</del><ins>+ _ignore_attribute, attributeValue, fieldValue = (
+ attributeRule.split(":")
+ )
</ins><span class="cx">
</span><span class="cx"> for value in values:
</span><span class="cx"> if value == attributeValue:
</span><span class="cx"> # convert to a constant
</span><span class="cx"> try:
</span><del>- fieldValue = valueType.lookupByName(fieldValue)
</del><ins>+ fieldValue = (
+ valueType.lookupByName(fieldValue)
+ )
</ins><span class="cx"> fields[fieldName] = fieldValue
</span><span class="cx"> except ValueError:
</span><span class="cx"> pass
</span><span class="lines">@@ -1034,7 +1086,8 @@
</span><span class="cx"> dn = ldap.dn.str2dn(dnStr.lower())
</span><span class="cx"> attrName, value, ignored = dn[0][0]
</span><span class="cx"> fieldName = self.service._attributeToFieldNameMap[attrName][0]
</span><del>- fieldValuesByRecordType.setdefault(recordType, []).append((fieldName, value))
</del><ins>+ fieldValues = fieldValuesByRecordType.setdefault(recordType, [])
+ fieldValues.append((fieldName, value))
</ins><span class="cx"> continue
</span><span class="cx">
</span><span class="cx"> except:
</span><span class="lines">@@ -1098,6 +1151,9 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx"> def reverseDict(source):
</span><ins>+ """
+ Reverse keys and values in a mapping.
+ """
</ins><span class="cx"> new = {}
</span><span class="cx">
</span><span class="cx"> for key, values in source.iteritems():
</span><span class="lines">@@ -1155,7 +1211,6 @@
</span><span class="cx"> @param recordData: LDAP record data.
</span><span class="cx"> @type recordData: mapping
</span><span class="cx"> """
</span><del>-
</del><span class="cx"> for recordType, schema in recordTypeSchemas.iteritems():
</span><span class="cx"> for attribute, value in schema.attributes:
</span><span class="cx"> dataValue = recordData.get(attribute)
</span></span></pre>
</div>
</div>
</body>
</html>