Encapsulate ShardedDOMDataTreeProducer layout
[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     CheckedFuture<Void, TransactionCommitFailedException> doSubmit(
126             final Consumer<ShardedDOMDataTreeWriteTransaction> success,
127             final BiConsumer<ShardedDOMDataTreeWriteTransaction, Throwable> failure) {
128
129         final ListenableFuture<List<Void>> listListenableFuture = Futures.allAsList(
130             transactions.values().stream().map(tx -> {
131                 LOG.debug("Readying tx {}", identifier);
132                 tx.ready();
133                 return tx.submit();
134             }).collect(Collectors.toList()));
135
136         final SettableFuture<Void> ret = SettableFuture.create();
137         Futures.addCallback(listListenableFuture, new FutureCallback<List<Void>>() {
138             @Override
139             public void onSuccess(final List<Void> result) {
140                 success.accept(ShardedDOMDataTreeWriteTransaction.this);
141                 ret.set(null);
142             }
143
144             @Override
145             public void onFailure(final Throwable exp) {
146                 failure.accept(ShardedDOMDataTreeWriteTransaction.this, exp);
147                 ret.setException(exp);
148             }
149         });
150
151         return Futures.makeChecked(ret, SUBMIT_FAILED_MAPPER);
152     }
153
154     void onTransactionSuccess(final Void result) {
155         future.set(result);
156     }
157
158     void onTransactionFailure(final Throwable throwable) {
159         future.setException(throwable);
160     }
161
162     synchronized void cursorClosed() {
163         openCursor = null;
164     }
165
166     private class DelegatingCursor implements DOMDataTreeWriteCursor {
167         private final Deque<PathArgument> path = new ArrayDeque<>();
168         private final DOMDataTreeWriteCursor delegate;
169         private final DOMDataTreeIdentifier rootPosition;
170
171         DelegatingCursor(final DOMDataTreeWriteCursor delegate, final DOMDataTreeIdentifier rootPosition) {
172             this.delegate = Preconditions.checkNotNull(delegate);
173             this.rootPosition = Preconditions.checkNotNull(rootPosition);
174             path.addAll(rootPosition.getRootIdentifier().getPathArguments());
175         }
176
177         @Override
178         public void enter(@Nonnull final PathArgument child) {
179             checkAvailable(child);
180             path.push(child);
181             delegate.enter(child);
182         }
183
184         @Override
185         public void enter(@Nonnull final PathArgument... path) {
186             for (final PathArgument pathArgument : path) {
187                 enter(pathArgument);
188             }
189         }
190
191         @Override
192         public void enter(@Nonnull final Iterable<PathArgument> path) {
193             for (final PathArgument pathArgument : path) {
194                 enter(pathArgument);
195             }
196         }
197
198         @Override
199         public void exit() {
200             path.pop();
201             delegate.exit();
202         }
203
204         @Override
205         public void exit(final int depth) {
206             for (int i = 0; i < depth; i++) {
207                 path.pop();
208             }
209             delegate.exit(depth);
210         }
211
212         @Override
213         public void close() {
214             int depthEntered = path.size() - rootPosition.getRootIdentifier().getPathArguments().size();
215             if (depthEntered > 0) {
216                 // clean up existing modification cursor in case this tx will be reused for batching
217                 delegate.exit(depthEntered);
218             }
219
220             delegate.close();
221             cursorClosed();
222         }
223
224         @Override
225         public void delete(final PathArgument child) {
226             checkAvailable(child);
227             delegate.delete(child);
228         }
229
230         @Override
231         public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
232             checkAvailable(child);
233             delegate.merge(child, data);
234         }
235
236         @Override
237         public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
238             checkAvailable(child);
239             delegate.write(child, data);
240         }
241
242         void checkAvailable(final PathArgument child) {
243             layout.checkAvailable(path, child);
244         }
245     }
246
247     ProducerLayout getLayout() {
248         return layout;
249     }
250 }