2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
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;
34 * Factory for creating local and remote TransactionContext instances. Maintains a cache of known local
35 * transaction factories.
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");
43 private final ConcurrentMap<String, F> knownLocal = new ConcurrentHashMap<>();
44 private final LocalHistoryIdentifier historyId;
45 private final ActorContext actorContext;
47 // Used via TX_COUNTER_UPDATER
48 @SuppressWarnings("unused")
49 private volatile long nextTx;
51 protected AbstractTransactionContextFactory(final ActorContext actorContext,
52 final LocalHistoryIdentifier historyId) {
53 this.actorContext = Preconditions.checkNotNull(actorContext);
54 this.historyId = Preconditions.checkNotNull(historyId);
57 final ActorContext getActorContext() {
61 final LocalHistoryIdentifier getHistoryId() {
65 private TransactionContext maybeCreateLocalTransactionContext(final TransactionProxy parent, final String shardName) {
66 final LocalTransactionFactory local = knownLocal.get(shardName);
68 LOG.debug("Tx {} - Creating local component for shard {} using factory {}", parent.getIdentifier(),
72 return createLocalTransactionContext(local, parent);
73 } catch(Exception e) {
74 return new NoOpTransactionContext(e, parent.getIdentifier());
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);
88 updateShardInfo(shardName, primaryShardInfo);
91 TransactionContext localContext = maybeCreateLocalTransactionContext(parent, shardName);
92 if(localContext != null) {
93 transactionContextWrapper.executePriorTransactionOperations(localContext);
95 RemoteTransactionContextSupport remote = new RemoteTransactionContextSupport(transactionContextWrapper,
97 remote.setPrimaryShard(primaryShardInfo);
100 onTransactionContextCreated(parent.getIdentifier());
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);
109 transactionContextWrapper.executePriorTransactionOperations(new NoOpTransactionContext(failure,
110 parent.getIdentifier()));
112 onTransactionContextCreated(parent.getIdentifier());
116 final TransactionContextWrapper newTransactionContextWrapper(final TransactionProxy parent, final String shardName) {
117 final TransactionContextWrapper transactionContextWrapper =
118 new TransactionContextWrapper(parent.getIdentifier(), actorContext);
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);
126 onFindPrimaryShardFailure(maybe.failed().get(), parent, shardName, transactionContextWrapper);
129 findPrimaryFuture.onComplete(new OnComplete<PrimaryShardInfo>() {
131 public void onComplete(final Throwable failure, final PrimaryShardInfo primaryShardInfo) {
132 if (failure == null) {
133 onFindPrimaryShardSuccess(primaryShardInfo, parent, shardName, transactionContextWrapper);
135 onFindPrimaryShardFailure(failure, parent, shardName, transactionContextWrapper);
138 }, actorContext.getClientDispatcher());
141 return transactionContextWrapper;
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);
150 F factory = factoryForShard(shardName, primaryShardInfo.getPrimaryShardActor(), maybeDataTree.get());
151 knownLocal.putIfAbsent(shardName, factory);
153 } else if(knownLocal.containsKey(shardName)) {
154 LOG.debug("Shard {} invalidating local data tree", shardName);
156 knownLocal.remove(shardName);
160 protected final MemberName getMemberName() {
161 return historyId.getClientId().getFrontendId().getMemberName();
165 * Create an identifier for the next TransactionProxy attached to this component
167 * @return Transaction identifier, may not be null.
169 protected final TransactionIdentifier nextIdentifier() {
170 return new TransactionIdentifier(historyId, TX_COUNTER_UPDATER.getAndIncrement(this));
174 * Find the primary shard actor.
176 * @param shardName Shard name
177 * @return Future containing shard information.
179 protected abstract Future<PrimaryShardInfo> findPrimaryShard(@Nonnull String shardName,
180 @Nonnull TransactionIdentifier txId);
183 * Create local transaction factory for specified shard, backed by specified shard leader
184 * and data tree instance.
188 * @param dataTree Backing data tree instance. The data tree may only be accessed in
190 * @return Transaction factory for local use.
192 protected abstract F factoryForShard(String shardName, ActorSelection shardLeader, DataTree dataTree);
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
199 protected abstract <T> void onTransactionReady(@Nonnull TransactionIdentifier transaction, @Nonnull Collection<Future<T>> cohortFutures);
202 * Callback invoked when the internal TransactionContext has been created for a transaction.
204 * @param transactionId the ID of the transaction.
206 protected abstract void onTransactionContextCreated(@Nonnull TransactionIdentifier transactionId);
208 private static TransactionContext createLocalTransactionContext(final LocalTransactionFactory factory,
209 final TransactionProxy parent) {
211 switch(parent.getType()) {
213 final DOMStoreReadTransaction readOnly = factory.newReadOnlyTransaction(parent.getIdentifier());
214 return new LocalTransactionContext(readOnly, parent.getIdentifier(), factory) {
216 protected DOMStoreWriteTransaction getWriteDelegate() {
217 throw new UnsupportedOperationException();
221 protected DOMStoreReadTransaction getReadDelegate() {
226 final DOMStoreReadWriteTransaction readWrite = factory.newReadWriteTransaction(parent.getIdentifier());
227 return new LocalTransactionContext(readWrite, parent.getIdentifier(), factory) {
229 protected DOMStoreWriteTransaction getWriteDelegate() {
234 protected DOMStoreReadTransaction getReadDelegate() {
239 final DOMStoreWriteTransaction writeOnly = factory.newWriteOnlyTransaction(parent.getIdentifier());
240 return new LocalTransactionContext(writeOnly, parent.getIdentifier(), factory) {
242 protected DOMStoreWriteTransaction getWriteDelegate() {
247 protected DOMStoreReadTransaction getReadDelegate() {
248 throw new UnsupportedOperationException();
252 throw new IllegalArgumentException("Invalid transaction type: " + parent.getType());