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