Fix InMemory shard transaction chaining.
[mdsal.git] / dom / mdsal-dom-inmemory-datastore / src / main / java / org / opendaylight / mdsal / dom / store / inmemory / InMemoryDOMDataTreeShardProducer.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.mdsal.dom.store.inmemory;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.AbstractMap.SimpleEntry;
14 import java.util.Collection;
15 import java.util.Map.Entry;
16 import java.util.concurrent.atomic.AtomicLong;
17 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
18 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 class InMemoryDOMDataTreeShardProducer implements DOMDataTreeShardProducer {
25
26     private abstract static class State {
27         /**
28          * Allocate a new snapshot.
29          *
30          * @return A new snapshot
31          */
32         protected abstract DataTreeSnapshot getSnapshot(Object transactionId);
33     }
34
35     private static final class Idle extends State {
36         private final InMemoryDOMDataTreeShardProducer producer;
37
38         Idle(final InMemoryDOMDataTreeShardProducer producer) {
39             this.producer = Preconditions.checkNotNull(producer);
40         }
41
42         @Override
43         protected DataTreeSnapshot getSnapshot(Object transactionId) {
44             return producer.takeSnapshot();
45         }
46     }
47
48     /**
49      * We have a transaction out there.
50      */
51     private static final class Allocated extends State {
52         private static final AtomicReferenceFieldUpdater<Allocated, DataTreeSnapshot> SNAPSHOT_UPDATER =
53                 AtomicReferenceFieldUpdater.newUpdater(Allocated.class, DataTreeSnapshot.class, "snapshot");
54         private final InmemoryDOMDataTreeShardWriteTransaction transaction;
55         private volatile DataTreeSnapshot snapshot;
56
57         Allocated(final InmemoryDOMDataTreeShardWriteTransaction transaction) {
58             this.transaction = Preconditions.checkNotNull(transaction);
59         }
60
61         public InmemoryDOMDataTreeShardWriteTransaction getTransaction() {
62             return transaction;
63         }
64
65         @Override
66         protected DataTreeSnapshot getSnapshot(Object transactionId) {
67             final DataTreeSnapshot ret = snapshot;
68             Preconditions.checkState(ret != null,
69                     "Could not get snapshot for transaction %s - previous transaction %s is not ready yet",
70                     transactionId, transaction.getIdentifier());
71             return ret;
72         }
73
74         void setSnapshot(final DataTreeSnapshot snapshot) {
75             final boolean success = SNAPSHOT_UPDATER.compareAndSet(this, null, snapshot);
76             Preconditions.checkState(success, "Transaction %s has already been marked as ready",
77                     transaction.getIdentifier());
78         }
79     }
80
81     /**
82      * Producer is logically shut down, no further allocation allowed.
83      */
84     private static final class Shutdown extends State {
85         private final String message;
86
87         Shutdown(final String message) {
88             this.message = Preconditions.checkNotNull(message);
89         }
90
91         @Override
92         protected DataTreeSnapshot getSnapshot(Object transactionId) {
93             throw new IllegalStateException(message);
94         }
95     }
96
97     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataTreeShard.class);
98     private static final AtomicLong COUNTER = new AtomicLong();
99
100     private final InMemoryDOMDataTreeShard parentShard;
101     private final Collection<DOMDataTreeIdentifier> prefixes;
102
103     private static final AtomicReferenceFieldUpdater<InMemoryDOMDataTreeShardProducer, State> STATE_UPDATER =
104             AtomicReferenceFieldUpdater.newUpdater(InMemoryDOMDataTreeShardProducer.class, State.class, "state");
105     private final Idle idleState = new Idle(this);
106     private volatile State state;
107
108     InMemoryDOMDataTreeShardProducer(final InMemoryDOMDataTreeShard parentShard,
109             final Collection<DOMDataTreeIdentifier> prefixes) {
110         this.parentShard = Preconditions.checkNotNull(parentShard);
111         this.prefixes = ImmutableSet.copyOf(prefixes);
112         state = idleState;
113     }
114
115     @Override
116     public synchronized InmemoryDOMDataTreeShardWriteTransaction createTransaction() {
117         Entry<State, DataTreeSnapshot> entry;
118         InmemoryDOMDataTreeShardWriteTransaction ret;
119         String transactionId = nextIdentifier();
120
121         do {
122             entry = getSnapshot(transactionId);
123             ret = parentShard.createTransaction(transactionId, this, prefixes, entry.getValue());
124         } while (!recordTransaction(entry.getKey(), ret));
125
126         return ret;
127     }
128
129     synchronized void transactionReady(final InmemoryDOMDataTreeShardWriteTransaction tx,
130                                        final DataTreeModification modification) {
131         final State localState = state;
132         LOG.debug("Transaction was readied {}, current state {}", tx.getIdentifier(), localState);
133
134         if (localState instanceof Allocated) {
135             final Allocated allocated = (Allocated) localState;
136             final InmemoryDOMDataTreeShardWriteTransaction transaction = allocated.getTransaction();
137             Preconditions.checkState(tx.equals(transaction),
138                     "Mis-ordered ready transaction %s last allocated was %s", tx, transaction);
139             allocated.setSnapshot(modification);
140         } else {
141             LOG.debug("Ignoring transaction {} readiness due to state {}", tx, localState);
142         }
143     }
144
145     /**
146      * Notify the base logic that a previously-submitted transaction has been committed successfully.
147      *
148      * @param transaction Transaction which completed successfully.
149      */
150     synchronized void onTransactionCommited(final InmemoryDOMDataTreeShardWriteTransaction transaction) {
151         // If the committed transaction was the one we allocated last,
152         // we clear it and the ready snapshot, so the next transaction
153         // allocated refers to the data tree directly.
154         final State localState = state;
155         LOG.debug("Transaction {} commit done, current state {}", transaction.getIdentifier(), localState);
156
157         if (!(localState instanceof Allocated)) {
158             // This can legally happen if the chain is shut down before the transaction was committed
159             // by the backend.
160             LOG.debug("Ignoring successful transaction {} in state {}", transaction, localState);
161             return;
162         }
163
164         final Allocated allocated = (Allocated) localState;
165         final InmemoryDOMDataTreeShardWriteTransaction tx = allocated.getTransaction();
166         if (!tx.equals(transaction)) {
167             LOG.debug("Ignoring non-latest successful transaction {} in state {}", transaction, allocated);
168             return;
169         }
170
171         if (!STATE_UPDATER.compareAndSet(this, localState, idleState)) {
172             LOG.debug("Producer {} has already transitioned from {} to {}, not making it idle", this,
173                     localState, state);
174         }
175     }
176
177     synchronized void transactionAborted(final InmemoryDOMDataTreeShardWriteTransaction tx) {
178         final State localState = state;
179         if (localState instanceof Allocated) {
180             final Allocated allocated = (Allocated)localState;
181             if (allocated.getTransaction().equals(tx)) {
182                 final boolean success = STATE_UPDATER.compareAndSet(this, localState, idleState);
183                 if (!success) {
184                     LOG.warn("Transaction {} aborted, but producer {} state already transitioned from {} to {}",
185                             tx, this, localState, state);
186                 }
187             }
188         }
189     }
190
191
192     private Entry<State, DataTreeSnapshot> getSnapshot(String transactionId) {
193         final State localState = state;
194         return new SimpleEntry<>(localState, localState.getSnapshot(transactionId));
195     }
196
197     private boolean recordTransaction(final State expected,
198                                       final InmemoryDOMDataTreeShardWriteTransaction transaction) {
199         final State state = new Allocated(transaction);
200         return STATE_UPDATER.compareAndSet(this, expected, state);
201     }
202
203     private String nextIdentifier() {
204         return "INMEMORY-SHARD-TX-" + COUNTER.getAndIncrement();
205
206     }
207
208     DataTreeSnapshot takeSnapshot() {
209         return parentShard.takeSnapshot();
210     }
211
212     @Override
213     public Collection<DOMDataTreeIdentifier> getPrefixes() {
214         return prefixes;
215     }
216 }