d11ea898dec1806595e79363c7fc5ff201c46869
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / ShardedDOMDataTreeProducer.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.BiMap;
12 import com.google.common.collect.ImmutableBiMap;
13 import com.google.common.collect.ImmutableBiMap.Builder;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.LinkedList;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Queue;
23 import java.util.Set;
24 import javax.annotation.concurrent.GuardedBy;
25 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
26 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerBusyException;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeShard;
30 import org.opendaylight.mdsal.dom.api.DOMDataWriteTransaction;
31 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
32 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
33 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 final class ShardedDOMDataTreeProducer implements DOMDataTreeProducer {
38     private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeProducer.class);
39     private final BiMap<DOMDataTreeShard, DOMStoreTransactionChain> shardToChain;
40     private final Map<DOMDataTreeIdentifier, DOMDataTreeShard> idToShard;
41     private final ShardedDOMDataTree dataTree;
42
43     @GuardedBy("this")
44     private Map<DOMDataTreeIdentifier, DOMDataTreeProducer> children = Collections.emptyMap();
45     @GuardedBy("this")
46     private DOMDataWriteTransaction openTx;
47     @GuardedBy("this")
48     private boolean closed;
49
50     ShardedDOMDataTreeProducer(final ShardedDOMDataTree dataTree, final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap, final Set<DOMDataTreeShard> shards) {
51         this.dataTree = Preconditions.checkNotNull(dataTree);
52
53         // Create shard -> chain map
54         final Builder<DOMDataTreeShard, DOMStoreTransactionChain> cb = ImmutableBiMap.builder();
55         final Queue<Exception> es = new LinkedList<>();
56
57         for (final DOMDataTreeShard s : shards) {
58             if (s instanceof DOMStore) {
59                 try {
60                     final DOMStoreTransactionChain c = ((DOMStore)s).createTransactionChain();
61                     LOG.trace("Using DOMStore chain {} to access shard {}", c, s);
62                     cb.put(s, c);
63                 } catch (final Exception e) {
64                     LOG.error("Failed to instantiate chain for shard {}", s, e);
65                     es.add(e);
66                 }
67             } else {
68                 LOG.error("Unhandled shard instance type {}", s.getClass());
69             }
70         }
71         this.shardToChain = cb.build();
72
73         // An error was encountered, close chains and report the error
74         if (shardToChain.size() != shards.size()) {
75             for (final DOMStoreTransactionChain c : shardToChain.values()) {
76                 try {
77                     c.close();
78                 } catch (final Exception e) {
79                     LOG.warn("Exception raised while closing chain {}", c, e);
80                 }
81             }
82
83             final IllegalStateException e = new IllegalStateException("Failed to completely allocate contexts", es.poll());
84             while (!es.isEmpty()) {
85                 e.addSuppressed(es.poll());
86             }
87
88             throw e;
89         }
90
91         idToShard = ImmutableMap.copyOf(shardMap);
92     }
93
94     @Override
95     public synchronized DOMDataWriteTransaction createTransaction(final boolean isolated) {
96         Preconditions.checkState(!closed, "Producer is already closed");
97         Preconditions.checkState(openTx == null, "Transaction %s is still open", openTx);
98
99         // Allocate backing transactions
100         final Map<DOMDataTreeShard, DOMStoreWriteTransaction> shardToTx = new HashMap<>();
101         for (final Entry<DOMDataTreeShard, DOMStoreTransactionChain> e : shardToChain.entrySet()) {
102             shardToTx.put(e.getKey(), e.getValue().newWriteOnlyTransaction());
103         }
104
105         // Create the ID->transaction map
106         final ImmutableMap.Builder<DOMDataTreeIdentifier, DOMStoreWriteTransaction> b = ImmutableMap.builder();
107         for (final Entry<DOMDataTreeIdentifier, DOMDataTreeShard> e : idToShard.entrySet()) {
108             b.put(e.getKey(), shardToTx.get(e.getValue()));
109         }
110
111         final ShardedDOMDataWriteTransaction ret = new ShardedDOMDataWriteTransaction(this, b.build());
112         openTx = ret;
113         return ret;
114     }
115
116     @GuardedBy("this")
117     private boolean haveSubtree(final DOMDataTreeIdentifier subtree) {
118         for (final DOMDataTreeIdentifier i : idToShard.keySet()) {
119             if (i.contains(subtree)) {
120                 return true;
121             }
122         }
123
124         return false;
125     }
126
127     @GuardedBy("this")
128     private DOMDataTreeProducer lookupChild(final DOMDataTreeIdentifier s) {
129         for (final Entry<DOMDataTreeIdentifier, DOMDataTreeProducer> e : children.entrySet()) {
130             if (e.getKey().contains(s)) {
131                 return e.getValue();
132             }
133         }
134
135         return null;
136     }
137
138     @Override
139     public synchronized DOMDataTreeProducer createProducer(final Collection<DOMDataTreeIdentifier> subtrees) {
140         Preconditions.checkState(!closed, "Producer is already closed");
141         Preconditions.checkState(openTx == null, "Transaction %s is still open", openTx);
142
143         for (final DOMDataTreeIdentifier s : subtrees) {
144             // Check if the subtree was visible at any time
145             Preconditions.checkArgument(haveSubtree(s), "Subtree %s was never available in producer %s", s, this);
146             // Check if the subtree has not been delegated to a child
147             final DOMDataTreeProducer child = lookupChild(s);
148             Preconditions.checkArgument(child == null, "Subtree %s is delegated to child producer %s", s, child);
149
150             // Check if part of the requested subtree is not delegated to a child.
151             for (final DOMDataTreeIdentifier c : children.keySet()) {
152                 if (s.contains(c)) {
153                     throw new IllegalArgumentException(String.format("Subtree %s cannot be delegated as it is superset of already-delegated %s", s, c));
154                 }
155             }
156         }
157
158         final DOMDataTreeProducer ret = dataTree.createProducer(this, subtrees);
159         final ImmutableMap.Builder<DOMDataTreeIdentifier, DOMDataTreeProducer> cb = ImmutableMap.builder();
160         cb.putAll(children);
161         for (final DOMDataTreeIdentifier s : subtrees) {
162             cb.put(s, ret);
163         }
164
165         children = cb.build();
166         return ret;
167     }
168
169     boolean isDelegatedToChild(DOMDataTreeIdentifier path) {
170         for (final DOMDataTreeIdentifier c : children.keySet()) {
171             if (c.contains(path)) {
172                 return true;
173             }
174         }
175         return false;
176     }
177
178
179     @Override
180     public synchronized void close() throws DOMDataTreeProducerException {
181         if (!closed) {
182             if (openTx != null) {
183                 throw new DOMDataTreeProducerBusyException(String.format("Transaction %s is still open", openTx));
184             }
185
186             closed = true;
187             dataTree.destroyProducer(this);
188         }
189     }
190
191     static DOMDataTreeProducer create(final ShardedDOMDataTree dataTree, final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
192         /*
193          * FIXME: we do not allow multiple multiple shards in a producer because we do not implement the
194          *        synchronization primitives yet
195          */
196         final Set<DOMDataTreeShard> shards = ImmutableSet.copyOf(shardMap.values());
197         if (shards.size() > 1) {
198             throw new UnsupportedOperationException("Cross-shard producers are not supported yet");
199         }
200
201         return new ShardedDOMDataTreeProducer(dataTree, shardMap, shards);
202     }
203
204     Set<DOMDataTreeIdentifier> getSubtrees() {
205         return idToShard.keySet();
206     }
207
208     synchronized void cancelTransaction(final ShardedDOMDataWriteTransaction transaction) {
209         if (!openTx.equals(transaction)) {
210             LOG.warn("Transaction {} is not open in producer {}", transaction, this);
211             return;
212         }
213
214         LOG.debug("Transaction {} cancelled", transaction);
215         openTx = null;
216     }
217
218     synchronized void transactionSubmitted(ShardedDOMDataWriteTransaction transaction) {
219         Preconditions.checkState(openTx.equals(transaction));
220         openTx = null;
221     }
222 }