Merge "Fix the build errors due to the class change of InstanceIdentifier to YangInst...
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / TransactionProxy.java
1 /*
2  * Copyright (c) 2014 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
9 package org.opendaylight.controller.cluster.datastore;
10
11 import akka.actor.ActorPath;
12 import akka.actor.ActorSelection;
13 import com.google.common.base.Optional;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ListenableFutureTask;
16 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
17 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
18 import org.opendaylight.controller.cluster.datastore.messages.DeleteData;
19 import org.opendaylight.controller.cluster.datastore.messages.MergeData;
20 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
21 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
22 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
23 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
24 import org.opendaylight.controller.cluster.datastore.messages.WriteData;
25 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
26 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
27 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.atomic.AtomicLong;
41
42 /**
43  * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
44  * <p>
45  * Creating a transaction on the consumer side will create one instance of a transaction proxy. If during
46  * the transaction reads and writes are done on data that belongs to different shards then a separate transaction will
47  * be created on each of those shards by the TransactionProxy
48  *</p>
49  * <p>
50  * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
51  * shards will be executed.
52  * </p>
53  */
54 public class TransactionProxy implements DOMStoreReadWriteTransaction {
55     public enum TransactionType {
56         READ_ONLY,
57         WRITE_ONLY,
58         READ_WRITE
59     }
60
61     private static final AtomicLong counter = new AtomicLong();
62
63     private final TransactionType transactionType;
64     private final ActorContext actorContext;
65     private final Map<String, ActorSelection> remoteTransactionPaths = new HashMap<>();
66     private final String identifier;
67     private final ExecutorService executor;
68     private final SchemaContext schemaContext;
69
70     public TransactionProxy(
71         ActorContext actorContext,
72         TransactionType transactionType,
73         ExecutorService executor,
74         SchemaContext schemaContext
75         ) {
76
77         this.identifier = "txn-" + counter.getAndIncrement();
78         this.transactionType = transactionType;
79         this.actorContext = actorContext;
80         this.executor = executor;
81         this.schemaContext = schemaContext;
82
83
84     }
85
86     @Override
87     public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
88
89         createTransactionIfMissing(actorContext, path);
90
91         final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
92
93         Callable<Optional<NormalizedNode<?,?>>> call = new Callable() {
94
95             @Override public Optional<NormalizedNode<?,?>> call() throws Exception {
96                 Object response = actorContext
97                     .executeRemoteOperation(remoteTransaction, new ReadData(path).toSerializable(),
98                         ActorContext.ASK_DURATION);
99                 if(response.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)){
100                     ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext,path, response);
101                     if(reply.getNormalizedNode() == null){
102                         return Optional.absent();
103                     }
104                     //FIXME : A cast should not be required here ???
105                     return (Optional<NormalizedNode<?, ?>>) Optional.of(reply.getNormalizedNode());
106                 }
107
108                 return Optional.absent();
109             }
110         };
111
112         ListenableFutureTask<Optional<NormalizedNode<?, ?>>>
113             future = ListenableFutureTask.create(call);
114
115         executor.submit(future);
116
117         return future;
118     }
119
120     @Override
121     public void write(InstanceIdentifier path, NormalizedNode<?, ?> data) {
122
123         createTransactionIfMissing(actorContext, path);
124
125         final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
126         remoteTransaction.tell(new WriteData(path, data, schemaContext).toSerializable(), null);
127     }
128
129     @Override
130     public void merge(InstanceIdentifier path, NormalizedNode<?, ?> data) {
131
132         createTransactionIfMissing(actorContext, path);
133
134         final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
135         remoteTransaction.tell(new MergeData(path, data, schemaContext).toSerializable(), null);
136     }
137
138     @Override
139     public void delete(InstanceIdentifier path) {
140
141         createTransactionIfMissing(actorContext, path);
142
143         final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
144         remoteTransaction.tell(new DeleteData(path).toSerializable(), null);
145     }
146
147     @Override
148     public DOMStoreThreePhaseCommitCohort ready() {
149         List<ActorPath> cohortPaths = new ArrayList<>();
150
151         for(ActorSelection remoteTransaction : remoteTransactionPaths.values()) {
152             Object result = actorContext.executeRemoteOperation(remoteTransaction,
153                 new ReadyTransaction(),
154                 ActorContext.ASK_DURATION
155             );
156
157             if(result instanceof ReadyTransactionReply){
158                 ReadyTransactionReply reply = (ReadyTransactionReply) result;
159                 cohortPaths.add(reply.getCohortPath());
160             }
161         }
162
163         return new ThreePhaseCommitCohortProxy(actorContext, cohortPaths, identifier, executor);
164     }
165
166     @Override
167     public Object getIdentifier() {
168         return this.identifier;
169     }
170
171     @Override
172     public void close() {
173         for(ActorSelection remoteTransaction : remoteTransactionPaths.values()) {
174             remoteTransaction.tell(new CloseTransaction(), null);
175         }
176     }
177
178     private ActorSelection remoteTransactionFromIdentifier(InstanceIdentifier path){
179         String shardName = shardNameFromIdentifier(path);
180         return remoteTransactionPaths.get(shardName);
181     }
182
183     private String shardNameFromIdentifier(InstanceIdentifier path){
184         return ShardStrategyFactory.getStrategy(path).findShard(path);
185     }
186
187     private void createTransactionIfMissing(ActorContext actorContext, InstanceIdentifier path) {
188         String shardName = ShardStrategyFactory.getStrategy(path).findShard(path);
189
190         ActorSelection actorSelection =
191             remoteTransactionPaths.get(shardName);
192
193         if(actorSelection != null){
194             // A transaction already exists with that shard
195             return;
196         }
197
198         Object response = actorContext.executeShardOperation(shardName, new CreateTransaction(identifier), ActorContext.ASK_DURATION);
199         if(response instanceof CreateTransactionReply){
200             CreateTransactionReply reply = (CreateTransactionReply) response;
201             remoteTransactionPaths.put(shardName, actorContext.actorSelection(reply.getTransactionActorPath()));
202         }
203     }
204
205
206 }