Python ldap3.ServerPool() Examples

The following are 10 code examples of ldap3.ServerPool(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap3 , or try the search function .
Example #1
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        ldap3.ServerPool.__init__(self, *args, **kwargs)
        self._lock = threading.RLock() 
Example #2
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def initialize(self, connection):
        with self._lock:
            return ldap3.ServerPool.initialize(self, connection) 
Example #3
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_server(self, connection):
        with self._lock:
            return ldap3.ServerPool.get_server(self, connection) 
Example #4
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_current_server(self, connection):
        with self._lock:
            return ldap3.ServerPool.get_current_server(self, connection) 
Example #5
Source File: test_lib_resolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_35_persistent_serverpool(self):
        ldap3mock.setLDAPDirectory(LDAPDirectory)
        params = {'LDAPURI': 'ldap://localhost, ldap://127.0.0.1, ldap://127.0.1.1',
                      'LDAPBASE': 'o=test',
                      'BINDDN': 'cn=manager,ou=example,o=test',
                      'BINDPW': 'ldaptest',
                      'LOGINNAMEATTRIBUTE': 'cn',
                      'LDAPSEARCHFILTER': '(cn=*)',
                      'USERINFO': '{ "username": "cn", "phone": "telephoneNumber", '
                                  '"mobile" : "mobile", "email": "mail", '
                                  '"surname" : "sn", "givenname": "givenName" }',
                      'UIDTYPE': 'DN',
                      'CACHE_TIMEOUT': '0', # to disable the per-process cache
                      'resolver': 'testpool',
                      'type': 'ldapresolver'}
        y1 = LDAPResolver()
        y1.loadConfig(params)
        y2 = LDAPResolver()
        y2.loadConfig(params)
        # Make a query, so that a ServerPool is instantiated
        y1.getUserId('bob')
        y2.getUserId('bob')
        # We haven't configured a persistent serverpool, so every resolver has its own ServerPool
        self.assertIs(type(y1.serverpool), ldap3.ServerPool)
        self.assertIs(type(y2.serverpool), ldap3.ServerPool)
        self.assertIsNot(y1.serverpool, y2.serverpool)
        # Now, we configure a persistent serverpool
        params["SERVERPOOL_PERSISTENT"] = "true"
        y3 = LDAPResolver()
        y3.loadConfig(params)
        y4 = LDAPResolver()
        y4.loadConfig(params)
        y3.getUserId('bob')
        y4.getUserId('bob')
        # The resolvers share a ServerPool
        self.assertIs(type(y3.serverpool), LockingServerPool)
        self.assertIs(type(y4.serverpool), LockingServerPool)
        self.assertIs(y3.serverpool, y4.serverpool) 
Example #6
Source File: test_lib_resolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_36_locking_serverpool(self):
        # check that the LockingServerPool correctly forwards all relevant method calls
        pool = LockingServerPool()
        pool.add(ldap3.Server('server1'))
        pool.add(ldap3.Server('server2'))
        with mock.patch('ldap3.ServerPool.initialize') as mock_method:
            pool.initialize(None)
            mock_method.assert_called_once()
        with mock.patch('ldap3.ServerPool.get_server') as mock_method:
            pool.get_server(None)
            mock_method.assert_called_once()
        with mock.patch('ldap3.ServerPool.get_current_server') as mock_method:
            pool.get_current_server(None)
            mock_method.assert_called_once() 
Example #7
Source File: __init__.py    From flask-ldap3-login with MIT License 5 votes vote down vote up
def init_app(self, app):
        """
        Configures this extension with the given app. This registers an
        ``teardown_appcontext`` call, and attaches this ``LDAP3LoginManager``
        to it as ``app.ldap3_login_manager``.

        Args:
            app (flask.Flask): The flask app to initialise with
        """

        app.ldap3_login_manager = self
        for k, v in _CONFIG_DEFAULTS:
            app.config.setdefault(k, v)

        app.ldap3_login_manager_server_pool = ldap3.ServerPool(
            [],
            ldap3.FIRST,
            active=1,  # Loop through all servers once.
            exhaust=10,  # Remove unreachable servers for 10 seconds.
        )

        if app.config["LDAP_ADD_SERVER"]:
            self.add_server(
                hostname=app.config["LDAP_HOST"],
                port=app.config["LDAP_PORT"],
                use_ssl=app.config["LDAP_USE_SSL"],
                app=app,
            )

        if hasattr(app, "teardown_appcontext"):
            app.teardown_appcontext(self.teardown)
        else:  # pragma: no cover
            app.teardown_request(self.teardown) 
Example #8
Source File: ad_users.py    From django_auth_ldap3_ad with GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
        # check configuration
        if not (hasattr(settings, 'LDAP_SERVERS') and hasattr(settings, 'LDAP_BIND_ADMIN') and
                hasattr(settings, 'LDAP_BIND_ADMIN_PASS') and hasattr(settings, 'LDAP_AD_DOMAIN')
                and hasattr(settings, 'LDAP_CERT_FILE')
                ):
            raise ImproperlyConfigured()

        # first: build server pool from settings
        tls = Tls(validate=ssl.CERT_OPTIONAL, version=ssl.PROTOCOL_TLSv1, ca_certs_file=settings.LDAP_CERT_FILE)

        if self.pool is None:
            self.pool = ServerPool(None, pool_strategy=FIRST, active=True)
            for srv in settings.LDAP_SERVERS:
                # Only add servers that supports SSL, impossible to make changes without
                if srv['use_ssl']:
                    server = Server(srv['host'], srv['port'], srv['use_ssl'], tls=tls)
                    self.pool.add(server)

        # then, try to connect with user/pass from settings
        self.con = Connection(self.pool, auto_bind=True, authentication=SIMPLE,
                              user=settings.LDAP_BIND_ADMIN, password=settings.LDAP_BIND_ADMIN_PASS) 
Example #9
Source File: ldap.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, ldap_server_host, ldap_admin_dn, ldap_admin_password, ldap_server_port=389, ldap_use_ssl=False):
        self._ldap_admin_dn = ldap_admin_dn
        self._ldap_admin_password = ldap_admin_password
        # ldap_server_pool = ServerPool(["172.16.0.102",'172.16.0.103'])
        self.ldap_server = Server(ldap_server_host, port=ldap_server_port, use_ssl=ldap_use_ssl) 
Example #10
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def create_serverpool(cls, urilist, timeout, get_info=None, tls_context=None, rounds=SERVERPOOL_ROUNDS,
                          exhaust=SERVERPOOL_SKIP, pool_cls=ldap3.ServerPool):
        """
        This create the serverpool for the ldap3 connection.
        The URI from the LDAP resolver can contain a comma separated list of
        LDAP servers. These are split and then added to the pool.

        See
        https://github.com/cannatag/ldap3/blob/master/docs/manual/source/servers.rst#server-pool

        :param urilist: The list of LDAP URIs, comma separated
        :type urilist: basestring
        :param timeout: The connection timeout
        :type timeout: float
        :param get_info: The get_info type passed to the ldap3.Sever
            constructor. default: ldap3.SCHEMA, should be ldap3.NONE in case
            of a bind.
        :param tls_context: A ldap3.tls object, which defines if certificate
            verification should be performed
        :param rounds: The number of rounds we should cycle through the server pool
            before giving up
        :param exhaust: The seconds, for how long a non-reachable server should be
            removed from the serverpool
        :param pool_cls: ``ldap3.ServerPool`` subclass that should be instantiated
        :return: Server Pool
        :rtype: serverpool_cls
        """
        get_info = get_info or ldap3.SCHEMA
        server_pool = pool_cls(None, ldap3.ROUND_ROBIN,
                               active=rounds,
                               exhaust=exhaust)
        for uri in urilist.split(","):
            uri = uri.strip()
            host, port, ssl = cls.split_uri(uri)
            server = ldap3.Server(host, port=port,
                                  use_ssl=ssl,
                                  connect_timeout=float(timeout),
                                  get_info=get_info,
                                  tls=tls_context)
            server_pool.add(server)
            log.debug("Added {0!s}, {1!s}, {2!s} to server pool.".format(host, port, ssl))
        return server_pool