3 # Tony Mack <tmack@cs.princeton.edu>
4 # Copyright (C) 2006 The Trustees of Princeton University
7 # $URL: svn+ssh://svn.planet-lab.org/svn/PLCAPI/trunk/PLC/LDAP.py $
13 from PLC.Debug import profile, log
14 from PLC.Faults import *
18 def __init__(self, api):
22 self.connection = None
25 def bind(self, async=False):
27 if self.connection is None:
29 if self.api.config.PLC_LDAP_SECURE:
30 url = 'ldaps://%s' % \
31 (self.api.config.PLC_LDAP_HOST, self.api.config.PLC_LDAP_PORT)
34 (self.api.config.PLC_LDAP_HOST, self.api.config.PLC_LDAP_PORT)
35 self.connection = ldap.open(url)
36 dn = self.api.config.PLC_LDAP_ROOT_DN
37 pw = self.api.config.PLC_LDAP_ROOT_PASSWORD
39 self.connection.bind(dn, pw, ldap.AUTH_SIMPLE)
41 self.connection.bind_s(dn, pw, ldap.AUTH_SIMPLE)
42 except ldap.LDAPError, e:
43 raise PLCLDAPError, "Unable to bind to server: %s" % e
50 if self.connection is not None:
51 self.connection.unbind()
52 self.connection = None
54 def pl_to_ldap(self, filter):
56 Convert pl fields to ldap fields
58 ldap_filter = {'objectClass': '*'}
59 if 'first_name' in filter and 'last_name' in filter:
60 ldap_filter['cn'] = "%s %s" % \
61 (filter['first_name'], filter['last_name'])
64 ldap_filter['mail'] = filter['email']
65 if key == 'objectClass':
66 ldap_filter['objectClass'] = filter['objectClass']
70 def to_ldap_filter(search_filter):
71 search_filter = pl_to_ldap(search_filter)
73 for (key,value) in search_filter.items():
74 values.append("(%s=%s)" % (key,value))
76 return "(&%s)" % "".join(values)
78 def to_list_of_dicts(results_list):
80 Convert ldap search results to a list of dicts
83 for (dn, result_dict) in result_list:
84 result_dict['dn'] = dn
85 results.append(result_dict)
88 def search(self, search_filter):
90 Search the ldap directory
93 dn = self.api.config.PLC_LDAP_SUFFIX
94 scope = ldap.SCOPE_SUBTREE
95 filter = to_ldap_filter(search_filter)
96 # always do synchronous searchers
97 search = self.connection.search_s
98 results = to_list_of_dicts(search(dn, scope, filter))
102 def add(self, record, type):
104 Add to the ldap directory
109 def update(self, record):
111 Update a record in the ldap directory
116 def remove(self, record):
118 Remove a record from the ldap directory