BUG-5280: add AbstractClientConnection
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / LocalProxyTransaction.java
1 /*
2  * Copyright (c) 2016 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.databroker.actors.dds;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.Futures;
15 import java.util.function.Consumer;
16 import javax.annotation.Nullable;
17 import javax.annotation.concurrent.NotThreadSafe;
18 import org.opendaylight.controller.cluster.access.commands.AbortLocalTransactionRequest;
19 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
20 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
22 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
23 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
24 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
25 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
26 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
27 import org.opendaylight.controller.cluster.access.concepts.RequestException;
28 import org.opendaylight.controller.cluster.access.concepts.Response;
29 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
30 import org.opendaylight.controller.cluster.datastore.util.AbstractDataTreeModificationCursor;
31 import org.opendaylight.mdsal.common.api.ReadFailedException;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeModification;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
37 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
38 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * An {@link AbstractProxyTransaction} for dispatching a transaction towards a shard leader which is co-located with
44  * the client instance.
45  *
46  * <p>
47  * It requires a {@link DataTreeSnapshot}, which is used to instantiated a new {@link DataTreeModification}. Operations
48  * are then performed on this modification and once the transaction is submitted, the modification is sent to the shard
49  * leader.
50  *
51  * <p>
52  * This class is not thread-safe as usual with transactions. Since it does not interact with the backend until the
53  * transaction is submitted, at which point this class gets out of the picture, this is not a cause for concern.
54  *
55  * @author Robert Varga
56  */
57 @NotThreadSafe
58 final class LocalProxyTransaction extends AbstractProxyTransaction {
59     private static final Logger LOG = LoggerFactory.getLogger(LocalProxyTransaction.class);
60
61     private final TransactionIdentifier identifier;
62
63     private CursorAwareDataTreeModification modification;
64
65     LocalProxyTransaction(final ProxyHistory parent, final TransactionIdentifier identifier,
66         final CursorAwareDataTreeModification modification) {
67         super(parent);
68         this.identifier = Preconditions.checkNotNull(identifier);
69         this.modification = Preconditions.checkNotNull(modification);
70     }
71
72     @Override
73     public TransactionIdentifier getIdentifier() {
74         return identifier;
75     }
76
77     @Override
78     void doDelete(final YangInstanceIdentifier path) {
79         modification.delete(path);
80     }
81
82     @Override
83     void doMerge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
84         modification.merge(path, data);
85     }
86
87     @Override
88     void doWrite(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
89         modification.write(path, data);
90     }
91
92     @Override
93     CheckedFuture<Boolean, ReadFailedException> doExists(final YangInstanceIdentifier path) {
94         return Futures.immediateCheckedFuture(modification.readNode(path).isPresent());
95     }
96
97     @Override
98     CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(final YangInstanceIdentifier path) {
99         return Futures.immediateCheckedFuture(modification.readNode(path));
100     }
101
102     private RuntimeException abortedException() {
103         return new IllegalStateException("Tracker " + identifier + " has been aborted");
104     }
105
106     private RuntimeException submittedException() {
107         return new IllegalStateException("Tracker " + identifier + " has been submitted");
108     }
109
110     @Override
111     void doAbort() {
112         sendAbort(new AbortLocalTransactionRequest(identifier, localActor()), response -> {
113             LOG.debug("Transaction {} abort completed with {}", identifier, response);
114         });
115     }
116
117     @Override
118     CommitLocalTransactionRequest commitRequest(final boolean coordinated) {
119         final CommitLocalTransactionRequest ret = new CommitLocalTransactionRequest(identifier, localActor(),
120             modification, coordinated);
121         modification = new FailedDataTreeModification(this::submittedException);
122         return ret;
123     }
124
125     @Override
126     void doSeal() {
127         modification.ready();
128     }
129
130     DataTreeSnapshot getSnapshot() {
131         return modification;
132     }
133
134     private void applyModifyTransactionRequest(final ModifyTransactionRequest request,
135             final @Nullable Consumer<Response<?, ?>> callback) {
136         for (TransactionModification mod : request.getModifications()) {
137             if (mod instanceof TransactionWrite) {
138                 modification.write(mod.getPath(), ((TransactionWrite)mod).getData());
139             } else if (mod instanceof TransactionMerge) {
140                 modification.merge(mod.getPath(), ((TransactionMerge)mod).getData());
141             } else if (mod instanceof TransactionDelete) {
142                 modification.delete(mod.getPath());
143             } else {
144                 throw new IllegalArgumentException("Unsupported modification " + mod);
145             }
146         }
147
148         final java.util.Optional<PersistenceProtocol> maybeProtocol = request.getPersistenceProtocol();
149         if (maybeProtocol.isPresent()) {
150             seal();
151             Verify.verify(callback != null, "Request {} has null callback", request);
152
153             switch (maybeProtocol.get()) {
154                 case ABORT:
155                     sendAbort(callback);
156                     break;
157                 case SIMPLE:
158                     sendRequest(commitRequest(false), callback);
159                     break;
160                 case THREE_PHASE:
161                     sendRequest(commitRequest(true), callback);
162                     break;
163                 default:
164                     throw new IllegalArgumentException("Unhandled protocol " + maybeProtocol.get());
165             }
166         }
167     }
168
169     @Override
170     void handleForwardedRemoteRequest(final TransactionRequest<?> request,
171             final @Nullable Consumer<Response<?, ?>> callback) {
172         LOG.debug("Applying forwaded request {}", request);
173
174         if (request instanceof ModifyTransactionRequest) {
175             applyModifyTransactionRequest((ModifyTransactionRequest) request, callback);
176         } else {
177             throw new IllegalArgumentException("Unhandled request " + request);
178         }
179     }
180
181     @Override
182     void forwardToRemote(final RemoteProxyTransaction successor, final TransactionRequest<?> request,
183             final Consumer<Response<?, ?>> callback) throws RequestException {
184         if (request instanceof CommitLocalTransactionRequest) {
185             final CommitLocalTransactionRequest req = (CommitLocalTransactionRequest) request;
186             final DataTreeModification mod = req.getModification();
187
188             LOG.debug("Applying modification {} to successor {}", mod, successor);
189             mod.applyToCursor(new AbstractDataTreeModificationCursor() {
190                 @Override
191                 public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
192                     successor.write(current().node(child), data);
193                 }
194
195                 @Override
196                 public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
197                     successor.merge(current().node(child), data);
198                 }
199
200                 @Override
201                 public void delete(final PathArgument child) {
202                     successor.delete(current().node(child));
203                 }
204             });
205
206             successor.seal();
207
208             final ModifyTransactionRequest successorReq = successor.commitRequest(req.isCoordinated());
209             successor.sendRequest(successorReq, callback);
210         } else if (request instanceof AbortLocalTransactionRequest) {
211             LOG.debug("Forwarding abort {} to successor {}", request, successor);
212             successor.abort();
213         } else {
214             throw new IllegalArgumentException("Unhandled request" + request);
215         }
216     }
217
218     @Override
219     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
220             final Consumer<Response<?, ?>> callback) throws RequestException {
221         if (request instanceof AbortLocalTransactionRequest) {
222             successor.sendAbort(request, callback);
223         } else if (request instanceof CommitLocalTransactionRequest) {
224             successor.sendCommit((CommitLocalTransactionRequest)request, callback);
225         } else {
226             throw new IllegalArgumentException("Unhandled request" + request);
227         }
228
229         LOG.debug("Forwarded request {} to successor {}", request, successor);
230     }
231
232     private void sendAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
233         sendRequest(request, callback);
234         modification = new FailedDataTreeModification(this::abortedException);
235     }
236
237     private void sendCommit(final CommitLocalTransactionRequest request, final Consumer<Response<?, ?>> callback) {
238         // Rebase old modification on new data tree.
239         try (DataTreeModificationCursor cursor = modification.createCursor(YangInstanceIdentifier.EMPTY)) {
240             request.getModification().applyToCursor(cursor);
241         }
242
243         seal();
244         sendRequest(commitRequest(request.isCoordinated()), callback);
245     }
246 }