Adjust to yangtools-2.0.0 changes
[mdsal.git] / dom / mdsal-dom-inmemory-datastore / src / main / java / org / opendaylight / mdsal / dom / store / inmemory / InmemoryDOMDataTreeShardWriteTransaction.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.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.ListeningExecutorService;
15 import java.util.ArrayList;
16 import java.util.Iterator;
17 import java.util.Map.Entry;
18 import java.util.Optional;
19 import java.util.concurrent.atomic.AtomicLong;
20 import org.opendaylight.mdsal.common.api.ReadFailedException;
21 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
23 import org.opendaylight.mdsal.dom.spi.shard.DOMDataTreeShardWriteTransaction;
24 import org.opendaylight.mdsal.dom.spi.shard.ForeignShardModificationContext;
25 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
26 import org.opendaylight.yangtools.concepts.Identifiable;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 class InmemoryDOMDataTreeShardWriteTransaction implements DOMDataTreeShardWriteTransaction, Identifiable<String> {
36
37     private static final Logger LOG = LoggerFactory.getLogger(InmemoryDOMDataTreeShardWriteTransaction.class);
38
39     private enum SimpleCursorOperation {
40         MERGE {
41             @Override
42             void applyOnLeaf(final DOMDataTreeWriteCursor cur, final PathArgument child,
43                              final NormalizedNode<?, ?> data) {
44                 cur.merge(child, data);
45             }
46         },
47         DELETE {
48             @Override
49             void applyOnLeaf(final DOMDataTreeWriteCursor cur, final PathArgument child,
50                              final NormalizedNode<?, ?> data) {
51                 cur.delete(child);
52             }
53         },
54         WRITE {
55             @Override
56             void applyOnLeaf(final DOMDataTreeWriteCursor cur, final PathArgument child,
57                              final NormalizedNode<?, ?> data) {
58                 cur.write(child, data);
59             }
60         };
61
62         abstract void applyOnLeaf(DOMDataTreeWriteCursor cur, PathArgument child, NormalizedNode<?, ?> data);
63
64         void apply(final DOMDataTreeWriteCursor cur, final YangInstanceIdentifier path,
65                    final NormalizedNode<?, ?> data) {
66             int enterCount = 0;
67             final Iterator<PathArgument> it = path.getPathArguments().iterator();
68             if (it.hasNext()) {
69                 while (true) {
70                     final PathArgument currentArg = it.next();
71                     if (!it.hasNext()) {
72                         applyOnLeaf(cur, currentArg, data);
73                         break;
74                     }
75
76                     // We need to enter one level deeper, we are not at leaf (modified) node
77                     cur.enter(currentArg);
78                     enterCount++;
79                 }
80             }
81
82             cur.exit(enterCount);
83         }
84     }
85
86     private static final AtomicLong COUNTER = new AtomicLong();
87
88     private final ArrayList<DOMStoreThreePhaseCommitCohort> cohorts = new ArrayList<>();
89     private final InMemoryDOMDataTreeShardChangePublisher changePublisher;
90     private final InMemoryDOMDataTreeShardProducer producer;
91     private final ShardDataModification modification;
92     private final ListeningExecutorService executor;
93     private final DataTree rootShardDataTree;
94     private final String identifier;
95
96     private DataTreeModification rootModification = null;
97     private DOMDataTreeWriteCursor cursor;
98     private boolean finished = false;
99
100     InmemoryDOMDataTreeShardWriteTransaction(final InMemoryDOMDataTreeShardProducer producer,
101                                              final ShardDataModification root,
102                                              final DataTree rootShardDataTree,
103                                              final InMemoryDOMDataTreeShardChangePublisher changePublisher,
104                                              final ListeningExecutorService executor) {
105         this.producer = producer;
106         this.modification = Preconditions.checkNotNull(root);
107         this.rootShardDataTree = Preconditions.checkNotNull(rootShardDataTree);
108         this.changePublisher = Preconditions.checkNotNull(changePublisher);
109         this.identifier = "INMEMORY-SHARD-TX-" + COUNTER.getAndIncrement();
110         LOG.debug("Shard transaction{} created", identifier);
111         this.executor = executor;
112     }
113
114     @Override
115     public String getIdentifier() {
116         return identifier;
117     }
118
119     private DOMDataTreeWriteCursor getCursor() {
120         if (cursor == null) {
121             cursor = new InMemoryShardDataModificationCursor(modification, this);
122         }
123         return cursor;
124     }
125
126     void delete(final YangInstanceIdentifier path) {
127         final YangInstanceIdentifier relativePath = toRelative(path);
128         Preconditions.checkArgument(!YangInstanceIdentifier.EMPTY.equals(relativePath),
129                 "Deletion of shard root is not allowed");
130         SimpleCursorOperation.DELETE.apply(getCursor(), relativePath, null);
131     }
132
133     void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
134         SimpleCursorOperation.MERGE.apply(getCursor(), toRelative(path), data);
135     }
136
137     void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
138         SimpleCursorOperation.WRITE.apply(getCursor(), toRelative(path), data);
139     }
140
141     private YangInstanceIdentifier toRelative(final YangInstanceIdentifier path) {
142         final Optional<YangInstanceIdentifier> relative =
143                 path.relativeTo(modification.getPrefix().getRootIdentifier());
144         Preconditions.checkArgument(relative.isPresent());
145         return relative.get();
146     }
147
148     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
149         throw new UnsupportedOperationException("Not implemented yet");
150     }
151
152     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
153         throw new UnsupportedOperationException("Not implemented yet");
154     }
155
156     @Override
157     public void close() {
158         Preconditions.checkState(!finished, "Attempting to close an already finished transaction.");
159         modification.closeTransactions();
160         if (cursor != null) {
161             cursor.close();
162         }
163         producer.transactionAborted(this);
164         finished = true;
165     }
166
167     void cursorClosed() {
168         Preconditions.checkNotNull(cursor);
169         modification.closeCursor();
170         cursor = null;
171     }
172
173     public boolean isFinished() {
174         return finished;
175     }
176
177     @Override
178     public void ready() {
179         Preconditions.checkState(!finished, "Attempting to ready an already finished transaction.");
180         Preconditions.checkState(cursor == null, "Attempting to ready a transaction that has an open cursor.");
181         Preconditions.checkNotNull(modification, "Attempting to ready an empty transaction.");
182
183         LOG.debug("Readying open transaction on shard {}", modification.getPrefix());
184         rootModification = modification.seal();
185
186         producer.transactionReady(this, rootModification);
187         cohorts.add(new InMemoryDOMDataTreeShardThreePhaseCommitCohort(
188                 rootShardDataTree, rootModification, changePublisher));
189         for (final Entry<DOMDataTreeIdentifier, ForeignShardModificationContext> entry :
190                 modification.getChildShards().entrySet()) {
191             cohorts.add(new ForeignShardThreePhaseCommitCohort(entry.getKey(), entry.getValue()));
192         }
193         finished = true;
194     }
195
196     @Override
197     public ListenableFuture<Void> submit() {
198         LOG.debug("Submitting open transaction on shard {}", modification.getPrefix());
199
200         Preconditions.checkNotNull(cohorts);
201         Preconditions.checkState(!cohorts.isEmpty(), "Transaction was not readied yet.");
202
203         return executor.submit(new ShardSubmitCoordinationTask(modification.getPrefix(), cohorts, this));
204     }
205
206     @Override
207     public ListenableFuture<Boolean> validate() {
208         LOG.debug("CanCommit on open transaction on shard {}", modification.getPrefix());
209         return executor.submit(new ShardCanCommitCoordinationTask(modification.getPrefix(), cohorts));
210     }
211
212     @Override
213     public ListenableFuture<Void> prepare() {
214         LOG.debug("PreCommit on open transaction on shard {}", modification.getPrefix());
215         return executor.submit(new ShardPreCommitCoordinationTask(modification.getPrefix(), cohorts));
216     }
217
218     @Override
219     public ListenableFuture<Void> commit() {
220         LOG.debug("Commit open transaction on shard {}", modification.getPrefix());
221         return executor.submit(new ShardCommitCoordinationTask(modification.getPrefix(), cohorts, this));
222     }
223
224     DataTreeModification getRootModification() {
225         Preconditions.checkNotNull(rootModification, "Transaction wasn't sealed yet");
226         return rootModification;
227     }
228
229     void transactionCommited(final InmemoryDOMDataTreeShardWriteTransaction tx) {
230         producer.onTransactionCommited(tx);
231     }
232
233     @Override
234     public DOMDataTreeWriteCursor createCursor(final DOMDataTreeIdentifier prefix) {
235         Preconditions.checkState(!finished, "Transaction is finished/closed already.");
236         Preconditions.checkState(cursor == null, "Previous cursor wasn't closed");
237         final YangInstanceIdentifier relativePath = toRelative(prefix.getRootIdentifier());
238         final DOMDataTreeWriteCursor ret = getCursor();
239         ret.enter(relativePath.getPathArguments());
240         return ret;
241     }
242 }