Skip to content

Commit 3b58bf2

Browse files
author
stroeder
committed
some cosmetics in syncrepl demo script, use logging
1 parent 3592f97 commit 3b58bf2

File tree

1 file changed

+58
-52
lines changed

1 file changed

+58
-52
lines changed

Demo/pyasn1/syncrepl.py

Lines changed: 58 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,14 @@
77
Notes:
88
99
The bound user needs read access to the attributes entryDN and entryCSN.
10-
11-
This needs the following software:
12-
Python
13-
pyasn1 0.1.4+
14-
pyasn1-modules
15-
python-ldap 2.4.10+
1610
"""
1711

1812
# Import modules from Python standard lib
19-
import shelve,signal,time,sys,logging
13+
import logging
14+
import shelve
15+
import signal
16+
import sys
17+
import time
2018

2119
# Import the python-ldap modules
2220
import ldap
@@ -25,28 +23,34 @@
2523
from ldap.ldapobject import ReconnectLDAPObject
2624
from ldap.syncrepl import SyncreplConsumer
2725

26+
logger = logging.getLogger('syncrepl')
27+
logger.setLevel(logging.DEBUG)
28+
logger.addHandler(logging.StreamHandler())
2829

2930
# Global state
3031
watcher_running = True
3132
ldap_connection = False
3233

3334

34-
class SyncReplConsumer(ReconnectLDAPObject, SyncreplConsumer):
35+
class SyncReplClient(ReconnectLDAPObject, SyncreplConsumer):
3536
"""
36-
Syncrepl Consumer interface
37+
Syncrepl Consumer Client
3738
"""
3839

3940
def __init__(self, db_path, *args, **kwargs):
4041
# Initialise the LDAP Connection first
4142
ldap.ldapobject.ReconnectLDAPObject.__init__(self, *args, **kwargs)
4243
# Now prepare the data store
43-
self.__data = shelve.open(db_path, 'c')
44+
if db_path:
45+
self.__data = shelve.open(db_path, 'c')
46+
else:
47+
self.__data = dict()
4448
# We need this for later internal use
4549
self.__presentUUIDs = dict()
4650

4751
def close_db(self):
48-
# Close the data store properly to avoid corruption
49-
self.__data.close()
52+
# Close the data store properly to avoid corruption
53+
self.__data.close()
5054

5155
def syncrepl_get_cookie(self):
5256
if 'cookie' in self.__data:
@@ -55,7 +59,8 @@ def syncrepl_get_cookie(self):
5559
def syncrepl_set_cookie(self,cookie):
5660
self.__data['cookie'] = cookie
5761

58-
def syncrepl_entry(self,dn,attributes,uuid):
62+
def syncrepl_entry(self, dn, attributes, uuid):
63+
logger.debug('dn=%r attributes=%r uuid=%r', dn, attributes, uuid)
5964
# First we determine the type of change we have here
6065
# (and store away the previous data for later if needed)
6166
previous_attributes = dict()
@@ -69,18 +74,18 @@ def syncrepl_entry(self,dn,attributes,uuid):
6974
attributes['dn'] = dn
7075
self.__data[uuid] = attributes
7176
# Debugging
72-
print 'Detected', change_type, 'of entry:', dn
77+
logger.debug('Detected %s of entry %r', change_type, dn)
7378
# If we have a cookie then this is not our first time being run,
7479
# so it must be a change
7580
if 'ldap_cookie' in self.__data:
76-
self.perform_application_sync(dn, attributes, previous_attributes)
81+
self.perform_application_sync(dn, attributes, previous_attributes)
7782

7883
def syncrepl_delete(self,uuids):
7984
# Make sure we know about the UUID being deleted, just in case...
8085
uuids = [uuid for uuid in uuids if uuid in self.__data]
8186
# Delete all the UUID values we know of
8287
for uuid in uuids:
83-
print 'Detected deletion of entry:', self.__data[uuid]['dn']
88+
logger.debug('Detected deletion of entry %r', self.__data[uuid]['dn'])
8489
del self.__data[uuid]
8590

8691
def syncrepl_present(self,uuids,refreshDeletes=False):
@@ -105,78 +110,80 @@ def syncrepl_present(self,uuids,refreshDeletes=False):
105110
self.__presentUUIDs[uuid] = True
106111

107112
def syncrepl_refreshdone(self):
108-
print 'Initial synchronization is now done, persist phase begins'
113+
logger.info('Initial synchronization is now done, persist phase begins')
109114

110115
def perform_application_sync(self,dn,attributes,previous_attributes):
111-
print 'Performing application sync for:', dn
116+
logger.info('Performing application sync for %r', dn)
112117
return True
113118

114119

115120
# Shutdown handler
116121
def commenceShutdown(signum, stack):
117122
# Declare the needed global variables
118123
global watcher_running, ldap_connection
119-
print 'Shutting down!'
124+
logger.warn('Shutting down!')
120125

121126
# We are no longer running
122127
watcher_running = False
123128

124129
# Tear down the server connection
125-
if( ldap_connection ):
126-
ldap_connection.close_db()
127-
ldap_connection.unbind_s()
128-
del ldap_connection
130+
if ldap_connection:
131+
ldap_connection.close_db()
132+
ldap_connection.unbind_s()
133+
del ldap_connection
129134

130135
# Shutdown
131136
sys.exit(0)
132137

133138
# Time to actually begin execution
134139
# Install our signal handlers
135-
signal.signal(signal.SIGTERM,commenceShutdown)
136-
signal.signal(signal.SIGINT,commenceShutdown)
140+
signal.signal(signal.SIGTERM, commenceShutdown)
141+
signal.signal(signal.SIGINT, commenceShutdown)
137142

138143

139144
try:
140-
ldap_url = ldapurl.LDAPUrl(sys.argv[1])
141-
database_path = sys.argv[2]
145+
ldap_url = ldapurl.LDAPUrl(sys.argv[1])
146+
database_path = sys.argv[2]
142147
except IndexError,e:
143-
print 'Usage:'
144-
print sys.argv[0], '<LDAP URL> <pathname of database>'
145-
print sys.argv[0], '\'ldap://127.0.0.1/cn=users,dc=test'\
146-
'?*'\
147-
'?sub'\
148-
'?(objectClass=*)'\
149-
'?bindname=uid=admin%2ccn=users%2cdc=test,'\
150-
'X-BINDPW=password\' db.shelve'
148+
print (
149+
'Usage:\n'
150+
'{script_name} <LDAP URL> <pathname of database>\n'
151+
'{script_name} "ldap://127.0.0.1/cn=users,dc=test'
152+
'?*'
153+
'?sub'
154+
'?(objectClass=*)'
155+
'?bindname=uid=admin%2ccn=users%2cdc=test,'
156+
'X-BINDPW=password" db.shelve'
157+
).format(script_name=sys.argv[0])
151158
sys.exit(1)
152159
except ValueError,e:
153-
print 'Error parsing command-line arguments:',str(e)
154-
sys.exit(1)
160+
print 'Error parsing command-line arguments:', str(e)
161+
sys.exit(1)
155162

156163
while watcher_running:
157-
print 'Connecting to LDAP server now...'
164+
logger.info('Connecting to %s now...', ldap_url.initializeUrl())
158165
# Prepare the LDAP server connection (triggers the connection as well)
159-
ldap_connection = SyncReplConsumer(database_path, ldap_url.initializeUrl())
166+
ldap_connection = SyncReplClient(database_path, ldap_url.initializeUrl())
160167

161168
# Now we login to the LDAP server
162169
try:
163170
ldap_connection.simple_bind_s(ldap_url.who, ldap_url.cred)
164-
except ldap.INVALID_CREDENTIALS, e:
165-
print 'Login to LDAP server failed: ', str(e)
171+
except ldap.INVALID_CREDENTIALS, err:
172+
logger.error('Login to LDAP server failed: %s', err)
166173
sys.exit(1)
167174
except ldap.SERVER_DOWN:
168-
print 'LDAP server is down, going to retry.'
175+
logger.warn('LDAP server is down, going to retry.')
169176
time.sleep(5)
170177
continue
171178

172179
# Commence the syncing
173-
print 'Commencing sync process'
180+
logger.debug('Commencing sync process')
174181
ldap_search = ldap_connection.syncrepl_search(
175-
ldap_url.dn or '',
176-
ldap_url.scope or ldap.SCOPE_SUBTREE,
177-
mode = 'refreshAndPersist',
178-
attrlist=ldap_url.attrs,
179-
filterstr = ldap_url.filterstr or '(objectClass=*)'
182+
ldap_url.dn or '',
183+
ldap_url.scope or ldap.SCOPE_SUBTREE,
184+
mode = 'refreshAndPersist',
185+
attrlist=ldap_url.attrs,
186+
filterstr = ldap_url.filterstr or '(objectClass=*)'
180187
)
181188

182189
try:
@@ -185,10 +192,9 @@ def commenceShutdown(signum, stack):
185192
except KeyboardInterrupt:
186193
# User asked to exit
187194
commenceShutdown(None, None)
188-
pass
189-
except Exception, e:
195+
except Exception, err:
190196
# Handle any exception
191197
if watcher_running:
192-
print 'Encountered a problem, going to retry. Error:', str(e)
198+
logger.exception('Unhandled exception, going to retry: %s', err)
199+
logger.info('Going to retry after 5 secs')
193200
time.sleep(5)
194-
pass

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy