| 1 |
/*- |
| 2 |
* See the file LICENSE for redistribution information. |
| 3 |
* |
| 4 |
* Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved. |
| 5 |
* |
| 6 |
* $Id$ |
| 7 |
*/ |
| 8 |
|
| 9 |
// File TxnGuide.cpp |
| 10 |
|
| 11 |
#include <cstdlib> |
| 12 |
#include <cstring> |
| 13 |
#include <iostream> |
| 14 |
#include <db_cxx.h> |
| 15 |
|
| 16 |
#ifdef _WIN32 |
| 17 |
#include <windows.h> |
| 18 |
extern "C" { |
| 19 |
extern int getopt(int, char * const *, const char *); |
| 20 |
extern char *optarg; |
| 21 |
} |
| 22 |
#define PATHD '\\' |
| 23 |
|
| 24 |
typedef HANDLE thread_t; |
| 25 |
#define thread_create(thrp, attr, func, arg) \ |
| 26 |
(((*(thrp) = CreateThread(NULL, 0, \ |
| 27 |
(LPTHREAD_START_ROUTINE)(func), (arg), 0, NULL)) == NULL) ? -1 : 0) |
| 28 |
#define thread_join(thr, statusp) \ |
| 29 |
((WaitForSingleObject((thr), INFINITE) == WAIT_OBJECT_0) && \ |
| 30 |
((statusp == NULL) ? 0 : \ |
| 31 |
(GetExitCodeThread((thr), (LPDWORD)(statusp)) ? 0 : -1))) |
| 32 |
|
| 33 |
typedef HANDLE mutex_t; |
| 34 |
#define mutex_init(m, attr) \ |
| 35 |
(((*(m) = CreateMutex(NULL, FALSE, NULL)) != NULL) ? 0 : -1) |
| 36 |
#define mutex_lock(m) \ |
| 37 |
((WaitForSingleObject(*(m), INFINITE) == WAIT_OBJECT_0) ? 0 : -1) |
| 38 |
#define mutex_unlock(m) (ReleaseMutex(*(m)) ? 0 : -1) |
| 39 |
#else |
| 40 |
#include <pthread.h> |
| 41 |
#include <unistd.h> |
| 42 |
#define PATHD '/' |
| 43 |
|
| 44 |
typedef pthread_t thread_t; |
| 45 |
#define thread_create(thrp, attr, func, arg) \ |
| 46 |
pthread_create((thrp), (attr), (func), (arg)) |
| 47 |
#define thread_join(thr, statusp) pthread_join((thr), (statusp)) |
| 48 |
|
| 49 |
typedef pthread_mutex_t mutex_t; |
| 50 |
#define mutex_init(m, attr) pthread_mutex_init((m), (attr)) |
| 51 |
#define mutex_lock(m) pthread_mutex_lock(m) |
| 52 |
#define mutex_unlock(m) pthread_mutex_unlock(m) |
| 53 |
#endif |
| 54 |
|
| 55 |
// Run 5 writers threads at a time. |
| 56 |
#define NUMWRITERS 5 |
| 57 |
|
| 58 |
// Printing of thread_t is implementation-specific, so we |
| 59 |
// create our own thread IDs for reporting purposes. |
| 60 |
int global_thread_num; |
| 61 |
mutex_t thread_num_lock; |
| 62 |
|
| 63 |
// Forward declarations |
| 64 |
int countRecords(Db *, DbTxn *); |
| 65 |
int openDb(Db **, const char *, const char *, DbEnv *, u_int32_t); |
| 66 |
int usage(void); |
| 67 |
void *writerThread(void *); |
| 68 |
|
| 69 |
// Usage function |
| 70 |
int |
| 71 |
usage() |
| 72 |
{ |
| 73 |
std::cerr << " [-h <database_home_directory>]" << std::endl; |
| 74 |
return (EXIT_FAILURE); |
| 75 |
} |
| 76 |
|
| 77 |
int |
| 78 |
main(int argc, char *argv[]) |
| 79 |
{ |
| 80 |
// Initialize our handles |
| 81 |
Db *dbp = NULL; |
| 82 |
DbEnv *envp = NULL; |
| 83 |
|
| 84 |
thread_t writerThreads[NUMWRITERS]; |
| 85 |
int ch, i; |
| 86 |
u_int32_t envFlags; |
| 87 |
char *dbHomeDir; |
| 88 |
extern char *optarg; |
| 89 |
|
| 90 |
// Application name |
| 91 |
const char *progName = "TxnGuide"; |
| 92 |
|
| 93 |
// Database file name |
| 94 |
const char *fileName = "mydb.db"; |
| 95 |
|
| 96 |
// Parse the command line arguments |
| 97 |
#ifdef _WIN32 |
| 98 |
dbHomeDir = ".\\"; |
| 99 |
#else |
| 100 |
dbHomeDir = (char *)"./"; |
| 101 |
#endif |
| 102 |
while ((ch = getopt(argc, argv, "h:")) != EOF) |
| 103 |
switch (ch) { |
| 104 |
case 'h': |
| 105 |
dbHomeDir = optarg; |
| 106 |
break; |
| 107 |
case '?': |
| 108 |
default: |
| 109 |
return (usage()); |
| 110 |
} |
| 111 |
|
| 112 |
|
| 113 |
// Env open flags |
| 114 |
envFlags = |
| 115 |
DB_CREATE | // Create the environment if it does not exist |
| 116 |
DB_RECOVER | // Run normal recovery. |
| 117 |
DB_INIT_LOCK | // Initialize the locking subsystem |
| 118 |
DB_INIT_LOG | // Initialize the logging subsystem |
| 119 |
DB_INIT_TXN | // Initialize the transactional subsystem. This |
| 120 |
// also turns on logging. |
| 121 |
DB_INIT_MPOOL | // Initialize the memory pool (in-memory cache) |
| 122 |
DB_THREAD; // Cause the environment to be free-threaded |
| 123 |
|
| 124 |
try { |
| 125 |
// Create and open the environment |
| 126 |
envp = new DbEnv(0); |
| 127 |
|
| 128 |
// Indicate that we want db to internally perform deadlock |
| 129 |
// detection. Also indicate that the transaction with |
| 130 |
// the fewest number of write locks will receive the |
| 131 |
// deadlock notification in the event of a deadlock. |
| 132 |
envp->set_lk_detect(DB_LOCK_MINWRITE); |
| 133 |
|
| 134 |
envp->open(dbHomeDir, envFlags, 0); |
| 135 |
|
| 136 |
|
| 137 |
// If we had utility threads (for running checkpoints or |
| 138 |
// deadlock detection, for example) we would spawn those |
| 139 |
// here. However, for a simple example such as this, |
| 140 |
// that is not required. |
| 141 |
|
| 142 |
// Open the database |
| 143 |
openDb(&dbp, progName, fileName, |
| 144 |
envp, DB_DUPSORT); |
| 145 |
|
| 146 |
// Initialize a mutex. Used to help provide thread ids. |
| 147 |
(void)mutex_init(&thread_num_lock, NULL); |
| 148 |
|
| 149 |
// Start the writer threads. |
| 150 |
for (i = 0; i < NUMWRITERS; i++) |
| 151 |
(void)thread_create( |
| 152 |
&writerThreads[i], NULL, |
| 153 |
writerThread, (void *)dbp); |
| 154 |
|
| 155 |
// Join the writers |
| 156 |
for (i = 0; i < NUMWRITERS; i++) |
| 157 |
(void)thread_join(writerThreads[i], NULL); |
| 158 |
|
| 159 |
} catch(DbException &e) { |
| 160 |
std::cerr << "Error opening database environment: " |
| 161 |
<< dbHomeDir << std::endl; |
| 162 |
std::cerr << e.what() << std::endl; |
| 163 |
return (EXIT_FAILURE); |
| 164 |
} |
| 165 |
|
| 166 |
try { |
| 167 |
// Close our database handle if it was opened. |
| 168 |
if (dbp != NULL) |
| 169 |
dbp->close(0); |
| 170 |
|
| 171 |
// Close our environment if it was opened. |
| 172 |
if (envp != NULL) |
| 173 |
envp->close(0); |
| 174 |
} catch(DbException &e) { |
| 175 |
std::cerr << "Error closing database and environment." |
| 176 |
<< std::endl; |
| 177 |
std::cerr << e.what() << std::endl; |
| 178 |
return (EXIT_FAILURE); |
| 179 |
} |
| 180 |
|
| 181 |
// Final status message and return. |
| 182 |
|
| 183 |
std::cout << "I'm all done." << std::endl; |
| 184 |
return (EXIT_SUCCESS); |
| 185 |
} |
| 186 |
|
| 187 |
// A function that performs a series of writes to a |
| 188 |
// Berkeley DB database. The information written |
| 189 |
// to the database is largely nonsensical, but the |
| 190 |
// mechanism of transactional commit/abort and |
| 191 |
// deadlock detection is illustrated here. |
| 192 |
void * |
| 193 |
writerThread(void *args) |
| 194 |
{ |
| 195 |
int j, thread_num; |
| 196 |
int max_retries = 20; // Max retry on a deadlock |
| 197 |
const char *key_strings[] = {"key 1", "key 2", "key 3", "key 4", |
| 198 |
"key 5", "key 6", "key 7", "key 8", |
| 199 |
"key 9", "key 10"}; |
| 200 |
|
| 201 |
Db *dbp = (Db *)args; |
| 202 |
DbEnv *envp = dbp->get_env(); |
| 203 |
|
| 204 |
// Get the thread number |
| 205 |
(void)mutex_lock(&thread_num_lock); |
| 206 |
global_thread_num++; |
| 207 |
thread_num = global_thread_num; |
| 208 |
(void)mutex_unlock(&thread_num_lock); |
| 209 |
|
| 210 |
// Initialize the random number generator |
| 211 |
srand(thread_num); |
| 212 |
|
| 213 |
// Perform 50 transactions |
| 214 |
for (int i=0; i<50; i++) { |
| 215 |
DbTxn *txn; |
| 216 |
bool retry = true; |
| 217 |
int retry_count = 0; |
| 218 |
// while loop is used for deadlock retries |
| 219 |
while (retry) { |
| 220 |
// try block used for deadlock detection and |
| 221 |
// general db exception handling |
| 222 |
try { |
| 223 |
|
| 224 |
// Begin our transaction. We group multiple writes in |
| 225 |
// this thread under a single transaction so as to |
| 226 |
// (1) show that you can atomically perform multiple |
| 227 |
// writes at a time, and (2) to increase the chances |
| 228 |
// of a deadlock occurring so that we can observe our |
| 229 |
// deadlock detection at work. |
| 230 |
|
| 231 |
// Normally we would want to avoid the potential for |
| 232 |
// deadlocks, so for this workload the correct thing |
| 233 |
// would be to perform our puts with autocommit. But |
| 234 |
// that would excessively simplify our example, so we |
| 235 |
// do the "wrong" thing here instead. |
| 236 |
txn = NULL; |
| 237 |
envp->txn_begin(NULL, &txn, 0); |
| 238 |
|
| 239 |
// Perform the database write for this transaction. |
| 240 |
for (j = 0; j < 10; j++) { |
| 241 |
Dbt key, value; |
| 242 |
key.set_data((void *)key_strings[j]); |
| 243 |
key.set_size((u_int32_t)strlen(key_strings[j]) + 1); |
| 244 |
|
| 245 |
int payload = rand() + i; |
| 246 |
value.set_data(&payload); |
| 247 |
value.set_size(sizeof(int)); |
| 248 |
|
| 249 |
// Perform the database put |
| 250 |
dbp->put(txn, &key, &value, 0); |
| 251 |
} |
| 252 |
|
| 253 |
// countRecords runs a cursor over the entire database. |
| 254 |
// We do this to illustrate issues of deadlocking |
| 255 |
std::cout << thread_num << " : Found " |
| 256 |
<< countRecords(dbp, NULL) |
| 257 |
<< " records in the database." << std::endl; |
| 258 |
|
| 259 |
std::cout << thread_num << " : committing txn : " << i |
| 260 |
<< std::endl; |
| 261 |
|
| 262 |
// commit |
| 263 |
try { |
| 264 |
txn->commit(0); |
| 265 |
retry = false; |
| 266 |
txn = NULL; |
| 267 |
} catch (DbException &e) { |
| 268 |
std::cout << "Error on txn commit: " |
| 269 |
<< e.what() << std::endl; |
| 270 |
} |
| 271 |
} catch (DbDeadlockException &) { |
| 272 |
// First thing that we MUST do is abort the transaction. |
| 273 |
if (txn != NULL) |
| 274 |
(void)txn->abort(); |
| 275 |
|
| 276 |
// Now we decide if we want to retry the operation. |
| 277 |
// If we have retried less than max_retries, |
| 278 |
// increment the retry count and goto retry. |
| 279 |
if (retry_count < max_retries) { |
| 280 |
std::cout << "############### Writer " << thread_num |
| 281 |
<< ": Got DB_LOCK_DEADLOCK.\n" |
| 282 |
<< "Retrying write operation." |
| 283 |
<< std::endl; |
| 284 |
retry_count++; |
| 285 |
retry = true; |
| 286 |
} else { |
| 287 |
// Otherwise, just give up. |
| 288 |
std::cerr << "Writer " << thread_num |
| 289 |
<< ": Got DeadLockException and out of " |
| 290 |
<< "retries. Giving up." << std::endl; |
| 291 |
retry = false; |
| 292 |
} |
| 293 |
} catch (DbException &e) { |
| 294 |
std::cerr << "db put failed" << std::endl; |
| 295 |
std::cerr << e.what() << std::endl; |
| 296 |
if (txn != NULL) |
| 297 |
txn->abort(); |
| 298 |
retry = false; |
| 299 |
} catch (std::exception &ee) { |
| 300 |
std::cerr << "Unknown exception: " << ee.what() << std::endl; |
| 301 |
return (0); |
| 302 |
} |
| 303 |
} |
| 304 |
} |
| 305 |
return (0); |
| 306 |
} |
| 307 |
|
| 308 |
|
| 309 |
// This simply counts the number of records contained in the |
| 310 |
// database and returns the result. You can use this method |
| 311 |
// in three ways: |
| 312 |
// |
| 313 |
// First call it with an active txn handle. |
| 314 |
// Secondly, configure the cursor for uncommitted reads |
| 315 |
// |
| 316 |
// Third, call countRecords AFTER the writer has committed |
| 317 |
// its transaction. |
| 318 |
// |
| 319 |
// If you do none of these things, the writer thread will |
| 320 |
// self-deadlock. |
| 321 |
// |
| 322 |
// Note that this method exists only for illustrative purposes. |
| 323 |
// A more straight-forward way to count the number of records in |
| 324 |
// a database is to use the Database.getStats() method. |
| 325 |
int |
| 326 |
countRecords(Db *dbp, DbTxn *txn) |
| 327 |
{ |
| 328 |
|
| 329 |
Dbc *cursorp = NULL; |
| 330 |
int count = 0; |
| 331 |
|
| 332 |
try { |
| 333 |
// Get the cursor |
| 334 |
dbp->cursor(txn, &cursorp, DB_READ_UNCOMMITTED); |
| 335 |
|
| 336 |
Dbt key, value; |
| 337 |
while (cursorp->get(&key, &value, DB_NEXT) == 0) { |
| 338 |
count++; |
| 339 |
} |
| 340 |
} catch (DbDeadlockException &de) { |
| 341 |
std::cerr << "countRecords: got deadlock" << std::endl; |
| 342 |
cursorp->close(); |
| 343 |
throw de; |
| 344 |
} catch (DbException &e) { |
| 345 |
std::cerr << "countRecords error:" << std::endl; |
| 346 |
std::cerr << e.what() << std::endl; |
| 347 |
} |
| 348 |
|
| 349 |
if (cursorp != NULL) { |
| 350 |
try { |
| 351 |
cursorp->close(); |
| 352 |
} catch (DbException &e) { |
| 353 |
std::cerr << "countRecords: cursor close failed:" << std::endl; |
| 354 |
std::cerr << e.what() << std::endl; |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
return (count); |
| 359 |
} |
| 360 |
|
| 361 |
|
| 362 |
// Open a Berkeley DB database |
| 363 |
int |
| 364 |
openDb(Db **dbpp, const char *progname, const char *fileName, |
| 365 |
DbEnv *envp, u_int32_t extraFlags) |
| 366 |
{ |
| 367 |
int ret; |
| 368 |
u_int32_t openFlags; |
| 369 |
|
| 370 |
try { |
| 371 |
Db *dbp = new Db(envp, 0); |
| 372 |
|
| 373 |
// Point to the new'd Db |
| 374 |
*dbpp = dbp; |
| 375 |
|
| 376 |
if (extraFlags != 0) |
| 377 |
ret = dbp->set_flags(extraFlags); |
| 378 |
|
| 379 |
// Now open the database */ |
| 380 |
openFlags = DB_CREATE | // Allow database creation |
| 381 |
DB_READ_UNCOMMITTED | // Allow uncommitted reads |
| 382 |
DB_AUTO_COMMIT | // Allow autocommit |
| 383 |
DB_THREAD; // Cause the database to be free-threaded |
| 384 |
|
| 385 |
dbp->open(NULL, // Txn pointer |
| 386 |
fileName, // File name |
| 387 |
NULL, // Logical db name |
| 388 |
DB_BTREE, // Database type (using btree) |
| 389 |
openFlags, // Open flags |
| 390 |
0); // File mode. Using defaults |
| 391 |
} catch (DbException &e) { |
| 392 |
std::cerr << progname << ": openDb: db open failed:" << std::endl; |
| 393 |
std::cerr << e.what() << std::endl; |
| 394 |
return (EXIT_FAILURE); |
| 395 |
} |
| 396 |
|
| 397 |
return (EXIT_SUCCESS); |
| 398 |
} |
| 399 |
|