Fix incorrect remove call in ShardManager
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / AbstractTransactionContextFactory.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.controller.cluster.datastore;
9
10 import akka.actor.ActorSelection;
11 import akka.dispatch.OnComplete;
12 import com.google.common.base.Preconditions;
13 import java.util.Collection;
14 import java.util.Optional;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.ConcurrentMap;
17 import java.util.concurrent.atomic.AtomicLongFieldUpdater;
18 import javax.annotation.Nonnull;
19 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
20 import org.opendaylight.controller.cluster.access.concepts.MemberName;
21 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
22 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
23 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
24 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
25 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
26 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import scala.concurrent.Future;
31 import scala.util.Try;
32
33 /**
34  * Factory for creating local and remote TransactionContext instances. Maintains a cache of known local
35  * transaction factories.
36  */
37 abstract class AbstractTransactionContextFactory<F extends LocalTransactionFactory> implements AutoCloseable {
38     private static final Logger LOG = LoggerFactory.getLogger(AbstractTransactionContextFactory.class);
39     @SuppressWarnings("rawtypes")
40     private static final AtomicLongFieldUpdater<AbstractTransactionContextFactory> TX_COUNTER_UPDATER =
41             AtomicLongFieldUpdater.newUpdater(AbstractTransactionContextFactory.class, "nextTx");
42
43     private final ConcurrentMap<String, F> knownLocal = new ConcurrentHashMap<>();
44     private final LocalHistoryIdentifier historyId;
45     private final ActorContext actorContext;
46
47     // Used via TX_COUNTER_UPDATER
48     @SuppressWarnings("unused")
49     private volatile long nextTx;
50
51     protected AbstractTransactionContextFactory(final ActorContext actorContext,
52             final LocalHistoryIdentifier historyId) {
53         this.actorContext = Preconditions.checkNotNull(actorContext);
54         this.historyId = Preconditions.checkNotNull(historyId);
55     }
56
57     final ActorContext getActorContext() {
58         return actorContext;
59     }
60
61     final LocalHistoryIdentifier getHistoryId() {
62         return historyId;
63     }
64
65     private TransactionContext maybeCreateLocalTransactionContext(final TransactionProxy parent, final String shardName) {
66         final LocalTransactionFactory local = knownLocal.get(shardName);
67         if (local != null) {
68             LOG.debug("Tx {} - Creating local component for shard {} using factory {}", parent.getIdentifier(),
69                 shardName, local);
70
71             try {
72                 return createLocalTransactionContext(local, parent);
73             } catch(Exception e) {
74                 return new NoOpTransactionContext(e, parent.getIdentifier());
75             }
76         }
77
78         return null;
79     }
80
81     private void onFindPrimaryShardSuccess(PrimaryShardInfo primaryShardInfo, TransactionProxy parent,
82             String shardName, TransactionContextWrapper transactionContextWrapper) {
83         if(LOG.isDebugEnabled()) {
84             LOG.debug("Tx {}: Found primary {} for shard {}", parent.getIdentifier(),
85                     primaryShardInfo.getPrimaryShardActor(), shardName);
86         }
87
88         updateShardInfo(shardName, primaryShardInfo);
89
90         try {
91             TransactionContext localContext = maybeCreateLocalTransactionContext(parent, shardName);
92             if(localContext != null) {
93                 transactionContextWrapper.executePriorTransactionOperations(localContext);
94             } else {
95                 RemoteTransactionContextSupport remote = new RemoteTransactionContextSupport(transactionContextWrapper,
96                         parent, shardName);
97                 remote.setPrimaryShard(primaryShardInfo);
98             }
99         } finally {
100             onTransactionContextCreated(parent.getIdentifier());
101         }
102     }
103
104     private void onFindPrimaryShardFailure(Throwable failure, TransactionProxy parent,
105             String shardName, TransactionContextWrapper transactionContextWrapper) {
106         LOG.debug("Tx {}: Find primary for shard {} failed", parent.getIdentifier(), shardName, failure);
107
108         try {
109             transactionContextWrapper.executePriorTransactionOperations(new NoOpTransactionContext(failure,
110                     parent.getIdentifier()));
111         } finally {
112             onTransactionContextCreated(parent.getIdentifier());
113         }
114     }
115
116     final TransactionContextWrapper newTransactionContextWrapper(final TransactionProxy parent, final String shardName) {
117         final TransactionContextWrapper transactionContextWrapper =
118                 new TransactionContextWrapper(parent.getIdentifier(), actorContext);
119
120         Future<PrimaryShardInfo> findPrimaryFuture = findPrimaryShard(shardName, parent.getIdentifier());
121         if(findPrimaryFuture.isCompleted()) {
122             Try<PrimaryShardInfo> maybe = findPrimaryFuture.value().get();
123             if(maybe.isSuccess()) {
124                 onFindPrimaryShardSuccess(maybe.get(), parent, shardName, transactionContextWrapper);
125             } else {
126                 onFindPrimaryShardFailure(maybe.failed().get(), parent, shardName, transactionContextWrapper);
127             }
128         } else {
129             findPrimaryFuture.onComplete(new OnComplete<PrimaryShardInfo>() {
130                 @Override
131                 public void onComplete(final Throwable failure, final PrimaryShardInfo primaryShardInfo) {
132                     if (failure == null) {
133                         onFindPrimaryShardSuccess(primaryShardInfo, parent, shardName, transactionContextWrapper);
134                     } else {
135                         onFindPrimaryShardFailure(failure, parent, shardName, transactionContextWrapper);
136                     }
137                 }
138             }, actorContext.getClientDispatcher());
139         }
140
141         return transactionContextWrapper;
142     }
143
144     private void updateShardInfo(final String shardName, final PrimaryShardInfo primaryShardInfo) {
145         final Optional<DataTree> maybeDataTree = primaryShardInfo.getLocalShardDataTree();
146         if (maybeDataTree.isPresent()) {
147             if(!knownLocal.containsKey(shardName)) {
148                 LOG.debug("Shard {} resolved to local data tree - adding local factory", shardName);
149
150                 F factory = factoryForShard(shardName, primaryShardInfo.getPrimaryShardActor(), maybeDataTree.get());
151                 knownLocal.putIfAbsent(shardName, factory);
152             }
153         } else if(knownLocal.containsKey(shardName)) {
154             LOG.debug("Shard {} invalidating local data tree", shardName);
155
156             knownLocal.remove(shardName);
157         }
158     }
159
160     protected final MemberName getMemberName() {
161         return historyId.getClientId().getFrontendId().getMemberName();
162     }
163
164     /**
165      * Create an identifier for the next TransactionProxy attached to this component
166      * factory.
167      * @return Transaction identifier, may not be null.
168      */
169     protected final TransactionIdentifier nextIdentifier() {
170         return new TransactionIdentifier(historyId, TX_COUNTER_UPDATER.getAndIncrement(this));
171     }
172
173     /**
174      * Find the primary shard actor.
175      *
176      * @param shardName Shard name
177      * @return Future containing shard information.
178      */
179     protected abstract Future<PrimaryShardInfo> findPrimaryShard(@Nonnull String shardName,
180             @Nonnull TransactionIdentifier txId);
181
182     /**
183      * Create local transaction factory for specified shard, backed by specified shard leader
184      * and data tree instance.
185      *
186      * @param shardName
187      * @param shardLeader
188      * @param dataTree Backing data tree instance. The data tree may only be accessed in
189      *                 read-only manner.
190      * @return Transaction factory for local use.
191      */
192     protected abstract F factoryForShard(String shardName, ActorSelection shardLeader, DataTree dataTree);
193
194     /**
195      * Callback invoked from child transactions to push any futures, which need to
196      * be waited for before the next transaction is allocated.
197      * @param cohortFutures Collection of futures
198      */
199     protected abstract <T> void onTransactionReady(@Nonnull TransactionIdentifier transaction, @Nonnull Collection<Future<T>> cohortFutures);
200
201     /**
202      * Callback invoked when the internal TransactionContext has been created for a transaction.
203      *
204      * @param transactionId the ID of the transaction.
205      */
206     protected abstract void onTransactionContextCreated(@Nonnull TransactionIdentifier transactionId);
207
208     private static TransactionContext createLocalTransactionContext(final LocalTransactionFactory factory,
209                                                                     final TransactionProxy parent) {
210
211         switch(parent.getType()) {
212             case READ_ONLY:
213                 final DOMStoreReadTransaction readOnly = factory.newReadOnlyTransaction(parent.getIdentifier());
214                 return new LocalTransactionContext(readOnly, parent.getIdentifier(), factory) {
215                     @Override
216                     protected DOMStoreWriteTransaction getWriteDelegate() {
217                         throw new UnsupportedOperationException();
218                     }
219
220                     @Override
221                     protected DOMStoreReadTransaction getReadDelegate() {
222                         return readOnly;
223                     }
224                 };
225             case READ_WRITE:
226                 final DOMStoreReadWriteTransaction readWrite = factory.newReadWriteTransaction(parent.getIdentifier());
227                 return new LocalTransactionContext(readWrite, parent.getIdentifier(), factory) {
228                     @Override
229                     protected DOMStoreWriteTransaction getWriteDelegate() {
230                         return readWrite;
231                     }
232
233                     @Override
234                     protected DOMStoreReadTransaction getReadDelegate() {
235                         return readWrite;
236                     }
237                 };
238             case WRITE_ONLY:
239                 final DOMStoreWriteTransaction writeOnly = factory.newWriteOnlyTransaction(parent.getIdentifier());
240                 return new LocalTransactionContext(writeOnly, parent.getIdentifier(), factory) {
241                     @Override
242                     protected DOMStoreWriteTransaction getWriteDelegate() {
243                         return writeOnly;
244                     }
245
246                     @Override
247                     protected DOMStoreReadTransaction getReadDelegate() {
248                         throw new UnsupportedOperationException();
249                     }
250                 };
251              default:
252                  throw new IllegalArgumentException("Invalid transaction type: " + parent.getType());
253         }
254     }
255 }