Skip to content

Commit 2b96159

Browse files
authored
Merge pull request #19 from mongodb-labs/PERF-4758
PERF-4758: Update py-tpcc to use Python3
2 parents 76208db + 33b1570 commit 2b96159

File tree

9 files changed

+50
-40
lines changed

9 files changed

+50
-40
lines changed

pytpcc/constants.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@
9191
MIN_CARRIER_ID = 1
9292
MAX_CARRIER_ID = 10
9393
# HACK: This is not strictly correct, but it works
94-
NULL_CARRIER_ID = 0L
94+
NULL_CARRIER_ID = 0
9595
# o_id < than this value, carrier != null, >= -> carrier == null
9696
NULL_CARRIER_LOWER_BOUND = 2101
9797
MIN_OL_CNT = 5

pytpcc/coordinator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def startExecution(scaleParameters, args, config,channels):
160160
## Load Configuration file
161161
if args['config']:
162162
logging.debug("Loading configuration file '%s'" % args['config'])
163-
cparser = SafeConfigParser()
163+
cparser = ConfigParser()
164164
cparser.read(os.path.realpath(args['config'].name))
165165
config = dict(cparser.items(args['system']))
166166
else:

pytpcc/drivers/mongodbdriver.py

+17-15
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
import pymongo
4141

4242
import constants
43-
from abstractdriver import AbstractDriver
43+
from .abstractdriver import AbstractDriver
4444

4545
TABLE_COLUMNS = {
4646
constants.TABLENAME_ITEM: [
@@ -345,9 +345,9 @@ def loadConfig(self, config):
345345
logging.error("ConnectionFailure %d (%s) when connected to %s: ",
346346
exc.code, exc.details, display_uri)
347347
return
348-
except pymongo.errors.PyMongoError, err:
348+
except pymongo.errors.PyMongoError as err:
349349
logging.error("Some general error (%s) when connected to %s: ", str(err), display_uri)
350-
print "Got some other error: %s" % str(err)
350+
print("Got some other error: %s" % str(err))
351351
return
352352

353353
## ----------------------------------------------
@@ -408,7 +408,7 @@ def loadTuples(self, tableName, tuples):
408408
tuple_dicts.append(dict([(columns[i], t[i]) for i in num_columns]))
409409
## FOR
410410

411-
self.database[tableName].insert(tuple_dicts)
411+
self.database[tableName].insert_many(tuple_dicts)
412412
## IF
413413

414414
return
@@ -593,7 +593,7 @@ def _doNewOrderTxn(self, s, params):
593593
session=s)
594594
if not d:
595595
d1 = self.district.find_one({"D_ID": d_id, "D_W_ID": w_id, "$comment": "new order did not find district"})
596-
print d1, w_id, d_id, c_id, i_ids, i_w_ids, s_dist_col
596+
print(d1, w_id, d_id, c_id, i_ids, i_w_ids, s_dist_col)
597597
assert d, "Couldn't find district in new order w_id %d d_id %d" % (w_id, d_id)
598598
else:
599599
d = self.district.find_one({"D_ID": d_id, "D_W_ID": w_id, "$comment": comment},
@@ -621,7 +621,8 @@ def _doNewOrderTxn(self, s, params):
621621
#print constants.INVALID_ITEM_MESSAGE + ", Aborting transaction (ok for 1%)"
622622
return None
623623
## IF
624-
items = sorted(items, key=lambda x: i_ids.index(x['I_ID']))
624+
xxi_ids = tuple(map(lambda o: o['I_ID'], items))
625+
items = sorted(items, key=lambda x: xxi_ids.index(x['I_ID']))
625626

626627
# getWarehouseTaxRate
627628
w = self.warehouse.find_one({"W_ID": w_id, "$comment": comment}, {"_id":0, "W_TAX": 1}, session=s)
@@ -676,7 +677,8 @@ def _doNewOrderTxn(self, s, params):
676677
session=s))
677678
## IF
678679
assert len(all_stocks) == ol_cnt, "all_stocks len %d != ol_cnt %d" % (len(all_stocks), ol_cnt)
679-
all_stocks = sorted(all_stocks, key=lambda x: item_w_list.index((x['S_I_ID'], x["S_W_ID"])))
680+
xxxi_ids = tuple(map(lambda o: (o['S_I_ID'], o['S_W_ID']), all_stocks))
681+
all_stocks = sorted(all_stocks, key=lambda x: xxxi_ids.index((x['S_I_ID'], x["S_W_ID"])))
680682

681683
## ----------------
682684
## Insert Order Line, Stock Item Information
@@ -820,7 +822,7 @@ def _doOrderStatusTxn(self, s, params):
820822
all_customers = list(self.customer.find(search_fields, return_fields, session=s))
821823
namecnt = len(all_customers)
822824
assert namecnt > 0, "No matching customer for last name %s!" % c_last
823-
index = (namecnt-1)/2
825+
index = (namecnt-1)//2
824826
c = all_customers[index]
825827
c_id = c["C_ID"]
826828
## IF
@@ -891,7 +893,7 @@ def _doPaymentTxn(self, s, params):
891893
session=s)
892894
if not d:
893895
d1 = self.district.find_one({"D_ID": d_id, "D_W_ID": w_id, "$comment": "payment did not find district"})
894-
print d1, w_id, d_id, h_amount, c_w_id, c_d_id, c_id, c_last, h_date
896+
print(d1, w_id, d_id, h_amount, c_w_id, c_d_id, c_id, c_last, h_date)
895897
assert d, "Couldn't find district in payment w_id %d d_id %d" % (w_id, d_id)
896898
else:
897899
d = self.district.find_one({"D_W_ID": w_id, "D_ID": d_id, "$comment": comment},
@@ -942,7 +944,7 @@ def _doPaymentTxn(self, s, params):
942944
all_customers = list(self.customer.find(search_fields, return_fields, session=s))
943945
namecnt = len(all_customers)
944946
assert namecnt > 0, "No matching customer w %d d %d clast %s" % (w_id, d_id, c_last)
945-
index = (namecnt-1)/2
947+
index = (namecnt-1)//2
946948
c = all_customers[index]
947949
c_id = c["C_ID"]
948950
## IF
@@ -1075,9 +1077,9 @@ def _doStockLevelTxn(self, s, params):
10751077
ol_ids.add(ol["OL_I_ID"])
10761078
## FOR
10771079

1078-
result = self.stock.find({"S_W_ID": w_id,
1080+
result = self.stock.count_documents({"S_W_ID": w_id,
10791081
"S_I_ID": {"$in": list(ol_ids)},
1080-
"S_QUANTITY": {"$lt": threshold}, "$comment": comment}).count()
1082+
"S_QUANTITY": {"$lt": threshold}, "$comment": comment})
10811083

10821084
return int(result)
10831085

@@ -1095,11 +1097,11 @@ def run_transaction(self, txn_callback, session, name, params):
10951097
exc.code, exc.details, name)
10961098
return (False, None)
10971099
logging.error("Failed with unknown OperationFailure: %d", exc.code)
1098-
print "Failed with unknown OperationFailure: %d" % exc.code
1099-
print exc.details
1100+
print("Failed with unknown OperationFailure: %d" % exc.code)
1101+
print(exc.details)
11001102
raise
11011103
except pymongo.errors.ConnectionFailure:
1102-
print "ConnectionFailure during %s: " % name
1104+
print("ConnectionFailure during %s: " % name)
11031105
return (False, None)
11041106
## TRY
11051107

pytpcc/runtime/executor.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,10 @@ def execute(self, duration):
6868
(val, retries) = self.driver.executeTransaction(txn, params)
6969
except KeyboardInterrupt:
7070
return -1
71-
except (Exception, AssertionError), ex:
71+
except (Exception, AssertionError) as ex:
7272
logging.warn("Failed to execute Transaction '%s': %s" % (txn, ex))
7373
traceback.print_exc(file=sys.stdout)
74-
print "Aborting some transaction with some error %s %s" % (txn, ex)
74+
print("Aborting some transaction with some error %s %s" % (txn, ex))
7575
global_result.abortTransaction(global_txn_id)
7676
batch_result.abortTransaction(batch_txn_id)
7777
if self.stop_on_error: raise

pytpcc/runtime/loader.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def execute(self):
7373
## ==============================================
7474
def loadItems(self):
7575
## Select 10% of the rows to be marked "original"
76-
originalRows = rand.selectUniqueIds(self.scaleParameters.items / 10, 1, self.scaleParameters.items)
76+
originalRows = rand.selectUniqueIds(self.scaleParameters.items // 10, 1, self.scaleParameters.items)
7777

7878
## Load all of the items
7979
tuples = [ ]
@@ -112,7 +112,7 @@ def loadWarehouse(self, w_id):
112112
h_tuples = [ ]
113113

114114
## Select 10% of the customers to have bad credit
115-
selectedRows = rand.selectUniqueIds(self.scaleParameters.customersPerDistrict / 10, 1, self.scaleParameters.customersPerDistrict)
115+
selectedRows = rand.selectUniqueIds(self.scaleParameters.customersPerDistrict // 10, 1, self.scaleParameters.customersPerDistrict)
116116

117117
## TPC-C 4.3.3.1. says that o_c_id should be a permutation of [1, 3000]. But since it
118118
## is a c_id field, it seems to make sense to have it be a permutation of the
@@ -160,7 +160,7 @@ def loadWarehouse(self, w_id):
160160

161161
## Select 10% of the stock to be marked "original"
162162
s_tuples = [ ]
163-
selectedRows = rand.selectUniqueIds(self.scaleParameters.items / 10, 1, self.scaleParameters.items)
163+
selectedRows = rand.selectUniqueIds(self.scaleParameters.items // 10, 1, self.scaleParameters.items)
164164
total_tuples = 0
165165
for i_id in range(1, self.scaleParameters.items+1):
166166
original = (i_id in selectedRows)

pytpcc/tpcc.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import glob
3636
import time
3737
import multiprocessing
38-
from ConfigParser import SafeConfigParser
38+
from configparser import ConfigParser
3939
from pprint import pprint, pformat
4040

4141
from util import results, scaleparameters
@@ -90,6 +90,10 @@ def startLoading(driverClass, scaleParameters, args, config):
9090
## FOR
9191

9292
loader_results = []
93+
try:
94+
del args['config']
95+
except KeyError:
96+
print()
9397
for i in range(args['clients']):
9498
r = pool.apply_async(loaderFunc, (driverClass, scaleParameters, args, config, w_ids[i]))
9599
loader_results.append(r)
@@ -122,7 +126,7 @@ def loaderFunc(driverClass, scaleParameters, args, config, w_ids):
122126
driver.loadFinish()
123127
except KeyboardInterrupt:
124128
return -1
125-
except (Exception, AssertionError), ex:
129+
except (Exception, AssertionError) as ex:
126130
logging.warn("Failed to load data: %s", ex)
127131
raise
128132

@@ -135,7 +139,10 @@ def startExecution(driverClass, scaleParameters, args, config):
135139
logging.debug("Creating client pool with %d processes", args['clients'])
136140
pool = multiprocessing.Pool(args['clients'])
137141
debug = logging.getLogger().isEnabledFor(logging.DEBUG)
138-
142+
try:
143+
del args['config']
144+
except KeyError:
145+
print()
139146
worker_results = []
140147
for _ in range(args['clients']):
141148
r = pool.apply_async(executorFunc, (driverClass, scaleParameters, args, config, debug,))
@@ -184,7 +191,7 @@ def executorFunc(driverClass, scaleParameters, args, config, debug):
184191
aparser = argparse.ArgumentParser(description='Python implementation of the TPC-C Benchmark')
185192
aparser.add_argument('system', choices=getDrivers(),
186193
help='Target system driver')
187-
aparser.add_argument('--config', type=file,
194+
aparser.add_argument('--config', type=open,
188195
help='Path to driver configuration file')
189196
aparser.add_argument('--reset', action='store_true',
190197
help='Instruct the driver to reset the contents of the database')
@@ -221,14 +228,14 @@ def executorFunc(driverClass, scaleParameters, args, config, debug):
221228
assert driver != None, "Failed to create '%s' driver" % args['system']
222229
if args['print_config']:
223230
config = driver.makeDefaultConfig()
224-
print driver.formatConfig(config)
225-
print
231+
print(driver.formatConfig(config))
232+
print()
226233
sys.exit(0)
227234

228235
## Load Configuration file
229236
if args['config']:
230237
logging.debug("Loading configuration file '%s'", args['config'])
231-
cparser = SafeConfigParser()
238+
cparser = ConfigParser()
232239
cparser.read(os.path.realpath(args['config'].name))
233240
config = dict(cparser.items(args['system']))
234241
else:

pytpcc/util/nurand.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,14 @@
2929
# OTHER DEALINGS IN THE SOFTWARE.
3030
# -----------------------------------------------------------------------
3131

32-
import rand
32+
import random
3333

3434
def makeForLoad():
3535
"""Create random NURand constants, appropriate for loading the database."""
36-
cLast = rand.number(0, 255)
37-
cId = rand.number(0, 1023)
38-
orderLineItemId = rand.number(0, 8191)
36+
cLast = random.randint(0, 255)
37+
cId = random.randint(0, 1023)
38+
orderLineItemId = random.randint(0, 8191)
39+
return NURandC(cLast, cId, orderLineItemId)
3940
return NURandC(cLast, cId, orderLineItemId)
4041

4142
def validCRun(cRun, cLoad):
@@ -45,13 +46,13 @@ def validCRun(cRun, cLoad):
4546

4647
def makeForRun(loadC):
4748
"""Create random NURand constants for running TPC-C. TPC-C 2.1.6.1. (page 20) specifies the valid range for these constants."""
48-
cRun = rand.number(0, 255)
49+
cRun = random.randint(0, 255)
4950
while validCRun(cRun, loadC.cLast) == False:
50-
cRun = rand.number(0, 255)
51+
cRun = random.randint(0, 255)
5152
assert validCRun(cRun, loadC.cLast)
5253

53-
cId = rand.number(0, 1023)
54-
orderLineItemId = rand.number(0, 8191)
54+
cId = random.randint(0, 1023)
55+
orderLineItemId = random.randint(0, 8191)
5556
return NURandC(cRun, cId, orderLineItemId)
5657

5758
class NURandC:

pytpcc/util/rand.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
# -----------------------------------------------------------------------
3131

3232
import random
33-
import nurand
33+
from . import nurand
3434

3535
SYLLABLES = [ "BAR", "OUGHT", "ABLE", "PRI", "PRES", "ESE", "ANTI", "CALLY", "ATION", "EING" ]
3636

@@ -129,7 +129,7 @@ def makeLastName(number):
129129
"""A last name as defined by TPC-C 4.3.2.3. Not actually random."""
130130
global SYLLABLES
131131
assert 0 <= number and number <= 999
132-
indicies = [ number/100, (number/10)%10, number%10 ]
132+
indicies = [ number//100, (number//10)%10, number%10 ]
133133
return "".join(map(lambda x: SYLLABLES[x], indicies))
134134
## DEF
135135

pytpcc/util/results.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def append(self, r):
126126
self.txn_times[txn_name] = orig_time + r.txn_times[txn_name]
127127
self.txn_retries[txn_name] = orig_retries + r.txn_retries[txn_name]
128128
self.txn_aborts[txn_name] = orig_aborts + r.txn_aborts[txn_name]
129-
print "%s [cnt=%d, time=%d]" % (txn_name, self.txn_counters[txn_name], self.txn_times[txn_name])
129+
print("%s [cnt=%d, time=%d]" % (txn_name, self.txn_counters[txn_name], self.txn_times[txn_name]))
130130
# logging.debug("%s [cnt=%d, time=%d]" % (txn_name, self.txn_counters[txn_name], self.txn_times[txn_name]))
131131
if txn_name not in self.latencies:
132132
self.latencies[txn_name] = []

0 commit comments

Comments
 (0)