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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.