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