Debian Codegraph @

src/main/org/h2/mvstore/tx/Transaction.java

raw
1 /*
2 * Copyright 2004-2019 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (http://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore.tx;
7
8 import org.h2.mvstore.DataUtils;
9 import org.h2.mvstore.MVMap;
10 import org.h2.mvstore.MVStore;
11 import org.h2.mvstore.type.DataType;
12 import org.h2.value.VersionedValue;
13 import java.util.Iterator;
14 import java.util.concurrent.atomic.AtomicLong;
15
16 /**
17 * A transaction.
18 */
19 public class Transaction {
20
21 /**
22 * The status of a closed transaction (committed or rolled back).
23 */
24 public static final int STATUS_CLOSED = 0;
25
26 /**
27 * The status of an open transaction.
28 */
29 public static final int STATUS_OPEN = 1;
30
31 /**
32 * The status of a prepared transaction.
33 */
34 public static final int STATUS_PREPARED = 2;
35
36 /**
37 * The status of a transaction that has been logically committed or rather
38 * marked as committed, because it might be still listed among prepared,
39 * if it was prepared for commit. Undo log entries might still exists for it
40 * and not all of it's changes within map's are re-written as committed yet.
41 * Nevertheless, those changes should be already viewed by other
42 * transactions as committed.
43 * This transaction's id can not be re-used until all of the above is completed
44 * and transaction is closed.
45 * A transactions can be observed in this state when the store was
46 * closed while the transaction was not closed yet.
47 * When opening a store, such transactions will automatically
48 * be processed and closed as committed.
49 */
50 public static final int STATUS_COMMITTED = 3;
51
52 /**
53 * The status of a transaction that currently in a process of rolling back
54 * to a savepoint.
55 */
56 private static final int STATUS_ROLLING_BACK = 4;
57
58 /**
59 * The status of a transaction that has been rolled back completely,
60 * but undo operations are not finished yet.
61 */
62 private static final int STATUS_ROLLED_BACK = 5;
63
64 private static final String[] STATUS_NAMES = {
65 "CLOSED", "OPEN", "PREPARED", "COMMITTED", "ROLLING_BACK", "ROLLED_BACK"
66 };
67 /**
68 * How many bits of the "operation id" we store in the transaction belong to the
69 * log id (the rest belong to the transaction id).
70 */
71 static final int LOG_ID_BITS = 40;
72 private static final int LOG_ID_BITS1 = LOG_ID_BITS + 1;
73 private static final long LOG_ID_LIMIT = 1L << LOG_ID_BITS;
74 private static final long LOG_ID_MASK = (1L << LOG_ID_BITS1) - 1;
75 private static final int STATUS_BITS = 4;
76 private static final int STATUS_MASK = (1 << STATUS_BITS) - 1;
77
78
79 /**
80 * The transaction store.
81 */
82 final TransactionStore store;
83
84 /**
85 * Listener for this transaction's rollback changes.
86 */
87 final TransactionStore.RollbackListener listener;
88
89 /**
90 * The transaction id.
91 * More appropriate name for this field would be "slotId"
92 */
93 final int transactionId;
94
95 /**
96 * This is really a transaction identity, because it's not re-used.
97 */
98 final long sequenceNum;
99
100 /*
101 * Transaction state is an atomic composite field:
102 * bit 45 : flag whether transaction had rollback(s)
103 * bits 44-41 : status
104 * bits 40 : overflow control bit, 1 indicates overflow
105 * bits 39-0 : log id of the last entry in the undo log map
106 */
107 private final AtomicLong statusAndLogId;
108
109 /**
110 * Reference to a counter for an earliest store version used by this transaction.
111 * Referenced version and all newer ones can not be discarded
112 * at least until this transaction ends.
113 */
114 private MVStore.TxCounter txCounter;
115
116 /**
117 * Transaction name.
118 */
119 private String name;
120
121 /**
122 * Indicates whether this transaction was stored in preparedTransactions map
123 */
124 boolean wasStored;
125
126 /**
127 * How long to wait for blocking transaction to commit or rollback.
128 */
129 final int timeoutMillis;
130
131 /**
132 * Identification of the owner of this transaction,
133 * usually the owner is a database session.
134 */
135 private final int ownerId;
136
137 /**
138 * Blocking transaction, if any
139 */
140 private volatile Transaction blockingTransaction;
141
142 /**
143 * Map on which this transaction is blocked.
144 */
145 private MVMap<?,VersionedValue> blockingMap;
146
147 /**
148 * Key in blockingMap on which this transaction is blocked.
149 */
150 private Object blockingKey;
151
152 /**
153 * Whether other transaction(s) are waiting for this to close.
154 */
155 private volatile boolean notificationRequested;
156
157
158 Transaction(TransactionStore store, int transactionId, long sequenceNum, int status,
159 String name, long logId, int timeoutMillis, int ownerId,
160 TransactionStore.RollbackListener listener) {
161 this.store = store;
162 this.transactionId = transactionId;
163 this.sequenceNum = sequenceNum;
164 this.statusAndLogId = new AtomicLong(composeState(status, logId, false));
165 this.name = name;
166 this.timeoutMillis = timeoutMillis;
167 this.ownerId = ownerId;
168 this.listener = listener;
169 }
170
171 public int getId() {
172 return transactionId;
173 }
174
175 public long getSequenceNum() {
176 return sequenceNum;
177 }
178
179 public int getStatus() {
180 return getStatus(statusAndLogId.get());
181 }
182
183 /**
184 * Changes transaction status to a specified value
185 * @param status to be set
186 * @return transaction state as it was before status change
187 */
188 private long setStatus(int status) {
189 while (true) {
190 long currentState = statusAndLogId.get();
191 long logId = getLogId(currentState);
192 int currentStatus = getStatus(currentState);
193 boolean valid;
194 switch (status) {
195 case STATUS_ROLLING_BACK:
196 valid = currentStatus == STATUS_OPEN;
197 break;
198 case STATUS_PREPARED:
199 valid = currentStatus == STATUS_OPEN;
200 break;
201 case STATUS_COMMITTED:
202 valid = currentStatus == STATUS_OPEN ||
203 currentStatus == STATUS_PREPARED ||
204 // this case is only possible if called
205 // from endLeftoverTransactions()
206 currentStatus == STATUS_COMMITTED;
207 break;
208 case STATUS_ROLLED_BACK:
209 valid = currentStatus == STATUS_OPEN ||
210 currentStatus == STATUS_PREPARED;
211 break;
212 case STATUS_CLOSED:
213 valid = currentStatus == STATUS_COMMITTED ||
214 currentStatus == STATUS_ROLLED_BACK;
215 break;
216 case STATUS_OPEN:
217 default:
218 valid = false;
219 break;
220 }
221 if (!valid) {
222 throw DataUtils.newIllegalStateException(
223 DataUtils.ERROR_TRANSACTION_ILLEGAL_STATE,
224 "Transaction was illegally transitioned from {0} to {1}",
225 STATUS_NAMES[currentStatus], STATUS_NAMES[status]);
226 }
227 long newState = composeState(status, logId, hasRollback(currentState));
228 if (statusAndLogId.compareAndSet(currentState, newState)) {
229 return currentState;
230 }
231 }
232 }
233
234 /**
235 * Determine if any database changes were made as part of this transaction.
236 *
237 * @return true if there are changes to commit, false otherwise
238 */
239 public boolean hasChanges() {
240 return hasChanges(statusAndLogId.get());
241 }
242
243 public void setName(String name) {
244 checkNotClosed();
245 this.name = name;
246 store.storeTransaction(this);
247 }
248
249 public String getName() {
250 return name;
251 }
252
253 public int getBlockerId() {
254 Transaction blocker = this.blockingTransaction;
255 return blocker == null ? 0 : blocker.ownerId;
256 }
257
258 /**
259 * Create a new savepoint.
260 *
261 * @return the savepoint id
262 */
263 public long setSavepoint() {
264 return getLogId();
265 }
266
267 /**
268 * Mark an entry into a new SQL statement execution within this transaction.
269 */
270 public void markStatementStart() {
271 markStatementEnd();
272 txCounter = store.store.registerVersionUsage();
273 }
274
275 /**
276 * Mark an exit from SQL statement execution within this transaction.
277 */
278 public void markStatementEnd() {
279 MVStore.TxCounter counter = txCounter;
280 if(counter != null) {
281 txCounter = null;
282 store.store.deregisterVersionUsage(counter);
283 }
284 }
285
286 /**
287 * Add a log entry.
288 *
289 * @param mapId the map id
290 * @param key the key
291 * @param oldValue the old value
292 *
293 * @return key for the newly added undo log entry
294 */
295 long log(int mapId, Object key, VersionedValue oldValue) {
296 long currentState = statusAndLogId.getAndIncrement();
297 long logId = getLogId(currentState);
298 if (logId >= LOG_ID_LIMIT) {
299 throw DataUtils.newIllegalStateException(
300 DataUtils.ERROR_TRANSACTION_TOO_BIG,
301 "Transaction {0} has too many changes",
302 transactionId);
303 }
304 int currentStatus = getStatus(currentState);
305 checkOpen(currentStatus);
306 long undoKey = store.addUndoLogRecord(transactionId, logId, new Object[]{ mapId, key, oldValue });
307 return undoKey;
308 }
309
310 /**
311 * Remove the last log entry.
312 */
313 void logUndo() {
314 long currentState = statusAndLogId.decrementAndGet();
315 long logId = getLogId(currentState);
316 if (logId >= LOG_ID_LIMIT) {
317 throw DataUtils.newIllegalStateException(
318 DataUtils.ERROR_TRANSACTION_CORRUPT,
319 "Transaction {0} has internal error",
320 transactionId);
321 }
322 int currentStatus = getStatus(currentState);
323 checkOpen(currentStatus);
324 store.removeUndoLogRecord(transactionId);
325 }
326
327 /**
328 * Open a data map.
329 *
330 * @param <K> the key type
331 * @param <V> the value type
332 * @param name the name of the map
333 * @return the transaction map
334 */
335 public <K, V> TransactionMap<K, V> openMap(String name) {
336 return openMap(name, null, null);
337 }
338
339 /**
340 * Open the map to store the data.
341 *
342 * @param <K> the key type
343 * @param <V> the value type
344 * @param name the name of the map
345 * @param keyType the key data type
346 * @param valueType the value data type
347 * @return the transaction map
348 */
349 public <K, V> TransactionMap<K, V> openMap(String name,
350 DataType keyType, DataType valueType) {
351 MVMap<K, VersionedValue> map = store.openMap(name, keyType, valueType);
352 return openMap(map);
353 }
354
355 /**
356 * Open the transactional version of the given map.
357 *
358 * @param <K> the key type
359 * @param <V> the value type
360 * @param map the base map
361 * @return the transactional map
362 */
363 public <K, V> TransactionMap<K, V> openMap(MVMap<K, VersionedValue> map) {
364 checkNotClosed();
365 return new TransactionMap<>(this, map);
366 }
367
368 /**
369 * Prepare the transaction. Afterwards, the transaction can only be
370 * committed or completely rolled back.
371 */
372 public void prepare() {
373 setStatus(STATUS_PREPARED);
374 store.storeTransaction(this);
375 }
376
377 /**
378 * Commit the transaction. Afterwards, this transaction is closed.
379 */
380 public void commit() {
381 assert store.openTransactions.get().get(transactionId);
382 Throwable ex = null;
383 boolean hasChanges = false;
384 try {
385 long state = setStatus(STATUS_COMMITTED);
386 hasChanges = hasChanges(state);
387 int previousStatus = getStatus(state);
388 if (hasChanges) {
389 store.commit(this, previousStatus == STATUS_COMMITTED);
390 }
391 } catch (Throwable e) {
392 ex = e;
393 throw e;
394 } finally {
395 try {
396 store.endTransaction(this, hasChanges);
397 } catch (Throwable e) {
398 if (ex == null) {
399 throw e;
400 } else {
401 ex.addSuppressed(e);
402 }
403 }
404 }
405 }
406
407 /**
408 * Roll back to the given savepoint. This is only allowed if the
409 * transaction is open.
410 *
411 * @param savepointId the savepoint id
412 */
413 public void rollbackToSavepoint(long savepointId) {
414 long lastState = setStatus(STATUS_ROLLING_BACK);
415 long logId = getLogId(lastState);
416 boolean success;
417 try {
418 store.rollbackTo(this, logId, savepointId);
419 } finally {
420 if (notificationRequested) {
421 notifyAllWaitingTransactions();
422 }
423 long expectedState = composeState(STATUS_ROLLING_BACK, logId, hasRollback(lastState));
424 long newState = composeState(STATUS_OPEN, savepointId, true);
425 do {
426 success = statusAndLogId.compareAndSet(expectedState, newState);
427 } while (!success && statusAndLogId.get() == expectedState);
428 }
429 // this is moved outside of finally block to avert masking original exception, if any
430 if (!success) {
431 throw DataUtils.newIllegalStateException(
432 DataUtils.ERROR_TRANSACTION_ILLEGAL_STATE,
433 "Transaction {0} concurrently modified while rollback to savepoint was in progress",
434 transactionId);
435 }
436 }
437
438 /**
439 * Roll the transaction back. Afterwards, this transaction is closed.
440 */
441 public void rollback() {
442 Throwable ex = null;
443 try {
444 long lastState = setStatus(STATUS_ROLLED_BACK);
445 long logId = getLogId(lastState);
446 if (logId > 0) {
447 store.rollbackTo(this, logId, 0);
448 }
449 } catch (Throwable e) {
450 ex = e;
451 throw e;
452 } finally {
453 try {
454 store.endTransaction(this, true);
455 } catch (Throwable e) {
456 if (ex == null) {
457 throw e;
458 } else {
459 ex.addSuppressed(e);
460 }
461 }
462 }
463 }
464
465 /**
466 * Get the list of changes, starting with the latest change, up to the
467 * given savepoint (in reverse order than they occurred). The value of
468 * the change is the value before the change was applied.
469 *
470 * @param savepointId the savepoint id, 0 meaning the beginning of the
471 * transaction
472 * @return the changes
473 */
474 public Iterator<TransactionStore.Change> getChanges(long savepointId) {
475 return store.getChanges(this, getLogId(), savepointId);
476 }
477
478 private long getLogId() {
479 return getLogId(statusAndLogId.get());
480 }
481
482 /**
483 * Check whether this transaction is open.
484 */
485 private void checkOpen(int status) {
486 if (status != STATUS_OPEN) {
487 throw DataUtils.newIllegalStateException(
488 DataUtils.ERROR_TRANSACTION_ILLEGAL_STATE,
489 "Transaction {0} has status {1}, not OPEN", transactionId, STATUS_NAMES[status]);
490 }
491 }
492
493 /**
494 * Check whether this transaction is open or prepared.
495 */
496 private void checkNotClosed() {
497 if (getStatus() == STATUS_CLOSED) {
498 throw DataUtils.newIllegalStateException(
499 DataUtils.ERROR_CLOSED, "Transaction {0} is closed", transactionId);
500 }
501 }
502
503 /**
504 * Transition this transaction into a closed state.
505 */
506 void closeIt() {
507 long lastState = setStatus(STATUS_CLOSED);
508 store.store.deregisterVersionUsage(txCounter);
509 if((hasChanges(lastState) || hasRollback(lastState)) && notificationRequested) {
510 notifyAllWaitingTransactions();
511 }
512 }
513
514 private synchronized void notifyAllWaitingTransactions() {
515 notifyAll();
516 }
517
518 /**
519 * Make this transaction to wait for the specified transaction to be closed,
520 * because both of them try to modify the same map entry.
521 *
522 * @param toWaitFor transaction to wait for
523 * @param map containing blocking entry
524 * @param key of the blocking entry
525 * @return true if other transaction was closed and this one can proceed, false if timed out
526 */
527 public boolean waitFor(Transaction toWaitFor, MVMap<?,VersionedValue> map, Object key) {
528 blockingTransaction = toWaitFor;
529 blockingMap = map;
530 blockingKey = key;
531 if (isDeadlocked(toWaitFor)) {
532 StringBuilder details = new StringBuilder(
533 String.format("Transaction %d has been chosen as a deadlock victim. Details:%n", transactionId));
534 for (Transaction tx = toWaitFor, nextTx; (nextTx = tx.blockingTransaction) != null; tx = nextTx) {
535 details.append(String.format(
536 "Transaction %d attempts to update map <%s> entry with key <%s> modified by transaction %s%n",
537 tx.transactionId, tx.blockingMap.getName(), tx.blockingKey, tx.blockingTransaction));
538 if (nextTx == this) {
539 details.append(String.format(
540 "Transaction %d attempts to update map <%s> entry with key <%s>"
541 + " modified by transaction %s%n",
542 transactionId, blockingMap.getName(), blockingKey, toWaitFor));
543 if (isDeadlocked(toWaitFor)) {
544 throw DataUtils.newIllegalStateException(DataUtils.ERROR_TRANSACTIONS_DEADLOCK,
545 details.toString());
546 }
547 }
548 }
549 }
550
551 try {
552 return toWaitFor.waitForThisToEnd(timeoutMillis);
553 } finally {
554 blockingMap = null;
555 blockingKey = null;
556 blockingTransaction = null;
557 }
558 }
559
560 private boolean isDeadlocked(Transaction toWaitFor) {
561 for(Transaction tx = toWaitFor, nextTx;
562 (nextTx = tx.blockingTransaction) != null && tx.getStatus() == Transaction.STATUS_OPEN;
563 tx = nextTx) {
564 if (nextTx == this) {
565 return true;
566 }
567 }
568 return false;
569 }
570
571 private synchronized boolean waitForThisToEnd(int millis) {
572 long until = System.currentTimeMillis() + millis;
573 notificationRequested = true;
574 long state;
575 int status;
576 while((status = getStatus(state = statusAndLogId.get())) != STATUS_CLOSED
577 && status != STATUS_ROLLED_BACK && !hasRollback(state)) {
578 long dur = until - System.currentTimeMillis();
579 if(dur <= 0) {
580 return false;
581 }
582 try {
583 wait(dur);
584 } catch (InterruptedException ex) {
585 return false;
586 }
587 }
588 return true;
589 }
590
591 /**
592 * Remove the map.
593 *
594 * @param <K> the key type
595 * @param <V> the value type
596 * @param map the map
597 */
598 public <K, V> void removeMap(TransactionMap<K, V> map) {
599 store.removeMap(map);
600 }
601
602 @Override
603 public String toString() {
604 return transactionId + "(" + sequenceNum + ") " + stateToString();
605 }
606
607 private String stateToString() {
608 return stateToString(statusAndLogId.get());
609 }
610
611 private static String stateToString(long state) {
612 return STATUS_NAMES[getStatus(state)] + (hasRollback(state) ? "<" : "") + " " + getLogId(state);
613 }
614
615
616 private static int getStatus(long state) {
617 return (int)(state >>> LOG_ID_BITS1) & STATUS_MASK;
618 }
619
620 private static long getLogId(long state) {
621 return state & LOG_ID_MASK;
622 }
623
624 private static boolean hasRollback(long state) {
625 return (state & (1L << (STATUS_BITS + LOG_ID_BITS1))) != 0;
626 }
627
628 private static boolean hasChanges(long state) {
629 return getLogId(state) != 0;
630 }
631
632 private static long composeState(int status, long logId, boolean hasRollback) {
633 assert logId < LOG_ID_LIMIT : logId;
634 assert (status & ~STATUS_MASK) == 0 : status;
635
636 if (hasRollback) {
637 status |= 1 << STATUS_BITS;
638 }
639 return ((long)status << LOG_ID_BITS1) | logId;
640 }
641 }