threaded.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """
  2. The purpose of this script is to test thread-safety
  3. It's called with an arbitrary number of LDAP URLs which
  4. specifies LDAP searches each executed continously in
  5. a separate thread with a separate LDAPObject instance.
  6. """
  7. import sys,time,threading,ldap,ldapurl
  8. ldap.LIBLDAP_R = 1
  9. class TestThread(threading.Thread):
  10. def __init__(self,ldap_url):
  11. self.ldap_url = ldapurl.LDAPUrl(ldap_url)
  12. # Open the connection
  13. self.l = ldap.ldapobject.SimpleLDAPObject(
  14. self.ldap_url.initializeUrl(),trace_level=0
  15. )
  16. self.stop_event = threading.Event()
  17. threading.Thread.__init__(self)
  18. self.setName(self.__class__.__name__+self.getName()[6:])
  19. print 'Initialized',self.getName(),self.ldap_url.unparse()
  20. def run(self):
  21. """Thread function for cleaning up session database"""
  22. try:
  23. while not self.stop_event.isSet():
  24. start_time=time.time()
  25. ldap_result = self.l.search_s(
  26. self.ldap_url.dn.encode('utf-8'),
  27. self.ldap_url.scope,
  28. self.ldap_url.filterstr.encode('utf-8'),
  29. self.ldap_url.attrs
  30. )
  31. end_time=time.time()
  32. # Let us see something working
  33. print self.getName(),': %d search results in %0.1f s' % (len(ldap_result),end_time-start_time)
  34. finally:
  35. self.l.unbind_s()
  36. del self.l
  37. thread_list = []
  38. ldap_url_list = sys.argv[1:]
  39. if ldap_url_list:
  40. for ldap_url in sys.argv[1:]:
  41. thread_list.append(TestThread(ldap_url))
  42. print 'Starting %d threads.' % (len(thread_list))
  43. for t in thread_list:
  44. t.start()
  45. print 'Started thread',t.getName()
  46. print 'Started %d threads.' % (len(thread_list))
  47. try:
  48. while 1:
  49. pass
  50. except KeyboardInterrupt:
  51. # Terminate all threads
  52. for t in thread_list:
  53. print 'Terminating thread',t.getName(),'...'
  54. t.stop_event.set()
  55. else:
  56. print 'Error: You have to provide a list of LDAP URLs at command-line'