| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.mvstore.tx; |
| 7 |
|
| 8 |
import java.util.ArrayList; |
| 9 |
import java.util.BitSet; |
| 10 |
import java.util.Iterator; |
| 11 |
import java.util.List; |
| 12 |
import java.util.Map; |
| 13 |
import java.util.Objects; |
| 14 |
import java.util.concurrent.atomic.AtomicReference; |
| 15 |
import java.util.concurrent.atomic.AtomicReferenceArray; |
| 16 |
import org.h2.engine.IsolationLevel; |
| 17 |
import org.h2.mvstore.Cursor; |
| 18 |
import org.h2.mvstore.DataUtils; |
| 19 |
import org.h2.mvstore.MVMap; |
| 20 |
import org.h2.mvstore.MVStore; |
| 21 |
import org.h2.mvstore.RootReference; |
| 22 |
import org.h2.mvstore.rtree.MVRTreeMap; |
| 23 |
import org.h2.mvstore.rtree.SpatialDataType; |
| 24 |
import org.h2.mvstore.type.DataType; |
| 25 |
import org.h2.mvstore.type.LongDataType; |
| 26 |
import org.h2.mvstore.type.MetaType; |
| 27 |
import org.h2.mvstore.type.ObjectDataType; |
| 28 |
import org.h2.mvstore.type.StringDataType; |
| 29 |
import org.h2.util.StringUtils; |
| 30 |
import org.h2.value.VersionedValue; |
| 31 |
|
| 32 |
/** |
| 33 |
* A store that supports concurrent MVCC read-committed transactions. |
| 34 |
*/ |
| 35 |
public class TransactionStore { |
| 36 |
|
| 37 |
/** |
| 38 |
* The store. |
| 39 |
*/ |
| 40 |
final MVStore store; |
| 41 |
|
| 42 |
/** |
| 43 |
* Default blocked transaction timeout |
| 44 |
*/ |
| 45 |
final int timeoutMillis; |
| 46 |
|
| 47 |
/** |
| 48 |
* The persisted map of prepared transactions. |
| 49 |
* Key: transactionId, value: [ status, name ]. |
| 50 |
*/ |
| 51 |
private final MVMap<Integer, Object[]> preparedTransactions; |
| 52 |
|
| 53 |
private final MVMap<String, DataType<?>> typeRegistry; |
| 54 |
|
| 55 |
/** |
| 56 |
* Undo logs. |
| 57 |
* <p> |
| 58 |
* If the first entry for a transaction doesn't have a logId |
| 59 |
* of 0, then the transaction is partially committed (which means rollback |
| 60 |
* is not possible). Log entries are written before the data is changed |
| 61 |
* (write-ahead). |
| 62 |
* <p> |
| 63 |
* Key: opId, value: [ mapId, key, oldValue ]. |
| 64 |
*/ |
| 65 |
@SuppressWarnings("unchecked") |
| 66 |
final MVMap<Long,Record<?,?>>[] undoLogs = new MVMap[MAX_OPEN_TRANSACTIONS]; |
| 67 |
private final MVMap.Builder<Long, Record<?,?>> undoLogBuilder; |
| 68 |
|
| 69 |
private final DataType<?> dataType; |
| 70 |
|
| 71 |
/** |
| 72 |
* This BitSet is used as vacancy indicator for transaction slots in transactions[]. |
| 73 |
* It provides easy way to find first unoccupied slot, and also allows for copy-on-write |
| 74 |
* non-blocking updates. |
| 75 |
*/ |
| 76 |
final AtomicReference<VersionedBitSet> openTransactions = new AtomicReference<>(new VersionedBitSet()); |
| 77 |
|
| 78 |
/** |
| 79 |
* This is intended to be the source of ultimate truth about transaction being committed. |
| 80 |
* Once bit is set, corresponding transaction is logically committed, |
| 81 |
* although it might be plenty of "uncommitted" entries in various maps |
| 82 |
* and undo record are still around. |
| 83 |
* Nevertheless, all of those should be considered by other transactions as committed. |
| 84 |
*/ |
| 85 |
final AtomicReference<BitSet> committingTransactions = new AtomicReference<>(new BitSet()); |
| 86 |
|
| 87 |
private boolean init; |
| 88 |
|
| 89 |
/** |
| 90 |
* Soft limit on the number of concurrently opened transactions. |
| 91 |
* Not really needed but used by some test. |
| 92 |
*/ |
| 93 |
private int maxTransactionId = MAX_OPEN_TRANSACTIONS; |
| 94 |
|
| 95 |
/** |
| 96 |
* Array holding all open transaction objects. |
| 97 |
* Position in array is "transaction id". |
| 98 |
* VolatileReferenceArray would do the job here, but there is no such thing in Java yet |
| 99 |
*/ |
| 100 |
private final AtomicReferenceArray<Transaction> transactions = |
| 101 |
new AtomicReferenceArray<>(MAX_OPEN_TRANSACTIONS + 1); |
| 102 |
|
| 103 |
private static final String TYPE_REGISTRY_NAME = "_"; |
| 104 |
|
| 105 |
/** |
| 106 |
* The prefix for undo log entries. |
| 107 |
*/ |
| 108 |
public static final String UNDO_LOG_NAME_PREFIX = "undoLog"; |
| 109 |
|
| 110 |
// must come before open in lexicographical order |
| 111 |
private static final char UNDO_LOG_COMMITTED = '-'; |
| 112 |
|
| 113 |
private static final char UNDO_LOG_OPEN = '.'; |
| 114 |
|
| 115 |
/** |
| 116 |
* Hard limit on the number of concurrently opened transactions |
| 117 |
*/ |
| 118 |
// TODO: introduce constructor parameter instead of a static field, driven by URL parameter |
| 119 |
private static final int MAX_OPEN_TRANSACTIONS = 65535; |
| 120 |
|
| 121 |
/** |
| 122 |
* Generate a string used to name undo log map for a specific transaction. |
| 123 |
* This name will contain transaction id. |
| 124 |
* |
| 125 |
* @param transactionId of the corresponding transaction |
| 126 |
* @return undo log name |
| 127 |
*/ |
| 128 |
private static String getUndoLogName(int transactionId) { |
| 129 |
return transactionId > 0 ? UNDO_LOG_NAME_PREFIX + UNDO_LOG_OPEN + transactionId |
| 130 |
: UNDO_LOG_NAME_PREFIX + UNDO_LOG_OPEN; |
| 131 |
} |
| 132 |
|
| 133 |
/** |
| 134 |
* Create a new transaction store. |
| 135 |
* |
| 136 |
* @param store the store |
| 137 |
*/ |
| 138 |
public TransactionStore(MVStore store) { |
| 139 |
this(store, new ObjectDataType()); |
| 140 |
} |
| 141 |
|
| 142 |
public TransactionStore(MVStore store, DataType<?> dataType) { |
| 143 |
this(store, new MetaType<>(null, store.backgroundExceptionHandler), dataType, 0); |
| 144 |
} |
| 145 |
|
| 146 |
/** |
| 147 |
* Create a new transaction store. |
| 148 |
* @param store the store |
| 149 |
* @param metaDataType the data type for type registry map values |
| 150 |
* @param dataType default data type for map keys and values |
| 151 |
* @param timeoutMillis lock acquisition timeout in milliseconds, 0 means no wait |
| 152 |
*/ |
| 153 |
public TransactionStore(MVStore store, MetaType<?> metaDataType, DataType<?> dataType, int timeoutMillis) { |
| 154 |
this.store = store; |
| 155 |
this.dataType = dataType; |
| 156 |
this.timeoutMillis = timeoutMillis; |
| 157 |
this.typeRegistry = openTypeRegistry(store, metaDataType); |
| 158 |
this.preparedTransactions = store.openMap("openTransactions", new MVMap.Builder<>()); |
| 159 |
this.undoLogBuilder = createUndoLogBuilder(); |
| 160 |
} |
| 161 |
|
| 162 |
@SuppressWarnings({"unchecked","rawtypes"}) |
| 163 |
MVMap.Builder<Long,Record<?, ?>> createUndoLogBuilder() { |
| 164 |
return new MVMap.Builder<Long,Record<?,?>>() |
| 165 |
.singleWriter() |
| 166 |
.keyType(LongDataType.INSTANCE) |
| 167 |
.valueType(new Record.Type(this)); |
| 168 |
} |
| 169 |
|
| 170 |
private static MVMap<String, DataType<?>> openTypeRegistry(MVStore store, MetaType<?> metaDataType) { |
| 171 |
MVMap.Builder<String, DataType<?>> typeRegistryBuilder = |
| 172 |
new MVMap.Builder<String, DataType<?>>() |
| 173 |
.keyType(StringDataType.INSTANCE) |
| 174 |
.valueType(metaDataType); |
| 175 |
return store.openMap(TYPE_REGISTRY_NAME, typeRegistryBuilder); |
| 176 |
} |
| 177 |
|
| 178 |
/** |
| 179 |
* Initialize the store without any RollbackListener. |
| 180 |
* @see #init(RollbackListener) |
| 181 |
*/ |
| 182 |
public void init() { |
| 183 |
init(ROLLBACK_LISTENER_NONE); |
| 184 |
} |
| 185 |
|
| 186 |
/** |
| 187 |
* Initialize the store. This is needed before a transaction can be opened. |
| 188 |
* If the transaction store is corrupt, this method can throw an exception, |
| 189 |
* in which case the store can only be used for reading. |
| 190 |
* |
| 191 |
* @param listener to notify about transaction rollback |
| 192 |
*/ |
| 193 |
public void init(RollbackListener listener) { |
| 194 |
if (!init) { |
| 195 |
for (String mapName : store.getMapNames()) { |
| 196 |
if (mapName.startsWith(UNDO_LOG_NAME_PREFIX)) { |
| 197 |
// Unexpectedly short name may be encountered upon upgrade from older version |
| 198 |
// where undo log was persisted as a single map, remove it. |
| 199 |
if (mapName.length() > UNDO_LOG_NAME_PREFIX.length()) { |
| 200 |
// make a decision about tx status based on a log name |
| 201 |
// to handle upgrade from a previous versions |
| 202 |
boolean committed = mapName.charAt(UNDO_LOG_NAME_PREFIX.length()) == UNDO_LOG_COMMITTED; |
| 203 |
if (store.hasData(mapName)) { |
| 204 |
int transactionId = StringUtils.parseUInt31(mapName, UNDO_LOG_NAME_PREFIX.length() + 1, |
| 205 |
mapName.length()); |
| 206 |
VersionedBitSet openTxBitSet = openTransactions.get(); |
| 207 |
if (!openTxBitSet.get(transactionId)) { |
| 208 |
Object[] data = preparedTransactions.get(transactionId); |
| 209 |
int status; |
| 210 |
String name; |
| 211 |
if (data == null) { |
| 212 |
status = Transaction.STATUS_OPEN; |
| 213 |
name = null; |
| 214 |
} else { |
| 215 |
status = (Integer) data[0]; |
| 216 |
name = (String) data[1]; |
| 217 |
} |
| 218 |
MVMap<Long, Record<?,?>> undoLog = store.openMap(mapName, undoLogBuilder); |
| 219 |
undoLogs[transactionId] = undoLog; |
| 220 |
Long lastUndoKey = undoLog.lastKey(); |
| 221 |
assert lastUndoKey != null; |
| 222 |
assert getTransactionId(lastUndoKey) == transactionId; |
| 223 |
long logId = getLogId(lastUndoKey) + 1; |
| 224 |
if (committed) { |
| 225 |
// give it a proper name and used marker record instead |
| 226 |
store.renameMap(undoLog, getUndoLogName(transactionId)); |
| 227 |
markUndoLogAsCommitted(transactionId); |
| 228 |
} else { |
| 229 |
committed = logId > LOG_ID_MASK; |
| 230 |
} |
| 231 |
if (committed) { |
| 232 |
status = Transaction.STATUS_COMMITTED; |
| 233 |
lastUndoKey = undoLog.lowerKey(lastUndoKey); |
| 234 |
assert lastUndoKey == null || getTransactionId(lastUndoKey) == transactionId; |
| 235 |
logId = lastUndoKey == null ? 0 : getLogId(lastUndoKey) + 1; |
| 236 |
} |
| 237 |
registerTransaction(transactionId, status, name, logId, timeoutMillis, 0, |
| 238 |
IsolationLevel.READ_COMMITTED, listener); |
| 239 |
continue; |
| 240 |
} |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
if (!store.isReadOnly()) { |
| 245 |
store.removeMap(mapName); |
| 246 |
} |
| 247 |
} |
| 248 |
} |
| 249 |
init = true; |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
private void markUndoLogAsCommitted(int transactionId) { |
| 254 |
addUndoLogRecord(transactionId, LOG_ID_MASK, Record.COMMIT_MARKER); |
| 255 |
} |
| 256 |
|
| 257 |
/** |
| 258 |
* Commit all transactions that are in the committed state, and |
| 259 |
* rollback all open transactions. |
| 260 |
*/ |
| 261 |
public void endLeftoverTransactions() { |
| 262 |
List<Transaction> list = getOpenTransactions(); |
| 263 |
for (Transaction t : list) { |
| 264 |
int status = t.getStatus(); |
| 265 |
if (status == Transaction.STATUS_COMMITTED) { |
| 266 |
t.commit(); |
| 267 |
} else if (status != Transaction.STATUS_PREPARED) { |
| 268 |
t.rollback(); |
| 269 |
} |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
int getMaxTransactionId() { |
| 274 |
return maxTransactionId; |
| 275 |
} |
| 276 |
|
| 277 |
/** |
| 278 |
* Set the maximum transaction id, after which ids are re-used. If the old |
| 279 |
* transaction is still in use when re-using an old id, the new transaction |
| 280 |
* fails. |
| 281 |
* |
| 282 |
* @param max the maximum id |
| 283 |
*/ |
| 284 |
public void setMaxTransactionId(int max) { |
| 285 |
DataUtils.checkArgument(max <= MAX_OPEN_TRANSACTIONS, |
| 286 |
"Concurrent transactions limit is too high: {0}", max); |
| 287 |
this.maxTransactionId = max; |
| 288 |
} |
| 289 |
|
| 290 |
/** |
| 291 |
* Check whether a given map exists. |
| 292 |
* |
| 293 |
* @param name the map name |
| 294 |
* @return true if it exists |
| 295 |
*/ |
| 296 |
public boolean hasMap(String name) { |
| 297 |
return store.hasMap(name); |
| 298 |
} |
| 299 |
|
| 300 |
private static final int LOG_ID_BITS = Transaction.LOG_ID_BITS; |
| 301 |
private static final long LOG_ID_MASK = (1L << LOG_ID_BITS) - 1; |
| 302 |
|
| 303 |
/** |
| 304 |
* Combine the transaction id and the log id to an operation id. |
| 305 |
* |
| 306 |
* @param transactionId the transaction id |
| 307 |
* @param logId the log id |
| 308 |
* @return the operation id |
| 309 |
*/ |
| 310 |
static long getOperationId(int transactionId, long logId) { |
| 311 |
DataUtils.checkArgument(transactionId >= 0 && transactionId < (1 << (64 - LOG_ID_BITS)), |
| 312 |
"Transaction id out of range: {0}", transactionId); |
| 313 |
DataUtils.checkArgument(logId >= 0 && logId <= LOG_ID_MASK, |
| 314 |
"Transaction log id out of range: {0}", logId); |
| 315 |
return ((long) transactionId << LOG_ID_BITS) | logId; |
| 316 |
} |
| 317 |
|
| 318 |
/** |
| 319 |
* Get the transaction id for the given operation id. |
| 320 |
* |
| 321 |
* @param operationId the operation id |
| 322 |
* @return the transaction id |
| 323 |
*/ |
| 324 |
static int getTransactionId(long operationId) { |
| 325 |
return (int) (operationId >>> LOG_ID_BITS); |
| 326 |
} |
| 327 |
|
| 328 |
/** |
| 329 |
* Get the log id for the given operation id. |
| 330 |
* |
| 331 |
* @param operationId the operation id |
| 332 |
* @return the log id |
| 333 |
*/ |
| 334 |
static long getLogId(long operationId) { |
| 335 |
return operationId & LOG_ID_MASK; |
| 336 |
} |
| 337 |
|
| 338 |
/** |
| 339 |
* Get the list of unclosed transactions that have pending writes. |
| 340 |
* |
| 341 |
* @return the list of transactions (sorted by id) |
| 342 |
*/ |
| 343 |
public List<Transaction> getOpenTransactions() { |
| 344 |
if(!init) { |
| 345 |
init(); |
| 346 |
} |
| 347 |
ArrayList<Transaction> list = new ArrayList<>(); |
| 348 |
int transactionId = 0; |
| 349 |
BitSet bitSet = openTransactions.get(); |
| 350 |
while((transactionId = bitSet.nextSetBit(transactionId + 1)) > 0) { |
| 351 |
Transaction transaction = getTransaction(transactionId); |
| 352 |
if(transaction != null) { |
| 353 |
if(transaction.getStatus() != Transaction.STATUS_CLOSED) { |
| 354 |
list.add(transaction); |
| 355 |
} |
| 356 |
} |
| 357 |
} |
| 358 |
return list; |
| 359 |
} |
| 360 |
|
| 361 |
/** |
| 362 |
* Close the transaction store. |
| 363 |
*/ |
| 364 |
public synchronized void close() { |
| 365 |
store.commit(); |
| 366 |
} |
| 367 |
|
| 368 |
/** |
| 369 |
* Begin a new transaction. |
| 370 |
* |
| 371 |
* @return the transaction |
| 372 |
*/ |
| 373 |
public Transaction begin() { |
| 374 |
return begin(ROLLBACK_LISTENER_NONE, timeoutMillis, 0, IsolationLevel.READ_COMMITTED); |
| 375 |
} |
| 376 |
|
| 377 |
/** |
| 378 |
* Begin a new transaction. |
| 379 |
* @param listener to be notified in case of a rollback |
| 380 |
* @param timeoutMillis to wait for a blocking transaction |
| 381 |
* @param ownerId of the owner (Session?) to be reported by getBlockerId |
| 382 |
* @param isolationLevel of new transaction |
| 383 |
* @return the transaction |
| 384 |
*/ |
| 385 |
public Transaction begin(RollbackListener listener, int timeoutMillis, int ownerId, |
| 386 |
IsolationLevel isolationLevel) { |
| 387 |
Transaction transaction = registerTransaction(0, Transaction.STATUS_OPEN, null, 0, |
| 388 |
timeoutMillis, ownerId, isolationLevel, listener); |
| 389 |
return transaction; |
| 390 |
} |
| 391 |
|
| 392 |
private Transaction registerTransaction(int txId, int status, String name, long logId, |
| 393 |
int timeoutMillis, int ownerId, |
| 394 |
IsolationLevel isolationLevel, RollbackListener listener) { |
| 395 |
int transactionId; |
| 396 |
long sequenceNo; |
| 397 |
boolean success; |
| 398 |
do { |
| 399 |
VersionedBitSet original = openTransactions.get(); |
| 400 |
if (txId == 0) { |
| 401 |
transactionId = original.nextClearBit(1); |
| 402 |
} else { |
| 403 |
transactionId = txId; |
| 404 |
assert !original.get(transactionId); |
| 405 |
} |
| 406 |
if (transactionId > maxTransactionId) { |
| 407 |
throw DataUtils.newMVStoreException( |
| 408 |
DataUtils.ERROR_TOO_MANY_OPEN_TRANSACTIONS, |
| 409 |
"There are {0} open transactions", |
| 410 |
transactionId - 1); |
| 411 |
} |
| 412 |
VersionedBitSet clone = original.clone(); |
| 413 |
clone.set(transactionId); |
| 414 |
sequenceNo = clone.getVersion() + 1; |
| 415 |
clone.setVersion(sequenceNo); |
| 416 |
success = openTransactions.compareAndSet(original, clone); |
| 417 |
} while(!success); |
| 418 |
|
| 419 |
Transaction transaction = new Transaction(this, transactionId, sequenceNo, status, name, logId, |
| 420 |
timeoutMillis, ownerId, isolationLevel, listener); |
| 421 |
|
| 422 |
assert transactions.get(transactionId) == null; |
| 423 |
transactions.set(transactionId, transaction); |
| 424 |
|
| 425 |
if (undoLogs[transactionId] == null) { |
| 426 |
String undoName = getUndoLogName(transactionId); |
| 427 |
MVMap<Long,Record<?,?>> undoLog = store.openMap(undoName, undoLogBuilder); |
| 428 |
undoLogs[transactionId] = undoLog; |
| 429 |
} |
| 430 |
return transaction; |
| 431 |
} |
| 432 |
|
| 433 |
/** |
| 434 |
* Store a transaction. |
| 435 |
* |
| 436 |
* @param t the transaction |
| 437 |
*/ |
| 438 |
void storeTransaction(Transaction t) { |
| 439 |
if (t.getStatus() == Transaction.STATUS_PREPARED || |
| 440 |
t.getName() != null) { |
| 441 |
Object[] v = { t.getStatus(), t.getName() }; |
| 442 |
preparedTransactions.put(t.getId(), v); |
| 443 |
t.wasStored = true; |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
/** |
| 448 |
* Add an undo log entry. |
| 449 |
* |
| 450 |
* @param transactionId id of the transaction |
| 451 |
* @param logId sequential number of the log record within transaction |
| 452 |
* @param record Record(mapId, key, previousValue) to add |
| 453 |
* @return key for the added record |
| 454 |
*/ |
| 455 |
long addUndoLogRecord(int transactionId, long logId, Record<?,?> record) { |
| 456 |
MVMap<Long, Record<?,?>> undoLog = undoLogs[transactionId]; |
| 457 |
long undoKey = getOperationId(transactionId, logId); |
| 458 |
if (logId == 0 && !undoLog.isEmpty()) { |
| 459 |
throw DataUtils.newMVStoreException( |
| 460 |
DataUtils.ERROR_TOO_MANY_OPEN_TRANSACTIONS, |
| 461 |
"An old transaction with the same id " + |
| 462 |
"is still open: {0}", |
| 463 |
transactionId); |
| 464 |
} |
| 465 |
undoLog.append(undoKey, record); |
| 466 |
return undoKey; |
| 467 |
} |
| 468 |
|
| 469 |
/** |
| 470 |
* Remove an undo log entry. |
| 471 |
* @param transactionId id of the transaction |
| 472 |
*/ |
| 473 |
void removeUndoLogRecord(int transactionId) { |
| 474 |
undoLogs[transactionId].trimLast(); |
| 475 |
} |
| 476 |
|
| 477 |
/** |
| 478 |
* Remove the given map. |
| 479 |
* |
| 480 |
* @param map the map |
| 481 |
*/ |
| 482 |
void removeMap(TransactionMap<?,?> map) { |
| 483 |
store.removeMap(map.map); |
| 484 |
} |
| 485 |
|
| 486 |
/** |
| 487 |
* Commit a transaction. |
| 488 |
* @param t transaction to commit |
| 489 |
* @param recovery if called during initial transaction recovery procedure |
| 490 |
* therefore undo log is stored under "committed" name already |
| 491 |
*/ |
| 492 |
void commit(Transaction t, boolean recovery) { |
| 493 |
if (!store.isClosed()) { |
| 494 |
int transactionId = t.transactionId; |
| 495 |
// First, mark log as "committed". |
| 496 |
// It does not change the way this transaction is treated by others, |
| 497 |
// but preserves fact of commit in case of abrupt termination. |
| 498 |
MVMap<Long,Record<?,?>> undoLog = undoLogs[transactionId]; |
| 499 |
Cursor<Long,Record<?,?>> cursor; |
| 500 |
if(recovery) { |
| 501 |
removeUndoLogRecord(transactionId); |
| 502 |
cursor = undoLog.cursor(null); |
| 503 |
} else { |
| 504 |
cursor = undoLog.cursor(null); |
| 505 |
markUndoLogAsCommitted(transactionId); |
| 506 |
} |
| 507 |
|
| 508 |
// this is an atomic action that causes all changes |
| 509 |
// made by this transaction, to be considered as "committed" |
| 510 |
flipCommittingTransactionsBit(transactionId, true); |
| 511 |
|
| 512 |
CommitDecisionMaker<Object> commitDecisionMaker = new CommitDecisionMaker<>(); |
| 513 |
try { |
| 514 |
while (cursor.hasNext()) { |
| 515 |
Long undoKey = cursor.next(); |
| 516 |
Record<?,?> op = cursor.getValue(); |
| 517 |
int mapId = op.mapId; |
| 518 |
MVMap<Object, VersionedValue<Object>> map = openMap(mapId); |
| 519 |
if (map != null && !map.isClosed()) { // might be null if map was removed later |
| 520 |
Object key = op.key; |
| 521 |
commitDecisionMaker.setUndoKey(undoKey); |
| 522 |
// second parameter (value) is not really |
| 523 |
// used by CommitDecisionMaker |
| 524 |
map.operate(key, null, commitDecisionMaker); |
| 525 |
} |
| 526 |
} |
| 527 |
} finally { |
| 528 |
try { |
| 529 |
undoLog.clear(); |
| 530 |
} finally { |
| 531 |
flipCommittingTransactionsBit(transactionId, false); |
| 532 |
} |
| 533 |
} |
| 534 |
} |
| 535 |
} |
| 536 |
|
| 537 |
private void flipCommittingTransactionsBit(int transactionId, boolean flag) { |
| 538 |
boolean success; |
| 539 |
do { |
| 540 |
BitSet original = committingTransactions.get(); |
| 541 |
assert original.get(transactionId) != flag : flag ? "Double commit" : "Mysterious bit's disappearance"; |
| 542 |
BitSet clone = (BitSet) original.clone(); |
| 543 |
clone.set(transactionId, flag); |
| 544 |
success = committingTransactions.compareAndSet(original, clone); |
| 545 |
} while(!success); |
| 546 |
} |
| 547 |
|
| 548 |
<K,V> MVMap<K, VersionedValue<V>> openVersionedMap(String name, DataType<K> keyType, DataType<V> valueType) { |
| 549 |
VersionedValueType<V,?> vt = valueType == null ? null : new VersionedValueType<>(valueType); |
| 550 |
return openMap(name, keyType, vt); |
| 551 |
} |
| 552 |
|
| 553 |
/** |
| 554 |
* Open the map with the given name. |
| 555 |
* |
| 556 |
* @param <K> the key type |
| 557 |
* @param <V> the value type |
| 558 |
* @param name the map name |
| 559 |
* @param keyType the key type |
| 560 |
* @param valueType the value type |
| 561 |
* @return the map |
| 562 |
*/ |
| 563 |
public <K,V> MVMap<K, V> openMap(String name, DataType<K> keyType, DataType<V> valueType) { |
| 564 |
return store.openMap(name, new TxMapBuilder<K, V>(typeRegistry, dataType) |
| 565 |
.keyType(keyType).valueType(valueType)); |
| 566 |
} |
| 567 |
|
| 568 |
/** |
| 569 |
* Open the map with the given id. |
| 570 |
* |
| 571 |
* @param <K> key type |
| 572 |
* @param <V> value type |
| 573 |
* |
| 574 |
* @param mapId the id |
| 575 |
* @return the map |
| 576 |
*/ |
| 577 |
<K,V> MVMap<K, VersionedValue<V>> openMap(int mapId) { |
| 578 |
MVMap<K, VersionedValue<V>> map = store.getMap(mapId); |
| 579 |
if (map == null) { |
| 580 |
String mapName = store.getMapName(mapId); |
| 581 |
if (mapName == null) { |
| 582 |
// the map was removed later on |
| 583 |
return null; |
| 584 |
} |
| 585 |
MVMap.Builder<K, VersionedValue<V>> txMapBuilder = new TxMapBuilder<>(typeRegistry, dataType); |
| 586 |
map = store.openMap(mapId, txMapBuilder); |
| 587 |
} |
| 588 |
return map; |
| 589 |
} |
| 590 |
|
| 591 |
<K,V> MVMap<K,VersionedValue<V>> getMap(int mapId) { |
| 592 |
MVMap<K, VersionedValue<V>> map = store.getMap(mapId); |
| 593 |
if (map == null && !init) { |
| 594 |
map = openMap(mapId); |
| 595 |
} |
| 596 |
assert map != null : "map with id " + mapId + " is missing" + |
| 597 |
(init ? "" : " during initialization"); |
| 598 |
return map; |
| 599 |
} |
| 600 |
|
| 601 |
/** |
| 602 |
* End this transaction. Change status to CLOSED and vacate transaction slot. |
| 603 |
* Will try to commit MVStore if autocommitDelay is 0 or if database is idle |
| 604 |
* and amount of unsaved changes is sizable. |
| 605 |
* |
| 606 |
* @param t the transaction |
| 607 |
* @param hasChanges true if transaction has done any updates |
| 608 |
* (even if they are fully rolled back), |
| 609 |
* false if it just performed a data access |
| 610 |
*/ |
| 611 |
void endTransaction(Transaction t, boolean hasChanges) { |
| 612 |
t.closeIt(); |
| 613 |
int txId = t.transactionId; |
| 614 |
transactions.set(txId, null); |
| 615 |
|
| 616 |
boolean success; |
| 617 |
do { |
| 618 |
VersionedBitSet original = openTransactions.get(); |
| 619 |
assert original.get(txId); |
| 620 |
VersionedBitSet clone = original.clone(); |
| 621 |
clone.clear(txId); |
| 622 |
success = openTransactions.compareAndSet(original, clone); |
| 623 |
} while(!success); |
| 624 |
|
| 625 |
if (hasChanges) { |
| 626 |
boolean wasStored = t.wasStored; |
| 627 |
if (wasStored && !preparedTransactions.isClosed()) { |
| 628 |
preparedTransactions.remove(txId); |
| 629 |
} |
| 630 |
|
| 631 |
if (store.isVersioningRequired()) { |
| 632 |
if (wasStored || store.getAutoCommitDelay() == 0) { |
| 633 |
store.commit(); |
| 634 |
} else { |
| 635 |
if (isUndoEmpty()) { |
| 636 |
// to avoid having to store the transaction log, |
| 637 |
// if there is no open transaction, |
| 638 |
// and if there have been many changes, store them now |
| 639 |
int unsaved = store.getUnsavedMemory(); |
| 640 |
int max = store.getAutoCommitMemory(); |
| 641 |
// save at 3/4 capacity |
| 642 |
if (unsaved * 4 > max * 3) { |
| 643 |
store.tryCommit(); |
| 644 |
} |
| 645 |
} |
| 646 |
} |
| 647 |
} |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
/** |
| 652 |
* Get the root references (snapshots) for undo-log maps. |
| 653 |
* Those snapshots can potentially be used to optimize TransactionMap.size(). |
| 654 |
* |
| 655 |
* @return the array of root references or null if snapshotting is not possible |
| 656 |
*/ |
| 657 |
RootReference<Long,Record<?,?>>[] collectUndoLogRootReferences() { |
| 658 |
BitSet opentransactions = openTransactions.get(); |
| 659 |
@SuppressWarnings("unchecked") |
| 660 |
RootReference<Long,Record<?,?>>[] undoLogRootReferences = new RootReference[opentransactions.length()]; |
| 661 |
for (int i = opentransactions.nextSetBit(0); i >= 0; i = opentransactions.nextSetBit(i+1)) { |
| 662 |
MVMap<Long,Record<?,?>> undoLog = undoLogs[i]; |
| 663 |
if (undoLog != null) { |
| 664 |
RootReference<Long,Record<?,?>> rootReference = undoLog.getRoot(); |
| 665 |
if (rootReference.needFlush()) { |
| 666 |
// abort attempt to collect snapshots for all undo logs |
| 667 |
// because map's append buffer can't be flushed from a non-owning thread |
| 668 |
return null; |
| 669 |
} |
| 670 |
undoLogRootReferences[i] = rootReference; |
| 671 |
} |
| 672 |
} |
| 673 |
return undoLogRootReferences; |
| 674 |
} |
| 675 |
|
| 676 |
/** |
| 677 |
* Calculate the size for undo log entries. |
| 678 |
* |
| 679 |
* @param undoLogRootReferences the root references |
| 680 |
* @return the number of key-value pairs |
| 681 |
*/ |
| 682 |
static long calculateUndoLogsTotalSize(RootReference<Long,Record<?,?>>[] undoLogRootReferences) { |
| 683 |
long undoLogsTotalSize = 0; |
| 684 |
for (RootReference<Long,Record<?,?>> rootReference : undoLogRootReferences) { |
| 685 |
if (rootReference != null) { |
| 686 |
undoLogsTotalSize += rootReference.getTotalCount(); |
| 687 |
} |
| 688 |
} |
| 689 |
return undoLogsTotalSize; |
| 690 |
} |
| 691 |
|
| 692 |
private boolean isUndoEmpty() { |
| 693 |
BitSet openTrans = openTransactions.get(); |
| 694 |
for (int i = openTrans.nextSetBit(0); i >= 0; i = openTrans.nextSetBit(i + 1)) { |
| 695 |
MVMap<Long,Record<?,?>> undoLog = undoLogs[i]; |
| 696 |
if (undoLog != null && !undoLog.isEmpty()) { |
| 697 |
return false; |
| 698 |
} |
| 699 |
} |
| 700 |
return true; |
| 701 |
} |
| 702 |
|
| 703 |
/** |
| 704 |
* Get Transaction object for a transaction id. |
| 705 |
* |
| 706 |
* @param transactionId id for an open transaction |
| 707 |
* @return Transaction object. |
| 708 |
*/ |
| 709 |
Transaction getTransaction(int transactionId) { |
| 710 |
return transactions.get(transactionId); |
| 711 |
} |
| 712 |
|
| 713 |
/** |
| 714 |
* Rollback to an old savepoint. |
| 715 |
* |
| 716 |
* @param t the transaction |
| 717 |
* @param maxLogId the last log id |
| 718 |
* @param toLogId the log id to roll back to |
| 719 |
*/ |
| 720 |
void rollbackTo(Transaction t, long maxLogId, long toLogId) { |
| 721 |
int transactionId = t.getId(); |
| 722 |
MVMap<Long,Record<?,?>> undoLog = undoLogs[transactionId]; |
| 723 |
RollbackDecisionMaker decisionMaker = new RollbackDecisionMaker(this, transactionId, toLogId, t.listener); |
| 724 |
for (long logId = maxLogId - 1; logId >= toLogId; logId--) { |
| 725 |
Long undoKey = getOperationId(transactionId, logId); |
| 726 |
undoLog.operate(undoKey, null, decisionMaker); |
| 727 |
decisionMaker.reset(); |
| 728 |
} |
| 729 |
} |
| 730 |
|
| 731 |
/** |
| 732 |
* Get the changes of the given transaction, starting from the latest log id |
| 733 |
* back to the given log id. |
| 734 |
* |
| 735 |
* @param t the transaction |
| 736 |
* @param maxLogId the maximum log id |
| 737 |
* @param toLogId the minimum log id |
| 738 |
* @return the changes |
| 739 |
*/ |
| 740 |
Iterator<Change> getChanges(final Transaction t, final long maxLogId, |
| 741 |
final long toLogId) { |
| 742 |
|
| 743 |
final MVMap<Long,Record<?,?>> undoLog = undoLogs[t.getId()]; |
| 744 |
return new Iterator<Change>() { |
| 745 |
|
| 746 |
private long logId = maxLogId - 1; |
| 747 |
private Change current; |
| 748 |
|
| 749 |
private void fetchNext() { |
| 750 |
int transactionId = t.getId(); |
| 751 |
while (logId >= toLogId) { |
| 752 |
Long undoKey = getOperationId(transactionId, logId); |
| 753 |
Record<?,?> op = undoLog.get(undoKey); |
| 754 |
logId--; |
| 755 |
if (op == null) { |
| 756 |
// partially rolled back: load previous |
| 757 |
undoKey = undoLog.floorKey(undoKey); |
| 758 |
if (undoKey == null || getTransactionId(undoKey) != transactionId) { |
| 759 |
break; |
| 760 |
} |
| 761 |
logId = getLogId(undoKey); |
| 762 |
continue; |
| 763 |
} |
| 764 |
int mapId = op.mapId; |
| 765 |
MVMap<Object, VersionedValue<Object>> m = openMap(mapId); |
| 766 |
if (m != null) { // could be null if map was removed later on |
| 767 |
VersionedValue<?> oldValue = op.oldValue; |
| 768 |
current = new Change(m.getName(), op.key, |
| 769 |
oldValue == null ? null : oldValue.getCurrentValue()); |
| 770 |
return; |
| 771 |
} |
| 772 |
} |
| 773 |
current = null; |
| 774 |
} |
| 775 |
|
| 776 |
@Override |
| 777 |
public boolean hasNext() { |
| 778 |
if(current == null) { |
| 779 |
fetchNext(); |
| 780 |
} |
| 781 |
return current != null; |
| 782 |
} |
| 783 |
|
| 784 |
@Override |
| 785 |
public Change next() { |
| 786 |
if(!hasNext()) { |
| 787 |
throw DataUtils.newUnsupportedOperationException("no data"); |
| 788 |
} |
| 789 |
Change result = current; |
| 790 |
current = null; |
| 791 |
return result; |
| 792 |
} |
| 793 |
|
| 794 |
}; |
| 795 |
} |
| 796 |
|
| 797 |
/** |
| 798 |
* A change in a map. |
| 799 |
*/ |
| 800 |
public static class Change { |
| 801 |
|
| 802 |
/** |
| 803 |
* The name of the map where the change occurred. |
| 804 |
*/ |
| 805 |
public final String mapName; |
| 806 |
|
| 807 |
/** |
| 808 |
* The key. |
| 809 |
*/ |
| 810 |
public final Object key; |
| 811 |
|
| 812 |
/** |
| 813 |
* The value. |
| 814 |
*/ |
| 815 |
public final Object value; |
| 816 |
|
| 817 |
public Change(String mapName, Object key, Object value) { |
| 818 |
this.mapName = mapName; |
| 819 |
this.key = key; |
| 820 |
this.value = value; |
| 821 |
} |
| 822 |
} |
| 823 |
|
| 824 |
/** |
| 825 |
* This listener can be registered with the transaction to be notified of |
| 826 |
* every compensating change during transaction rollback. |
| 827 |
* Normally this is not required, if no external resources were modified, |
| 828 |
* because state of all transactional maps will be restored automatically. |
| 829 |
* Only state of external resources, possibly modified by triggers |
| 830 |
* need to be restored. |
| 831 |
*/ |
| 832 |
public interface RollbackListener { |
| 833 |
|
| 834 |
/** |
| 835 |
* Notified of a single map change (add/update/remove) |
| 836 |
* @param map modified |
| 837 |
* @param key of the modified entry |
| 838 |
* @param existingValue value in the map (null if delete is rolled back) |
| 839 |
* @param restoredValue value to be restored (null if add is rolled back) |
| 840 |
*/ |
| 841 |
void onRollback(MVMap<Object,VersionedValue<Object>> map, Object key, |
| 842 |
VersionedValue<Object> existingValue, VersionedValue<Object> restoredValue); |
| 843 |
} |
| 844 |
|
| 845 |
private static final RollbackListener ROLLBACK_LISTENER_NONE = (map, key, existingValue, restoredValue) -> {}; |
| 846 |
|
| 847 |
private static final class TxMapBuilder<K,V> extends MVMap.Builder<K,V> { |
| 848 |
|
| 849 |
private final MVMap<String, DataType<?>> typeRegistry; |
| 850 |
private final DataType defaultDataType; |
| 851 |
|
| 852 |
TxMapBuilder(MVMap<String, DataType<?>> typeRegistry, DataType<?> defaultDataType) { |
| 853 |
this.typeRegistry = typeRegistry; |
| 854 |
this.defaultDataType = defaultDataType; |
| 855 |
} |
| 856 |
|
| 857 |
private void registerDataType(DataType<?> dataType) { |
| 858 |
String key = getDataTypeRegistrationKey(dataType); |
| 859 |
DataType<?> registeredDataType = typeRegistry.putIfAbsent(key, dataType); |
| 860 |
if(registeredDataType != null) { |
| 861 |
// TODO: ensure type consistency |
| 862 |
} |
| 863 |
} |
| 864 |
|
| 865 |
static String getDataTypeRegistrationKey(DataType<?> dataType) { |
| 866 |
return Integer.toHexString(Objects.hashCode(dataType)); |
| 867 |
} |
| 868 |
|
| 869 |
@SuppressWarnings("unchecked") |
| 870 |
@Override |
| 871 |
public MVMap<K,V> create(MVStore store, Map<String, Object> config) { |
| 872 |
DataType<K> keyType = getKeyType(); |
| 873 |
if (keyType == null) { |
| 874 |
String keyTypeKey = (String) config.remove("key"); |
| 875 |
if (keyTypeKey != null) { |
| 876 |
keyType = (DataType<K>)typeRegistry.get(keyTypeKey); |
| 877 |
if (keyType == null) { |
| 878 |
throw DataUtils.newMVStoreException(DataUtils.ERROR_UNKNOWN_DATA_TYPE, |
| 879 |
"Data type with hash {0} can not be found", keyTypeKey); |
| 880 |
} |
| 881 |
setKeyType(keyType); |
| 882 |
} |
| 883 |
} else { |
| 884 |
registerDataType(keyType); |
| 885 |
} |
| 886 |
|
| 887 |
DataType<V> valueType = getValueType(); |
| 888 |
if (valueType == null) { |
| 889 |
String valueTypeKey = (String) config.remove("val"); |
| 890 |
if (valueTypeKey != null) { |
| 891 |
valueType = (DataType<V>)typeRegistry.get(valueTypeKey); |
| 892 |
if (valueType == null) { |
| 893 |
throw DataUtils.newMVStoreException(DataUtils.ERROR_UNKNOWN_DATA_TYPE, |
| 894 |
"Data type with hash {0} can not be found", valueTypeKey); |
| 895 |
} |
| 896 |
setValueType(valueType); |
| 897 |
} |
| 898 |
} else { |
| 899 |
registerDataType(valueType); |
| 900 |
} |
| 901 |
|
| 902 |
if (getKeyType() == null) { |
| 903 |
setKeyType(defaultDataType); |
| 904 |
registerDataType(getKeyType()); |
| 905 |
} |
| 906 |
if (getValueType() == null) { |
| 907 |
setValueType((DataType<? super V>) new VersionedValueType<V,Object>(defaultDataType)); |
| 908 |
registerDataType(getValueType()); |
| 909 |
} |
| 910 |
|
| 911 |
config.put("store", store); |
| 912 |
config.put("key", getKeyType()); |
| 913 |
config.put("val", getValueType()); |
| 914 |
return create(config); |
| 915 |
} |
| 916 |
|
| 917 |
@Override |
| 918 |
@SuppressWarnings("unchecked") |
| 919 |
protected MVMap<K,V> create(Map<String,Object> config) { |
| 920 |
if ("rtree".equals(config.get("type"))) { |
| 921 |
MVMap<K, V> map = (MVMap<K, V>) new MVRTreeMap<>(config, (SpatialDataType) getKeyType(), |
| 922 |
getValueType()); |
| 923 |
return map; |
| 924 |
} |
| 925 |
return new TMVMap<>(config, getKeyType(), getValueType()); |
| 926 |
} |
| 927 |
|
| 928 |
private static final class TMVMap<K,V> extends MVMap<K,V> { |
| 929 |
private final String type; |
| 930 |
|
| 931 |
TMVMap(Map<String, Object> config, DataType<K> keyType, DataType<V> valueType) { |
| 932 |
super(config, keyType, valueType); |
| 933 |
type = (String)config.get("type"); |
| 934 |
} |
| 935 |
|
| 936 |
private TMVMap(MVMap<K, V> source) { |
| 937 |
super(source); |
| 938 |
type = source.getType(); |
| 939 |
} |
| 940 |
|
| 941 |
@Override |
| 942 |
protected MVMap<K, V> cloneIt() { |
| 943 |
return new TMVMap<>(this); |
| 944 |
} |
| 945 |
|
| 946 |
@Override |
| 947 |
public String getType() { |
| 948 |
return type; |
| 949 |
} |
| 950 |
|
| 951 |
@Override |
| 952 |
protected String asString(String name) { |
| 953 |
StringBuilder buff = new StringBuilder(); |
| 954 |
buff.append(super.asString(name)); |
| 955 |
DataUtils.appendMap(buff, "key", getDataTypeRegistrationKey(getKeyType())); |
| 956 |
DataUtils.appendMap(buff, "val", getDataTypeRegistrationKey(getValueType())); |
| 957 |
return buff.toString(); |
| 958 |
} |
| 959 |
} |
| 960 |
} |
| 961 |
} |