-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
KernelTransactionImplementation.java
1243 lines (1127 loc) · 42.9 KB
/
KernelTransactionImplementation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.api;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.neo4j.collection.pool.Pool;
import org.neo4j.graphdb.NotInTransactionException;
import org.neo4j.graphdb.TransactionTerminatedException;
import org.neo4j.internal.kernel.api.CursorFactory;
import org.neo4j.internal.kernel.api.ExecutionStatistics;
import org.neo4j.internal.kernel.api.ExplicitIndexRead;
import org.neo4j.internal.kernel.api.ExplicitIndexWrite;
import org.neo4j.internal.kernel.api.NodeCursor;
import org.neo4j.internal.kernel.api.PropertyCursor;
import org.neo4j.internal.kernel.api.Read;
import org.neo4j.internal.kernel.api.RelationshipScanCursor;
import org.neo4j.internal.kernel.api.SchemaRead;
import org.neo4j.internal.kernel.api.SchemaWrite;
import org.neo4j.internal.kernel.api.Token;
import org.neo4j.internal.kernel.api.TokenRead;
import org.neo4j.internal.kernel.api.TokenWrite;
import org.neo4j.internal.kernel.api.Write;
import org.neo4j.internal.kernel.api.exceptions.InvalidTransactionTypeKernelException;
import org.neo4j.internal.kernel.api.exceptions.TransactionFailureException;
import org.neo4j.internal.kernel.api.exceptions.schema.ConstraintValidationException;
import org.neo4j.internal.kernel.api.exceptions.schema.CreateConstraintFailureException;
import org.neo4j.internal.kernel.api.schema.SchemaDescriptor;
import org.neo4j.internal.kernel.api.security.AccessMode;
import org.neo4j.internal.kernel.api.security.AuthSubject;
import org.neo4j.internal.kernel.api.security.SecurityContext;
import org.neo4j.io.pagecache.tracing.cursor.PageCursorTracer;
import org.neo4j.io.pagecache.tracing.cursor.PageCursorTracerSupplier;
import org.neo4j.io.pagecache.tracing.cursor.context.VersionContextSupplier;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.SilentTokenNameLookup;
import org.neo4j.kernel.api.exceptions.ConstraintViolationTransactionFailureException;
import org.neo4j.kernel.api.exceptions.Status;
import org.neo4j.kernel.api.explicitindex.AutoIndexing;
import org.neo4j.kernel.api.txstate.ExplicitIndexTransactionState;
import org.neo4j.kernel.api.txstate.TransactionState;
import org.neo4j.kernel.api.txstate.TxStateHolder;
import org.neo4j.kernel.availability.AvailabilityGuard;
import org.neo4j.kernel.impl.api.index.IndexingProvidersService;
import org.neo4j.kernel.impl.api.state.ConstraintIndexCreator;
import org.neo4j.kernel.impl.api.state.TxState;
import org.neo4j.kernel.impl.constraints.ConstraintSemantics;
import org.neo4j.kernel.impl.core.TokenHolders;
import org.neo4j.kernel.impl.factory.AccessCapability;
import org.neo4j.kernel.impl.index.ExplicitIndexStore;
import org.neo4j.kernel.impl.locking.ActiveLock;
import org.neo4j.kernel.impl.locking.Locks;
import org.neo4j.kernel.impl.locking.StatementLocks;
import org.neo4j.kernel.impl.newapi.AllStoreHolder;
import org.neo4j.kernel.impl.newapi.DefaultCursors;
import org.neo4j.kernel.impl.newapi.IndexTxStateUpdater;
import org.neo4j.kernel.impl.newapi.KernelToken;
import org.neo4j.kernel.impl.newapi.Operations;
import org.neo4j.kernel.impl.proc.Procedures;
import org.neo4j.kernel.impl.transaction.TransactionHeaderInformationFactory;
import org.neo4j.kernel.impl.transaction.TransactionMonitor;
import org.neo4j.kernel.impl.transaction.log.PhysicalTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.tracing.CommitEvent;
import org.neo4j.kernel.impl.transaction.tracing.TransactionEvent;
import org.neo4j.kernel.impl.transaction.tracing.TransactionTracer;
import org.neo4j.kernel.impl.util.Dependencies;
import org.neo4j.kernel.impl.util.collection.CollectionsFactory;
import org.neo4j.kernel.impl.util.collection.CollectionsFactorySupplier;
import org.neo4j.resources.CpuClock;
import org.neo4j.resources.HeapAllocation;
import org.neo4j.storageengine.api.StorageCommand;
import org.neo4j.storageengine.api.StorageEngine;
import org.neo4j.storageengine.api.StorageReader;
import org.neo4j.storageengine.api.lock.LockTracer;
import org.neo4j.storageengine.api.schema.IndexDescriptor;
import org.neo4j.storageengine.api.txstate.TxStateVisitor;
import static java.lang.String.format;
import static java.util.Collections.emptyMap;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.neo4j.storageengine.api.TransactionApplicationMode.INTERNAL;
/**
* This class should replace the {@link org.neo4j.kernel.api.KernelTransaction} interface, and take its name, as soon
* as
* {@code TransitionalTxManagementKernelTransaction} is gone from {@code server}.
*/
public class KernelTransactionImplementation implements KernelTransaction, TxStateHolder, ExecutionStatistics
{
/*
* IMPORTANT:
* This class is pooled and re-used. If you add *any* state to it, you *must* make sure that:
* - the #initialize() method resets that state for re-use
* - the #release() method releases resources acquired in #initialize() or during the transaction's life time
*/
// default values for not committed tx id and tx commit time
private static final long NOT_COMMITTED_TRANSACTION_ID = -1;
private static final long NOT_COMMITTED_TRANSACTION_COMMIT_TIME = -1;
private final CollectionsFactory collectionsFactory;
// Logic
private final SchemaWriteGuard schemaWriteGuard;
private final TransactionHooks hooks;
private final ConstraintIndexCreator constraintIndexCreator;
private final StorageEngine storageEngine;
private final TransactionTracer transactionTracer;
private final Pool<KernelTransactionImplementation> pool;
private final Supplier<ExplicitIndexTransactionState> explicitIndexTxStateSupplier;
// For committing
private final TransactionHeaderInformationFactory headerInformationFactory;
private final TransactionCommitProcess commitProcess;
private final TransactionMonitor transactionMonitor;
private final PageCursorTracerSupplier cursorTracerSupplier;
private final VersionContextSupplier versionContextSupplier;
private final AvailabilityGuard databaseAvailabilityGuard;
private final StorageReader storageReader;
private final ClockContext clocks;
private final AccessCapability accessCapability;
private final ConstraintSemantics constraintSemantics;
// State that needs to be reset between uses. Most of these should be cleared or released in #release(),
// whereas others, such as timestamp or txId when transaction starts, even locks, needs to be set in #initialize().
private TxState txState;
private ExplicitIndexTransactionState explicitIndexTransactionState;
private TransactionWriteState writeState;
private TransactionHooks.TransactionHooksState hooksState;
private final KernelStatement currentStatement;
private final List<CloseListener> closeListeners = new ArrayList<>( 2 );
private SecurityContext securityContext;
private volatile StatementLocks statementLocks;
private volatile long userTransactionId;
private boolean beforeHookInvoked;
private volatile boolean closing;
private volatile boolean closed;
private boolean failure;
private boolean success;
private volatile Status terminationReason;
private long startTimeMillis;
private long timeoutMillis;
private long lastTransactionIdWhenStarted;
private volatile long lastTransactionTimestampWhenStarted;
private final Statistics statistics;
private TransactionEvent transactionEvent;
private Type type;
private long transactionId;
private long commitTime;
private volatile int reuseCount;
private volatile Map<String,Object> userMetaData;
private final Operations operations;
/**
* Lock prevents transaction {@link #markForTermination(Status)} transaction termination} from interfering with
* {@link #close() transaction commit} and specifically with {@link #release()}.
* Termination can run concurrently with commit and we need to make sure that it terminates the right lock client
* and the right transaction (with the right {@link #reuseCount}) because {@link KernelTransactionImplementation}
* instances are pooled.
*/
private final Lock terminationReleaseLock = new ReentrantLock();
public KernelTransactionImplementation( StatementOperationParts statementOperations, SchemaWriteGuard schemaWriteGuard, TransactionHooks hooks,
ConstraintIndexCreator constraintIndexCreator, Procedures procedures, TransactionHeaderInformationFactory headerInformationFactory,
TransactionCommitProcess commitProcess, TransactionMonitor transactionMonitor, Supplier<ExplicitIndexTransactionState> explicitIndexTxStateSupplier,
Pool<KernelTransactionImplementation> pool, Clock clock, AtomicReference<CpuClock> cpuClockRef, AtomicReference<HeapAllocation> heapAllocationRef,
TransactionTracer transactionTracer, LockTracer lockTracer, PageCursorTracerSupplier cursorTracerSupplier, StorageEngine storageEngine,
AccessCapability accessCapability, AutoIndexing autoIndexing, ExplicitIndexStore explicitIndexStore, VersionContextSupplier versionContextSupplier,
CollectionsFactorySupplier collectionsFactorySupplier, ConstraintSemantics constraintSemantics, SchemaState schemaState,
IndexingProvidersService indexProviders, TokenHolders tokenHolders, Dependencies dataSourceDependencies,
AvailabilityGuard databaseAvailabilityGuard )
{
this.schemaWriteGuard = schemaWriteGuard;
this.hooks = hooks;
this.constraintIndexCreator = constraintIndexCreator;
this.headerInformationFactory = headerInformationFactory;
this.commitProcess = commitProcess;
this.transactionMonitor = transactionMonitor;
this.storageReader = storageEngine.newReader();
this.storageEngine = storageEngine;
this.explicitIndexTxStateSupplier = explicitIndexTxStateSupplier;
this.pool = pool;
this.clocks = new ClockContext( clock );
this.transactionTracer = transactionTracer;
this.cursorTracerSupplier = cursorTracerSupplier;
this.versionContextSupplier = versionContextSupplier;
this.databaseAvailabilityGuard = databaseAvailabilityGuard;
this.currentStatement = new KernelStatement( this, this, storageReader,
lockTracer, statementOperations, this.clocks,
versionContextSupplier );
this.accessCapability = accessCapability;
this.statistics = new Statistics( this, cpuClockRef, heapAllocationRef );
this.userMetaData = emptyMap();
this.constraintSemantics = constraintSemantics;
DefaultCursors cursors = new DefaultCursors( storageReader );
AllStoreHolder allStoreHolder =
new AllStoreHolder( storageReader, this, cursors, explicitIndexStore,
procedures, schemaState, dataSourceDependencies );
this.operations =
new Operations(
allStoreHolder,
new IndexTxStateUpdater( storageReader, allStoreHolder, indexProviders ), storageReader,
this,
new KernelToken( storageReader, this, tokenHolders ),
cursors,
autoIndexing,
constraintIndexCreator,
constraintSemantics,
indexProviders );
this.collectionsFactory = collectionsFactorySupplier.create();
}
/**
* Reset this transaction to a vanilla state, turning it into a logically new transaction.
*/
public KernelTransactionImplementation initialize( long lastCommittedTx, long lastTimeStamp, StatementLocks statementLocks, Type type,
SecurityContext frozenSecurityContext, long transactionTimeout, long userTransactionId )
{
this.type = type;
this.statementLocks = statementLocks;
this.userTransactionId = userTransactionId;
this.terminationReason = null;
this.closing = false;
this. closed = false;
this.beforeHookInvoked = false;
this.failure = false;
this.success = false;
this.writeState = TransactionWriteState.NONE;
this.startTimeMillis = clocks.systemClock().millis();
this.timeoutMillis = transactionTimeout;
this.lastTransactionIdWhenStarted = lastCommittedTx;
this.lastTransactionTimestampWhenStarted = lastTimeStamp;
this.transactionEvent = transactionTracer.beginTransaction();
assert transactionEvent != null : "transactionEvent was null!";
this.securityContext = frozenSecurityContext;
this.transactionId = NOT_COMMITTED_TRANSACTION_ID;
this.commitTime = NOT_COMMITTED_TRANSACTION_COMMIT_TIME;
PageCursorTracer pageCursorTracer = cursorTracerSupplier.get();
this.statistics.init( Thread.currentThread().getId(), pageCursorTracer );
this.currentStatement.initialize( statementLocks, pageCursorTracer );
this.operations.initialize();
return this;
}
int getReuseCount()
{
return reuseCount;
}
@Override
public long startTime()
{
return startTimeMillis;
}
@Override
public long timeout()
{
return timeoutMillis;
}
@Override
public long lastTransactionIdWhenStarted()
{
return lastTransactionIdWhenStarted;
}
@Override
public void success()
{
this.success = true;
}
boolean isSuccess()
{
return success;
}
@Override
public void failure()
{
failure = true;
}
@Override
public Optional<Status> getReasonIfTerminated()
{
return Optional.ofNullable( terminationReason );
}
boolean markForTermination( long expectedReuseCount, Status reason )
{
terminationReleaseLock.lock();
try
{
return expectedReuseCount == reuseCount && markForTerminationIfPossible( reason );
}
finally
{
terminationReleaseLock.unlock();
}
}
/**
* {@inheritDoc}
* <p>
* This method is guarded by {@link #terminationReleaseLock} to coordinate concurrent
* {@link #close()} and {@link #release()} calls.
*/
@Override
public void markForTermination( Status reason )
{
terminationReleaseLock.lock();
try
{
markForTerminationIfPossible( reason );
}
finally
{
terminationReleaseLock.unlock();
}
}
private boolean markForTerminationIfPossible( Status reason )
{
if ( canBeTerminated() )
{
failure = true;
terminationReason = reason;
if ( statementLocks != null )
{
statementLocks.stop();
}
transactionMonitor.transactionTerminated( hasTxStateWithChanges() );
return true;
}
return false;
}
@Override
public boolean isOpen()
{
return !closed && !closing;
}
@Override
public SecurityContext securityContext()
{
if ( securityContext == null )
{
throw new NotInTransactionException();
}
return securityContext;
}
@Override
public AuthSubject subjectOrAnonymous()
{
SecurityContext context = this.securityContext;
return context == null ? AuthSubject.ANONYMOUS : context.subject();
}
@Override
public void setMetaData( Map<String, Object> data )
{
this.userMetaData = data;
}
@Override
public AvailabilityGuard getAvailabilityGuard()
{
return databaseAvailabilityGuard;
}
public Map<String, Object> getMetaData()
{
return userMetaData;
}
@Override
public KernelStatement acquireStatement()
{
assertTransactionOpen();
currentStatement.acquire();
return currentStatement;
}
@Override
public IndexDescriptor indexUniqueCreate( SchemaDescriptor schema, Optional<String> provider )
{
return operations.indexUniqueCreate( schema, provider );
}
@Override
public long pageHits()
{
return cursorTracerSupplier.get().hits();
}
@Override
public long pageFaults()
{
return cursorTracerSupplier.get().faults();
}
ExecutingQueryList executingQueries()
{
return currentStatement.executingQueryList();
}
void upgradeToDataWrites() throws InvalidTransactionTypeKernelException
{
writeState = writeState.upgradeToDataWrites();
}
void upgradeToSchemaWrites() throws InvalidTransactionTypeKernelException
{
schemaWriteGuard.assertSchemaWritesAllowed();
writeState = writeState.upgradeToSchemaWrites();
}
private void dropCreatedConstraintIndexes() throws TransactionFailureException
{
if ( hasTxStateWithChanges() )
{
for ( IndexDescriptor createdConstraintIndex : txState().constraintIndexesCreatedInTx() )
{
// TODO logically, which statement should this operation be performed on?
constraintIndexCreator.dropUniquenessConstraintIndex( createdConstraintIndex );
}
}
}
@Override
public TransactionState txState()
{
if ( txState == null )
{
transactionMonitor.upgradeToWriteTransaction();
txState = new TxState( collectionsFactory );
}
return txState;
}
@Override
public ExplicitIndexTransactionState explicitIndexTxState()
{
return explicitIndexTransactionState != null ? explicitIndexTransactionState :
(explicitIndexTransactionState = explicitIndexTxStateSupplier.get());
}
@Override
public boolean hasTxStateWithChanges()
{
return txState != null && txState.hasChanges();
}
private void markAsClosed( long txId )
{
assertTransactionOpen();
closed = true;
notifyListeners( txId );
closeCurrentStatementIfAny();
}
private void notifyListeners( long txId )
{
for ( CloseListener closeListener : closeListeners )
{
closeListener.notify( txId );
}
}
private void closeCurrentStatementIfAny()
{
currentStatement.forceClose();
}
private void assertTransactionNotClosing()
{
if ( closing )
{
throw new IllegalStateException( "This transaction is already being closed." );
}
}
private void assertTransactionOpen()
{
if ( closed )
{
throw new IllegalStateException( "This transaction has already been completed." );
}
}
@Override
public void assertOpen()
{
Status reason = this.terminationReason;
if ( reason != null )
{
throw new TransactionTerminatedException( reason );
}
if ( closed )
{
throw new NotInTransactionException( "The transaction has been closed." );
}
}
private boolean hasChanges()
{
return hasTxStateWithChanges() || hasExplicitIndexChanges();
}
private boolean hasExplicitIndexChanges()
{
return explicitIndexTransactionState != null && explicitIndexTransactionState.hasChanges();
}
private boolean hasDataChanges()
{
return hasTxStateWithChanges() && txState.hasDataChanges();
}
@Override
public long closeTransaction() throws TransactionFailureException
{
assertTransactionOpen();
assertTransactionNotClosing();
closing = true;
try
{
if ( failure || !success || isTerminated() )
{
rollback();
failOnNonExplicitRollbackIfNeeded();
return ROLLBACK;
}
else
{
return commit();
}
}
finally
{
try
{
closed = true;
closing = false;
transactionEvent.setSuccess( success );
transactionEvent.setFailure( failure );
transactionEvent.setTransactionWriteState( writeState.name() );
transactionEvent.setReadOnly( txState == null || !txState.hasChanges() );
transactionEvent.close();
}
finally
{
release();
}
}
}
public boolean isClosing()
{
return closing;
}
/**
* Throws exception if this transaction was marked as successful but failure flag has also been set to true.
* <p>
* This could happen when:
* <ul>
* <li>caller explicitly calls both {@link #success()} and {@link #failure()}</li>
* <li>caller explicitly calls {@link #success()} but transaction execution fails</li>
* <li>caller explicitly calls {@link #success()} but transaction is terminated</li>
* </ul>
* <p>
*
* @throws TransactionFailureException when execution failed
* @throws TransactionTerminatedException when transaction was terminated
*/
private void failOnNonExplicitRollbackIfNeeded() throws TransactionFailureException
{
if ( success && isTerminated() )
{
throw new TransactionTerminatedException( terminationReason );
}
if ( success )
{
// Success was called, but also failure which means that the client code using this
// transaction passed through a happy path, but the transaction was still marked as
// failed for one or more reasons. Tell the user that although it looked happy it
// wasn't committed, but was instead rolled back.
throw new TransactionFailureException( Status.Transaction.TransactionMarkedAsFailed,
"Transaction rolled back even if marked as successful" );
}
}
private long commit() throws TransactionFailureException
{
boolean success = false;
long txId = READ_ONLY;
try ( CommitEvent commitEvent = transactionEvent.beginCommitEvent() )
{
// Trigger transaction "before" hooks.
if ( hasDataChanges() )
{
try
{
hooksState = hooks.beforeCommit( txState, this, storageReader );
if ( hooksState != null && hooksState.failed() )
{
Throwable cause = hooksState.failure();
throw new TransactionFailureException( Status.Transaction.TransactionHookFailed, cause, "" );
}
}
finally
{
beforeHookInvoked = true;
}
}
// Convert changes into commands and commit
if ( hasChanges() )
{
// grab all optimistic locks now, locks can't be deferred any further
statementLocks.prepareForCommit( currentStatement.lockTracer() );
// use pessimistic locks for the rest of the commit process, locks can't be deferred any further
Locks.Client commitLocks = statementLocks.pessimistic();
// Gather up commands from the various sources
Collection<StorageCommand> extractedCommands = new ArrayList<>();
storageEngine.createCommands(
extractedCommands,
txState, storageReader,
commitLocks,
lastTransactionIdWhenStarted,
this::enforceConstraints );
if ( hasExplicitIndexChanges() )
{
explicitIndexTransactionState.extractCommands( extractedCommands );
}
/* Here's the deal: we track a quick-to-access hasChanges in transaction state which is true
* if there are any changes imposed by this transaction. Some changes made inside a transaction undo
* previously made changes in that same transaction, and so at some point a transaction may have
* changes and at another point, after more changes seemingly,
* the transaction may not have any changes.
* However, to track that "undoing" of the changes is a bit tedious, intrusive and hard to maintain
* and get right.... So to really make sure the transaction has changes we re-check by looking if we
* have produced any commands to add to the logical log.
*/
if ( !extractedCommands.isEmpty() )
{
// Finish up the whole transaction representation
PhysicalTransactionRepresentation transactionRepresentation =
new PhysicalTransactionRepresentation( extractedCommands );
TransactionHeaderInformation headerInformation = headerInformationFactory.create();
long timeCommitted = clocks.systemClock().millis();
transactionRepresentation.setHeader( headerInformation.getAdditionalHeader(),
headerInformation.getMasterId(),
headerInformation.getAuthorId(),
startTimeMillis, lastTransactionIdWhenStarted, timeCommitted,
commitLocks.getLockSessionId() );
// Commit the transaction
success = true;
TransactionToApply batch = new TransactionToApply( transactionRepresentation,
versionContextSupplier.getVersionContext() );
txId = transactionId = commitProcess.commit( batch, commitEvent, INTERNAL );
commitTime = timeCommitted;
}
}
success = true;
return txId;
}
catch ( ConstraintValidationException | CreateConstraintFailureException e )
{
throw new ConstraintViolationTransactionFailureException(
e.getUserMessage( new SilentTokenNameLookup( tokenRead() ) ), e );
}
finally
{
if ( !success )
{
rollback();
}
else
{
afterCommit( txId );
}
}
}
private void rollback() throws TransactionFailureException
{
try
{
try
{
dropCreatedConstraintIndexes();
}
catch ( IllegalStateException | SecurityException e )
{
throw new TransactionFailureException( Status.Transaction.TransactionRollbackFailed, e,
"Could not drop created constraint indexes" );
}
// Free any acquired id's
if ( txState != null )
{
try
{
txState.accept( new TxStateVisitor.Adapter()
{
@Override
public void visitCreatedNode( long id )
{
storageReader.releaseNode( id );
}
@Override
public void visitCreatedRelationship( long id, int type, long startNode, long endNode )
{
storageReader.releaseRelationship( id );
}
} );
}
catch ( ConstraintValidationException | CreateConstraintFailureException e )
{
throw new IllegalStateException(
"Releasing locks during rollback should perform no constraints checking.", e );
}
}
}
finally
{
afterRollback();
}
}
@Override
public Read dataRead()
{
assertAllows( AccessMode::allowsReads, "Read" );
return operations.dataRead();
}
@Override
public Write dataWrite() throws InvalidTransactionTypeKernelException
{
accessCapability.assertCanWrite();
assertAllows( AccessMode::allowsWrites, "Write" );
upgradeToDataWrites();
return operations;
}
@Override
public TokenWrite tokenWrite()
{
accessCapability.assertCanWrite();
return operations.token();
}
@Override
public Token token()
{
accessCapability.assertCanWrite();
return operations.token();
}
@Override
public TokenRead tokenRead()
{
assertAllows( AccessMode::allowsReads, "Read" );
return operations.token();
}
@Override
public ExplicitIndexRead indexRead()
{
assertAllows( AccessMode::allowsReads, "Read" );
return operations.indexRead();
}
@Override
public ExplicitIndexWrite indexWrite() throws InvalidTransactionTypeKernelException
{
accessCapability.assertCanWrite();
assertAllows( AccessMode::allowsWrites, "Write" );
upgradeToDataWrites();
return operations;
}
@Override
public SchemaRead schemaRead()
{
assertAllows( AccessMode::allowsReads, "Read" );
return operations.schemaRead();
}
@Override
public SchemaWrite schemaWrite() throws InvalidTransactionTypeKernelException
{
accessCapability.assertCanWrite();
assertAllows( AccessMode::allowsSchemaWrites, "Schema" );
upgradeToSchemaWrites();
return operations;
}
@Override
public org.neo4j.internal.kernel.api.Locks locks()
{
return operations.locks();
}
public StatementLocks statementLocks()
{
assertOpen();
return statementLocks;
}
@Override
public CursorFactory cursors()
{
return operations.cursors();
}
@Override
public org.neo4j.internal.kernel.api.Procedures procedures()
{
return operations.procedures();
}
@Override
public ExecutionStatistics executionStatistics()
{
return this;
}
public LockTracer lockTracer()
{
return currentStatement.lockTracer();
}
public void assertAllows( Function<AccessMode,Boolean> allows, String mode )
{
AccessMode accessMode = securityContext().mode();
if ( !allows.apply( accessMode ) )
{
throw accessMode.onViolation(
format( "%s operations are not allowed for %s.", mode,
securityContext().description() ) );
}
}
private void afterCommit( long txId )
{
try
{
markAsClosed( txId );
if ( beforeHookInvoked )
{
hooks.afterCommit( txState, this, hooksState );
}
}
finally
{
transactionMonitor.transactionFinished( true, hasTxStateWithChanges() );
}
}
private void afterRollback()
{
try
{
markAsClosed( ROLLBACK );
if ( beforeHookInvoked )
{
hooks.afterRollback( txState, this, hooksState );
}
}
finally
{
transactionMonitor.transactionFinished( false, hasTxStateWithChanges() );
}
}
/**
* Release resources held up by this transaction & return it to the transaction pool.
* This method is guarded by {@link #terminationReleaseLock} to coordinate concurrent
* {@link #markForTermination(Status)} calls.
*/
private void release()
{
terminationReleaseLock.lock();
try
{
statementLocks.close();
statementLocks = null;
terminationReason = null;
type = null;
securityContext = null;
transactionEvent = null;
explicitIndexTransactionState = null;
txState = null;
collectionsFactory.release();
hooksState = null;
closeListeners.clear();
reuseCount++;
userMetaData = emptyMap();
userTransactionId = 0;
statistics.reset();
operations.release();
pool.release( this );
}
finally
{
terminationReleaseLock.unlock();
}
}
/**
* Transaction can be terminated only when it is not closed and not already terminated.
* Otherwise termination does not make sense.
*/
private boolean canBeTerminated()
{
return !closed && !isTerminated();
}
@Override
public boolean isTerminated()
{
return terminationReason != null;
}
@Override
public long lastTransactionTimestampWhenStarted()
{
return lastTransactionTimestampWhenStarted;
}
@Override
public void registerCloseListener( CloseListener listener )
{
assert listener != null;
closeListeners.add( listener );
}
@Override
public Type transactionType()
{
return type;
}
@Override
public long getTransactionId()
{
if ( transactionId == NOT_COMMITTED_TRANSACTION_ID )
{
throw new IllegalStateException( "Transaction id is not assigned yet. " +
"It will be assigned during transaction commit." );
}
return transactionId;
}
@Override
public long getCommitTime()