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