cpython/Lib/bsddb/test/test_thread.py
Christian Heimes af98da18c0 Merged revisions 60284-60349 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r60286 | christian.heimes | 2008-01-25 15:54:23 +0100 (Fri, 25 Jan 2008) | 1 line

  setup.py doesn't pick up changes to a header file
........
  r60287 | christian.heimes | 2008-01-25 16:52:11 +0100 (Fri, 25 Jan 2008) | 2 lines

  Added the Python core headers Include/*.h and pyconfig.h as dependencies for the extensions in Modules/
  It forces a rebuild of all extensions when a header files has been modified
........
  r60291 | raymond.hettinger | 2008-01-25 20:24:46 +0100 (Fri, 25 Jan 2008) | 4 lines

  Changes 54857 and 54840 broke code and were reverted in Py2.5 just before
  it was released, but that reversion never made it to the Py2.6 head.
........
  r60296 | guido.van.rossum | 2008-01-25 20:50:26 +0100 (Fri, 25 Jan 2008) | 2 lines

  Rewrite the list_inline_repeat overflow check slightly differently.
........
  r60301 | thomas.wouters | 2008-01-25 22:09:34 +0100 (Fri, 25 Jan 2008) | 4 lines


  Use the right (portable) definition of the max of a Py_ssize_t.
........
  r60303 | thomas.wouters | 2008-01-26 02:47:05 +0100 (Sat, 26 Jan 2008) | 5 lines


  Make 'testall' work again when building in a separate directory.
  test_distutils still fails when doing that.
........
  r60305 | neal.norwitz | 2008-01-26 06:54:48 +0100 (Sat, 26 Jan 2008) | 3 lines

  Prevent this test from failing if there are transient network problems
  by retrying the host for up to 3 times.
........
  r60306 | neal.norwitz | 2008-01-26 08:26:12 +0100 (Sat, 26 Jan 2008) | 12 lines

  Use a condition variable (threading.Event) rather than sleeps and checking a
  global to determine when the server is ready to be used.  This slows the test
  down, but should make it correct.  There was a race condition before where the
  server could have assigned a port, yet it wasn't ready to serve requests.  If
  the client sent a request before the server was completely ready, it would get
  an exception.  There was machinery to try to handle this condition.  All of
  that should be unnecessary and removed if this change works.  A NOTE was
  added as a comment about what needs to be fixed.

  The buildbots will tell us if there are more errors or
  if this test is now stable.
........
  r60307 | neal.norwitz | 2008-01-26 08:38:03 +0100 (Sat, 26 Jan 2008) | 3 lines

  Fix exception in tearDown on ppc buildbot.  If there's no directory,
  that shouldn't cause the test to fail.  Just like it setUp.
........
  r60308 | raymond.hettinger | 2008-01-26 09:19:06 +0100 (Sat, 26 Jan 2008) | 3 lines

  Make PySet_Add() work with frozensets.  Works like PyTuple_SetItem() to build-up values in a brand new frozenset.
........
  r60309 | neal.norwitz | 2008-01-26 09:26:00 +0100 (Sat, 26 Jan 2008) | 1 line

  The OS X buildbot had errors with the unavailable exceptions disabled.  Restore it.
........
  r60310 | raymond.hettinger | 2008-01-26 09:37:28 +0100 (Sat, 26 Jan 2008) | 4 lines

  Let marshal build-up sets and frozensets one element at a time.
  Saves the unnecessary creation of a tuple as intermediate container.
........
  r60311 | raymond.hettinger | 2008-01-26 09:41:13 +0100 (Sat, 26 Jan 2008) | 1 line

  Update test code for change to PySet_Add().
........
  r60312 | raymond.hettinger | 2008-01-26 10:31:11 +0100 (Sat, 26 Jan 2008) | 1 line

  Revert PySet_Add() changes.
........
  r60314 | georg.brandl | 2008-01-26 10:43:35 +0100 (Sat, 26 Jan 2008) | 2 lines

  #1934: fix os.path.isabs docs.
........
  r60316 | georg.brandl | 2008-01-26 12:00:18 +0100 (Sat, 26 Jan 2008) | 2 lines

  Add missing things in re docstring.
........
  r60317 | georg.brandl | 2008-01-26 12:02:22 +0100 (Sat, 26 Jan 2008) | 2 lines

  Slashes allowed on Windows.
........
  r60319 | georg.brandl | 2008-01-26 14:41:21 +0100 (Sat, 26 Jan 2008) | 2 lines

  Fix markup again.
........
  r60320 | andrew.kuchling | 2008-01-26 14:50:51 +0100 (Sat, 26 Jan 2008) | 1 line

  Add some items
........
  r60321 | georg.brandl | 2008-01-26 15:02:38 +0100 (Sat, 26 Jan 2008) | 2 lines

  Clarify "b" mode under Unix.
........
  r60322 | georg.brandl | 2008-01-26 15:03:47 +0100 (Sat, 26 Jan 2008) | 3 lines

  #1940: make it possible to use curses.filter() before curses.initscr()
  as the documentation says.
........
  r60324 | georg.brandl | 2008-01-26 15:14:20 +0100 (Sat, 26 Jan 2008) | 3 lines

  #1473257: add generator.gi_code attribute that refers to
  the original code object backing the generator. Patch by Collin Winter.
........
  r60325 | georg.brandl | 2008-01-26 15:19:22 +0100 (Sat, 26 Jan 2008) | 2 lines

  Move C API entries to the corresponding section.
........
  r60326 | christian.heimes | 2008-01-26 17:43:35 +0100 (Sat, 26 Jan 2008) | 1 line

  Unit test fix from Giampaolo Rodola, #1938
........
  r60327 | gregory.p.smith | 2008-01-26 19:51:05 +0100 (Sat, 26 Jan 2008) | 2 lines

  Update docs for new callpack params added in r60188
........
  r60329 | neal.norwitz | 2008-01-26 21:24:36 +0100 (Sat, 26 Jan 2008) | 3 lines

  Cleanup the code a bit.  test_rfind is failing on PPC and PPC64 buildbots,
  this might fix the problem.
........
  r60330 | neal.norwitz | 2008-01-26 22:02:45 +0100 (Sat, 26 Jan 2008) | 1 line

  Always try to remove the test file even if close raises an exception
........
  r60331 | neal.norwitz | 2008-01-26 22:21:59 +0100 (Sat, 26 Jan 2008) | 3 lines

  Reduce the race condition by signalling when the server is ready
  and not trying to connect before.
........
  r60334 | neal.norwitz | 2008-01-27 00:13:46 +0100 (Sun, 27 Jan 2008) | 5 lines

  On some systems (e.g., Ubuntu on hppa) the flush()
  doesn't cause the exception, but the close() does.

  Will backport.
........
  r60335 | neal.norwitz | 2008-01-27 00:14:17 +0100 (Sun, 27 Jan 2008) | 2 lines

  Consistently use tempfile.tempdir for the db_home directory.
........
  r60338 | neal.norwitz | 2008-01-27 02:44:05 +0100 (Sun, 27 Jan 2008) | 4 lines

  Eliminate the sleeps that assume the server will start in .5 seconds.
  This should make the test less flaky.  It also speeds up the test
  by about 75% on my box (20+ seconds -> ~4 seconds).
........
  r60342 | neal.norwitz | 2008-01-27 06:02:34 +0100 (Sun, 27 Jan 2008) | 6 lines

  Try to prevent this test from being flaky.  We might need a sleep in here
  which isn't as bad as it sounds.  The close() *should* raise an exception,
  so if it didn't we should give more time to sync and really raise it.

  Will backport.
........
  r60344 | jeffrey.yasskin | 2008-01-27 06:40:35 +0100 (Sun, 27 Jan 2008) | 3 lines

  Make rational.gcd() public and allow Rational to take decimal strings, per
  Raymond's advice.
........
  r60345 | neal.norwitz | 2008-01-27 08:36:03 +0100 (Sun, 27 Jan 2008) | 3 lines

  Mostly reformat.  Also set an error and return NULL if neither MS_WINDOWS
  nor UNIX is defined.  This may have caused problems on cygwin.
........
  r60346 | neal.norwitz | 2008-01-27 08:37:38 +0100 (Sun, 27 Jan 2008) | 3 lines

  Use int for the sign rather than a char.  char can be signed or unsigned.
  It's system dependent.  This might fix the problem with test_rfind failing.
........
  r60347 | neal.norwitz | 2008-01-27 08:41:33 +0100 (Sun, 27 Jan 2008) | 1 line

  Add stdarg include for va_list to get this to compile on cygwin
........
  r60348 | raymond.hettinger | 2008-01-27 11:13:57 +0100 (Sun, 27 Jan 2008) | 1 line

  Docstring nit
........
  r60349 | raymond.hettinger | 2008-01-27 11:47:55 +0100 (Sun, 27 Jan 2008) | 1 line

  Removed an unnecessary and confusing paragraph from the namedtuple docs.
........
2008-01-27 15:18:18 +00:00

523 lines
16 KiB
Python

"""TestCases for multi-threaded access to a DB.
"""
import os
import sys
import time
import errno
import shutil
import tempfile
from pprint import pprint
from random import random
DASH = b'-'
try:
from threading import Thread, currentThread
have_threads = True
except ImportError:
have_threads = False
try:
WindowsError
except NameError:
class WindowsError(Exception):
pass
import unittest
from bsddb.test.test_all import verbose
try:
# For Pythons w/distutils pybsddb
from bsddb3 import db, dbutils
except ImportError:
# For Python 2.3
from bsddb import db, dbutils
#----------------------------------------------------------------------
class BaseThreadedTestCase(unittest.TestCase):
dbtype = db.DB_UNKNOWN # must be set in derived class
dbopenflags = 0
dbsetflags = 0
envflags = 0
def setUp(self):
if verbose:
dbutils._deadlock_VerboseFile = sys.stdout
homeDir = os.path.join(tempfile.gettempdir(), 'db_home')
self.homeDir = homeDir
try:
os.mkdir(homeDir)
except OSError, e:
if e.errno != errno.EEXIST: raise
self.env = db.DBEnv()
self.setEnvOpts()
self.env.open(self.homeDir, self.envflags | db.DB_CREATE)
self.filename = self.__class__.__name__ + '.db'
self.d = db.DB(self.env)
if self.dbsetflags:
self.d.set_flags(self.dbsetflags)
self.d.open(self.filename, self.dbtype, self.dbopenflags|db.DB_CREATE)
def tearDown(self):
self.d.close()
self.env.close()
try:
shutil.rmtree(self.homeDir)
except OSError, e:
if e.errno != errno.EEXIST: raise
def setEnvOpts(self):
pass
def makeData(self, key):
return DASH.join([key] * 5)
def _writerThread(self, *args, **kwargs):
raise RuntimeError("must override this in a subclass")
def _readerThread(self, *args, **kwargs):
raise RuntimeError("must override this in a subclass")
def writerThread(self, *args, **kwargs):
try:
self._writerThread(*args, **kwargs)
except db.DBLockDeadlockError:
if verbose:
print(currentThread().getName(), 'died from', e)
else:
if verbose:
print(currentThread().getName(), "finished.")
def readerThread(self, *args, **kwargs):
try:
self._readerThread(*args, **kwargs)
except db.DBLockDeadlockError as e:
if verbose:
print(currentThread().getName(), 'died from', e)
else:
if verbose:
print(currentThread().getName(), "finished.")
#----------------------------------------------------------------------
class ConcurrentDataStoreBase(BaseThreadedTestCase):
dbopenflags = db.DB_THREAD
envflags = db.DB_THREAD | db.DB_INIT_CDB | db.DB_INIT_MPOOL
readers = 0 # derived class should set
writers = 0
records = 1000
def test01_1WriterMultiReaders(self):
if verbose:
print('\n', '-=' * 30)
print("Running %s.test01_1WriterMultiReaders..." % \
self.__class__.__name__)
print('Using:', self.homeDir, self.filename)
threads = []
wt = Thread(target = self.writerThread,
args = (self.d, self.records),
name = 'the writer',
)#verbose = verbose)
threads.append(wt)
for x in range(self.readers):
rt = Thread(target = self.readerThread,
args = (self.d, x),
name = 'reader %d' % x,
)#verbose = verbose)
threads.append(rt)
for t in threads:
t.start()
for t in threads:
t.join()
def _writerThread(self, d, howMany):
name = currentThread().getName()
start = 0
stop = howMany
if verbose:
print(name+": creating records", start, "-", stop)
for x in range(start, stop):
key = ('%04d' % x).encode("ascii")
d.put(key, self.makeData(key))
if verbose and x > start and x % 50 == 0:
print(name+": records", start, "-", x, "finished")
if verbose:
print("%s: finished creating records" % name)
## # Each write-cursor will be exclusive, the only one that can update the DB...
## if verbose: print "%s: deleting a few records" % name
## c = d.cursor(flags = db.DB_WRITECURSOR)
## for x in range(10):
## key = int(random() * howMany) + start
## key = '%04d' % key
## if d.has_key(key):
## c.set(key)
## c.delete()
## c.close()
def _readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum)
name = currentThread().getName()
for loop in range(5):
c = d.cursor()
count = 0
rec = c.first()
while rec:
count += 1
key, data = rec
self.assertEqual(self.makeData(key), data)
rec = c.next()
if verbose:
print(name+": found", count, "records")
c.close()
time.sleep(0.05)
class BTreeConcurrentDataStore(ConcurrentDataStoreBase):
dbtype = db.DB_BTREE
writers = 1
readers = 10
records = 1000
class HashConcurrentDataStore(ConcurrentDataStoreBase):
dbtype = db.DB_HASH
writers = 1
readers = 0
records = 1000
#----------------------------------------------------------------------
class SimpleThreadedBase(BaseThreadedTestCase):
dbopenflags = db.DB_THREAD
envflags = db.DB_THREAD | db.DB_INIT_MPOOL | db.DB_INIT_LOCK
readers = 5
writers = 3
records = 1000
def setEnvOpts(self):
self.env.set_lk_detect(db.DB_LOCK_DEFAULT)
def test02_SimpleLocks(self):
if verbose:
print('\n', '-=' * 30)
print("Running %s.test02_SimpleLocks..." % self.__class__.__name__)
threads = []
for x in range(self.writers):
wt = Thread(target = self.writerThread,
args = (self.d, self.records, x),
name = 'writer %d' % x,
)#verbose = verbose)
threads.append(wt)
for x in range(self.readers):
rt = Thread(target = self.readerThread,
args = (self.d, x),
name = 'reader %d' % x,
)#verbose = verbose)
threads.append(rt)
for t in threads:
t.start()
for t in threads:
t.join()
def _writerThread(self, d, howMany, writerNum):
name = currentThread().getName()
start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1
if verbose:
print("%s: creating records %d - %d" % (name, start, stop))
# create a bunch of records
for x in range(start, stop):
key = ('%04d' % x).encode("ascii")
dbutils.DeadlockWrap(d.put, key, self.makeData(key),
max_retries=20)
if verbose and x % 100 == 0:
print("%s: records %d - %d finished" % (name, start, x))
# do a bit or reading too
if random() <= 0.05:
for y in range(start, x):
key = ('%04d' % x).encode("ascii")
data = dbutils.DeadlockWrap(d.get, key, max_retries=20)
self.assertEqual(data, self.makeData(key))
# flush them
try:
dbutils.DeadlockWrap(d.sync, max_retries=20)
except db.DBIncompleteError as val:
if verbose:
print("could not complete sync()...")
# read them back, deleting a few
for x in range(start, stop):
key = ('%04d' % x).encode("ascii")
data = dbutils.DeadlockWrap(d.get, key, max_retries=20)
if verbose and x % 100 == 0:
print("%s: fetched record (%s, %s)" % (name, key, data))
self.assertEqual(data, self.makeData(key))
if random() <= 0.10:
dbutils.DeadlockWrap(d.delete, key, max_retries=20)
if verbose:
print("%s: deleted record %s" % (name, key))
if verbose:
print("%s: thread finished" % name)
def _readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum)
name = currentThread().getName()
for loop in range(5):
c = d.cursor()
count = 0
rec = dbutils.DeadlockWrap(c.first, max_retries=20)
while rec:
count += 1
key, data = rec
self.assertEqual(self.makeData(key), data)
rec = dbutils.DeadlockWrap(c.next, max_retries=20)
if verbose:
print("%s: found %d records" % (name, count))
c.close()
time.sleep(0.05)
if verbose:
print("%s: thread finished" % name)
class BTreeSimpleThreaded(SimpleThreadedBase):
dbtype = db.DB_BTREE
class HashSimpleThreaded(SimpleThreadedBase):
dbtype = db.DB_HASH
#----------------------------------------------------------------------
class ThreadedTransactionsBase(BaseThreadedTestCase):
dbopenflags = db.DB_THREAD | db.DB_AUTO_COMMIT
envflags = (db.DB_THREAD |
db.DB_INIT_MPOOL |
db.DB_INIT_LOCK |
db.DB_INIT_LOG |
db.DB_INIT_TXN
)
readers = 0
writers = 0
records = 2000
txnFlag = 0
def setEnvOpts(self):
#self.env.set_lk_detect(db.DB_LOCK_DEFAULT)
pass
def test03_ThreadedTransactions(self):
if verbose:
print('\n', '-=' * 30)
print("Running %s.test03_ThreadedTransactions..." % \
self.__class__.__name__)
threads = []
for x in range(self.writers):
wt = Thread(target = self.writerThread,
args = (self.d, self.records, x),
name = 'writer %d' % x,
)#verbose = verbose)
threads.append(wt)
for x in range(self.readers):
rt = Thread(target = self.readerThread,
args = (self.d, x),
name = 'reader %d' % x,
)#verbose = verbose)
threads.append(rt)
dt = Thread(target = self.deadlockThread)
dt.start()
for t in threads:
t.start()
for t in threads:
t.join()
self.doLockDetect = False
dt.join()
def doWrite(self, d, name, start, stop):
finished = False
while not finished:
try:
txn = self.env.txn_begin(None, self.txnFlag)
for x in range(start, stop):
key = ('%04d' % x).encode("ascii")
d.put(key, self.makeData(key), txn)
if verbose and x % 100 == 0:
print("%s: records %d - %d finished" % (name, start, x))
txn.commit()
finished = True
except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
if verbose:
print("%s: Aborting transaction (%s)" % (name, val))
txn.abort()
time.sleep(0.05)
def _writerThread(self, d, howMany, writerNum):
name = currentThread().getName()
start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1
if verbose:
print("%s: creating records %d - %d" % (name, start, stop))
step = 100
for x in range(start, stop, step):
self.doWrite(d, name, x, min(stop, x+step))
if verbose:
print("%s: finished creating records" % name)
if verbose:
print("%s: deleting a few records" % name)
finished = False
while not finished:
try:
recs = []
txn = self.env.txn_begin(None, self.txnFlag)
for x in range(10):
key = int(random() * howMany) + start
key = ('%04d' % key).encode("ascii")
data = d.get(key, None, txn, db.DB_RMW)
if data is not None:
d.delete(key, txn)
recs.append(key)
txn.commit()
finished = True
if verbose:
print("%s: deleted records %s" % (name, recs))
except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
if verbose:
print("%s: Aborting transaction (%s)" % (name, val))
txn.abort()
time.sleep(0.05)
if verbose:
print("%s: thread finished" % name)
def _readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum + 0.05)
name = currentThread().getName()
for loop in range(5):
finished = False
while not finished:
try:
txn = self.env.txn_begin(None, self.txnFlag)
c = d.cursor(txn)
count = 0
rec = c.first()
while rec:
count += 1
key, data = rec
self.assertEqual(self.makeData(key), data)
rec = c.next()
if verbose: print("%s: found %d records" % (name, count))
c.close()
txn.commit()
finished = True
except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
if verbose:
print("%s: Aborting transaction (%s)" % (name, val))
c.close()
txn.abort()
time.sleep(0.05)
time.sleep(0.05)
if verbose:
print("%s: thread finished" % name)
def deadlockThread(self):
self.doLockDetect = True
while self.doLockDetect:
time.sleep(0.5)
try:
aborted = self.env.lock_detect(
db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT)
if verbose and aborted:
print("deadlock: Aborted %d deadlocked transaction(s)" \
% aborted)
except db.DBError:
pass
class BTreeThreadedTransactions(ThreadedTransactionsBase):
dbtype = db.DB_BTREE
writers = 3
readers = 5
records = 2000
class HashThreadedTransactions(ThreadedTransactionsBase):
dbtype = db.DB_HASH
writers = 1
readers = 5
records = 2000
class BTreeThreadedNoWaitTransactions(ThreadedTransactionsBase):
dbtype = db.DB_BTREE
writers = 3
readers = 5
records = 2000
txnFlag = db.DB_TXN_NOWAIT
class HashThreadedNoWaitTransactions(ThreadedTransactionsBase):
dbtype = db.DB_HASH
writers = 1
readers = 5
records = 2000
txnFlag = db.DB_TXN_NOWAIT
#----------------------------------------------------------------------
def test_suite():
suite = unittest.TestSuite()
if have_threads:
suite.addTest(unittest.makeSuite(BTreeConcurrentDataStore))
suite.addTest(unittest.makeSuite(HashConcurrentDataStore))
suite.addTest(unittest.makeSuite(BTreeSimpleThreaded))
suite.addTest(unittest.makeSuite(HashSimpleThreaded))
suite.addTest(unittest.makeSuite(BTreeThreadedTransactions))
suite.addTest(unittest.makeSuite(HashThreadedTransactions))
suite.addTest(unittest.makeSuite(BTreeThreadedNoWaitTransactions))
suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions))
else:
print("Threads not available, skipping thread tests.")
return suite
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')