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