Add cursor lookup fast-path
[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         final DOMDataTreeShardWriteTransaction fast = transactions.get(prefix);
72         if (fast != null) {
73             return fast;
74         }
75
76         LOG.debug("Prefix {} not found in available subtrees {}, fallback to slow path", prefix, transactions.keySet());
77         for (final Entry<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> e : transactions.entrySet()) {
78             if (e.getKey().contains(prefix)) {
79                 return e.getValue();
80             }
81         }
82
83         return null;
84     }
85
86     @Override
87     public String getIdentifier() {
88         return identifier;
89     }
90
91     @Override
92     public synchronized boolean cancel() {
93         if (closed) {
94             return false;
95         }
96
97         LOG.debug("Cancelling transaction {}", identifier);
98         if (openCursor != null) {
99             openCursor.close();
100         }
101         for (final DOMDataTreeShardWriteTransaction tx : transactions.values()) {
102             tx.close();
103         }
104
105         closed = true;
106         producer.cancelTransaction(this);
107         return true;
108     }
109
110     @Override
111     public synchronized DOMDataTreeWriteCursor createCursor(final DOMDataTreeIdentifier prefix) {
112         Preconditions.checkState(!closed, "Transaction is closed already");
113         Preconditions.checkState(openCursor == null, "There is still a cursor open");
114         Preconditions.checkArgument(!producer.isDelegatedToChild(prefix), "Path %s is delegated to child producer.",
115             prefix);
116
117         final DOMDataTreeShardWriteTransaction lookup = lookup(prefix);
118         Preconditions.checkArgument(lookup != null, "Path %s is not accessible from transaction %s", prefix, this);
119
120         openCursor = new DelegatingCursor(lookup.createCursor(prefix), prefix);
121         return openCursor;
122     }
123
124     @Override
125     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
126         Preconditions.checkState(!closed, "Transaction %s is already closed", identifier);
127         Preconditions.checkState(openCursor == null, "Cannot submit transaction while there is a cursor open");
128
129         producer.transactionSubmitted(this);
130         return submitFuture;
131     }
132
133     void doSubmit(final Consumer<ShardedDOMDataTreeWriteTransaction> success,
134             final BiConsumer<ShardedDOMDataTreeWriteTransaction, Throwable> failure) {
135
136         final ListenableFuture<List<Void>> listListenableFuture = Futures.allAsList(
137             transactions.values().stream().map(tx -> {
138                 LOG.debug("Readying tx {}", identifier);
139                 tx.ready();
140                 return tx.submit();
141             }).collect(Collectors.toList()));
142
143         Futures.addCallback(listListenableFuture, new FutureCallback<List<Void>>() {
144             @Override
145             public void onSuccess(final List<Void> result) {
146                 success.accept(ShardedDOMDataTreeWriteTransaction.this);
147             }
148
149             @Override
150             public void onFailure(final Throwable exp) {
151                 failure.accept(ShardedDOMDataTreeWriteTransaction.this, exp);
152             }
153         });
154     }
155
156     void onTransactionSuccess(final Void result) {
157         future.set(result);
158     }
159
160     void onTransactionFailure(final Throwable throwable) {
161         future.setException(throwable);
162     }
163
164     synchronized void cursorClosed() {
165         openCursor = null;
166     }
167
168     private class DelegatingCursor implements DOMDataTreeWriteCursor {
169         private final Deque<PathArgument> path = new ArrayDeque<>();
170         private final DOMDataTreeWriteCursor delegate;
171         private final DOMDataTreeIdentifier rootPosition;
172
173         DelegatingCursor(final DOMDataTreeWriteCursor delegate, final DOMDataTreeIdentifier rootPosition) {
174             this.delegate = Preconditions.checkNotNull(delegate);
175             this.rootPosition = Preconditions.checkNotNull(rootPosition);
176             path.addAll(rootPosition.getRootIdentifier().getPathArguments());
177         }
178
179         @Override
180         public void enter(@Nonnull final PathArgument child) {
181             checkAvailable(child);
182             delegate.enter(child);
183             path.push(child);
184         }
185
186         @Override
187         public void enter(@Nonnull final PathArgument... path) {
188             for (final PathArgument pathArgument : path) {
189                 enter(pathArgument);
190             }
191         }
192
193         @Override
194         public void enter(@Nonnull final Iterable<PathArgument> path) {
195             for (final PathArgument pathArgument : path) {
196                 enter(pathArgument);
197             }
198         }
199
200         @Override
201         public void exit() {
202             delegate.exit();
203             path.pop();
204         }
205
206         @Override
207         public void exit(final int depth) {
208             delegate.exit(depth);
209             for (int i = 0; i < depth; i++) {
210                 path.pop();
211             }
212         }
213
214         @Override
215         public void close() {
216             int depthEntered = path.size() - rootPosition.getRootIdentifier().getPathArguments().size();
217             if (depthEntered > 0) {
218                 // clean up existing modification cursor in case this tx will be reused for batching
219                 delegate.exit(depthEntered);
220             }
221
222             delegate.close();
223             cursorClosed();
224         }
225
226         @Override
227         public void delete(final PathArgument child) {
228             checkAvailable(child);
229             delegate.delete(child);
230         }
231
232         @Override
233         public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
234             checkAvailable(child);
235             delegate.merge(child, data);
236         }
237
238         @Override
239         public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
240             checkAvailable(child);
241             delegate.write(child, data);
242         }
243
244         void checkAvailable(final PathArgument child) {
245             layout.checkAvailable(path, child);
246         }
247     }
248
249     ProducerLayout getLayout() {
250         return layout;
251     }
252 }