Eliminate ShardedDOMDataTreeWriteTransaction.doSubmit()'s return
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / ShardedDOMDataTreeWriteTransaction.java
1 /*
2  * Copyright (c) 2015 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 package org.opendaylight.mdsal.dom.broker;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.SettableFuture;
17 import java.util.ArrayDeque;
18 import java.util.Deque;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.concurrent.atomic.AtomicLong;
23 import java.util.function.BiConsumer;
24 import java.util.function.Consumer;
25 import java.util.stream.Collectors;
26 import javax.annotation.Nonnull;
27 import javax.annotation.concurrent.GuardedBy;
28 import javax.annotation.concurrent.NotThreadSafe;
29 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
33 import org.opendaylight.mdsal.dom.store.inmemory.DOMDataTreeShardWriteTransaction;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 @NotThreadSafe
40 final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAwareTransaction {
41     private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeWriteTransaction.class);
42     private static final TransactionCommitFailedExceptionMapper SUBMIT_FAILED_MAPPER =
43             TransactionCommitFailedExceptionMapper.create("submit");
44     private static final AtomicLong COUNTER = new AtomicLong();
45
46     private final Map<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> transactions;
47     private final ShardedDOMDataTreeProducer producer;
48     private final ProducerLayout layout;
49     private final String identifier;
50
51     private final SettableFuture<Void> future = SettableFuture.create();
52     private final CheckedFuture<Void, TransactionCommitFailedException> submitFuture =
53             Futures.makeChecked(future, SUBMIT_FAILED_MAPPER);
54
55     @GuardedBy("this")
56     private boolean closed =  false;
57
58     @GuardedBy("this")
59     private DOMDataTreeWriteCursor openCursor;
60
61     ShardedDOMDataTreeWriteTransaction(final ShardedDOMDataTreeProducer producer,
62         final Map<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> transactions, final ProducerLayout layout) {
63         this.producer = Preconditions.checkNotNull(producer);
64         this.transactions = ImmutableMap.copyOf(transactions);
65         this.layout = Preconditions.checkNotNull(layout);
66         this.identifier = "SHARDED-DOM-" + COUNTER.getAndIncrement();
67         LOG.debug("Created new transaction {}", identifier);
68     }
69
70     private DOMDataTreeShardWriteTransaction lookup(final DOMDataTreeIdentifier prefix) {
71         for (final Entry<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> e : transactions.entrySet()) {
72             if (e.getKey().contains(prefix)) {
73                 Preconditions.checkArgument(!producer.isDelegatedToChild(prefix),
74                     "Path %s is delegated to child producer.", prefix);
75                 return e.getValue();
76             }
77         }
78
79         throw new IllegalArgumentException(String.format("Path %s is not accessible from transaction %s",
80                 prefix, this));
81     }
82
83     @Override
84     public String getIdentifier() {
85         return identifier;
86     }
87
88     @Override
89     public synchronized boolean cancel() {
90         if (closed) {
91             return false;
92         }
93
94         LOG.debug("Cancelling transaction {}", identifier);
95         if (openCursor != null) {
96             openCursor.close();
97         }
98         for (final DOMDataTreeShardWriteTransaction tx : transactions.values()) {
99             tx.close();
100         }
101
102         closed = true;
103         producer.cancelTransaction(this);
104         return true;
105     }
106
107     @Override
108     public synchronized DOMDataTreeWriteCursor createCursor(final DOMDataTreeIdentifier prefix) {
109         Preconditions.checkState(!closed, "Transaction is closed already");
110         Preconditions.checkState(openCursor == null, "There is still a cursor open");
111         final DOMDataTreeShardWriteTransaction lookup = lookup(prefix);
112         openCursor = new DelegatingCursor(lookup.createCursor(prefix), prefix);
113         return openCursor;
114     }
115
116     @Override
117     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
118         Preconditions.checkState(!closed, "Transaction %s is already closed", identifier);
119         Preconditions.checkState(openCursor == null, "Cannot submit transaction while there is a cursor open");
120
121         producer.transactionSubmitted(this);
122         return submitFuture;
123     }
124
125     void doSubmit(final Consumer<ShardedDOMDataTreeWriteTransaction> success,
126             final BiConsumer<ShardedDOMDataTreeWriteTransaction, Throwable> failure) {
127
128         final ListenableFuture<List<Void>> listListenableFuture = Futures.allAsList(
129             transactions.values().stream().map(tx -> {
130                 LOG.debug("Readying tx {}", identifier);
131                 tx.ready();
132                 return tx.submit();
133             }).collect(Collectors.toList()));
134
135         Futures.addCallback(listListenableFuture, new FutureCallback<List<Void>>() {
136             @Override
137             public void onSuccess(final List<Void> result) {
138                 success.accept(ShardedDOMDataTreeWriteTransaction.this);
139             }
140
141             @Override
142             public void onFailure(final Throwable exp) {
143                 failure.accept(ShardedDOMDataTreeWriteTransaction.this, exp);
144             }
145         });
146     }
147
148     void onTransactionSuccess(final Void result) {
149         future.set(result);
150     }
151
152     void onTransactionFailure(final Throwable throwable) {
153         future.setException(throwable);
154     }
155
156     synchronized void cursorClosed() {
157         openCursor = null;
158     }
159
160     private class DelegatingCursor implements DOMDataTreeWriteCursor {
161         private final Deque<PathArgument> path = new ArrayDeque<>();
162         private final DOMDataTreeWriteCursor delegate;
163         private final DOMDataTreeIdentifier rootPosition;
164
165         DelegatingCursor(final DOMDataTreeWriteCursor delegate, final DOMDataTreeIdentifier rootPosition) {
166             this.delegate = Preconditions.checkNotNull(delegate);
167             this.rootPosition = Preconditions.checkNotNull(rootPosition);
168             path.addAll(rootPosition.getRootIdentifier().getPathArguments());
169         }
170
171         @Override
172         public void enter(@Nonnull final PathArgument child) {
173             checkAvailable(child);
174             path.push(child);
175             delegate.enter(child);
176         }
177
178         @Override
179         public void enter(@Nonnull final PathArgument... path) {
180             for (final PathArgument pathArgument : path) {
181                 enter(pathArgument);
182             }
183         }
184
185         @Override
186         public void enter(@Nonnull final Iterable<PathArgument> path) {
187             for (final PathArgument pathArgument : path) {
188                 enter(pathArgument);
189             }
190         }
191
192         @Override
193         public void exit() {
194             path.pop();
195             delegate.exit();
196         }
197
198         @Override
199         public void exit(final int depth) {
200             for (int i = 0; i < depth; i++) {
201                 path.pop();
202             }
203             delegate.exit(depth);
204         }
205
206         @Override
207         public void close() {
208             int depthEntered = path.size() - rootPosition.getRootIdentifier().getPathArguments().size();
209             if (depthEntered > 0) {
210                 // clean up existing modification cursor in case this tx will be reused for batching
211                 delegate.exit(depthEntered);
212             }
213
214             delegate.close();
215             cursorClosed();
216         }
217
218         @Override
219         public void delete(final PathArgument child) {
220             checkAvailable(child);
221             delegate.delete(child);
222         }
223
224         @Override
225         public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
226             checkAvailable(child);
227             delegate.merge(child, data);
228         }
229
230         @Override
231         public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
232             checkAvailable(child);
233             delegate.write(child, data);
234         }
235
236         void checkAvailable(final PathArgument child) {
237             layout.checkAvailable(path, child);
238         }
239     }
240
241     ProducerLayout getLayout() {
242         return layout;
243     }
244 }