9940ae57f32858f042084440341d56a660dcb89b
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / DistributedDataStoreClientBehavior.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 akka.actor.ActorRef;
11 import akka.actor.Status;
12 import com.google.common.base.Throwables;
13 import com.google.common.base.Verify;
14 import java.util.Map;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.atomic.AtomicLong;
17 import java.util.function.Consumer;
18 import org.opendaylight.controller.cluster.access.client.ClientActorBehavior;
19 import org.opendaylight.controller.cluster.access.client.ClientActorContext;
20 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
21 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
22 import org.opendaylight.controller.cluster.access.concepts.Response;
23 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * {@link ClientActorBehavior} acting as an intermediary between the backend actors and the DistributedDataStore
29  * frontend.
30  *
31  * <p>
32  * This class is not visible outside of this package because it breaks the actor containment. Services provided to
33  * Java world outside of actor containment are captured in {@link DistributedDataStoreClient}.
34  *
35  * <p>
36  * IMPORTANT: this class breaks actor containment via methods implementing {@link DistributedDataStoreClient} contract.
37  *            When touching internal state, be mindful of the execution context from which execution context, Actor
38  *            or POJO, is the state being accessed or modified.
39  *
40  * <p>
41  * THREAD SAFETY: this class must always be kept thread-safe, so that both the Actor System thread and the application
42  *                threads can run concurrently. All state transitions must be made in a thread-safe manner. When in
43  *                doubt, feel free to synchronize on this object.
44  *
45  * <p>
46  * PERFORMANCE: this class lies in a performance-critical fast path. All code needs to be concise and efficient, but
47  *              performance must not come at the price of correctness. Any optimizations need to be carefully analyzed
48  *              for correctness and performance impact.
49  *
50  * <p>
51  * TRADE-OFFS: part of the functionality runs in application threads without switching contexts, which makes it ideal
52  *             for performing work and charging applications for it. That has two positive effects:
53  *             - CPU usage is distributed across applications, minimizing work done in the actor thread
54  *             - CPU usage provides back-pressure towards the application.
55  *
56  * @author Robert Varga
57  */
58 final class DistributedDataStoreClientBehavior extends ClientActorBehavior implements DistributedDataStoreClient {
59     private static final Logger LOG = LoggerFactory.getLogger(DistributedDataStoreClientBehavior.class);
60
61     private final Map<LocalHistoryIdentifier, ClientLocalHistory> histories = new ConcurrentHashMap<>();
62     private final AtomicLong nextHistoryId = new AtomicLong(1);
63     private final ModuleShardBackendResolver resolver;
64     private final SingleClientHistory singleHistory;
65
66     private volatile Throwable aborted;
67
68     DistributedDataStoreClientBehavior(final ClientActorContext context, final ActorContext actorContext) {
69         super(context);
70         resolver = new ModuleShardBackendResolver(context.getIdentifier(), actorContext);
71         singleHistory = new SingleClientHistory(this, new LocalHistoryIdentifier(getIdentifier(), 0));
72     }
73
74     //
75     //
76     // Methods below are invoked from the client actor thread
77     //
78     //
79
80     @Override
81     protected void haltClient(final Throwable cause) {
82         // If we have encountered a previous problem there is not cleanup necessary, as we have already cleaned up
83         // Thread safely is not an issue, as both this method and any failures are executed from the same (client actor)
84         // thread.
85         if (aborted != null) {
86             abortOperations(cause);
87         }
88     }
89
90     private void abortOperations(final Throwable cause) {
91         // This acts as a barrier, application threads check this after they have added an entry in the maps,
92         // and if they observe aborted being non-null, they will perform their cleanup and not return the handle.
93         aborted = cause;
94
95         for (ClientLocalHistory h : histories.values()) {
96             h.localAbort(cause);
97         }
98         histories.clear();
99     }
100
101     private DistributedDataStoreClientBehavior shutdown(final ClientActorBehavior currentBehavior) {
102         abortOperations(new IllegalStateException("Client " + getIdentifier() + " has been shut down"));
103         return null;
104     }
105
106     @Override
107     protected DistributedDataStoreClientBehavior onCommand(final Object command) {
108         if (command instanceof GetClientRequest) {
109             ((GetClientRequest) command).getReplyTo().tell(new Status.Success(this), ActorRef.noSender());
110         } else {
111             LOG.warn("{}: ignoring unhandled command {}", persistenceId(), command);
112         }
113
114         return this;
115     }
116
117     //
118     //
119     // Methods below are invoked from application threads
120     //
121     //
122
123     @SuppressWarnings("checkstyle:IllegalCatch")
124     private static <K, V extends LocalAbortable> V returnIfOperational(final Map<K , V> map, final K key, final V value,
125             final Throwable aborted) {
126         Verify.verify(map.put(key, value) == null);
127
128         if (aborted != null) {
129             try {
130                 value.localAbort(aborted);
131             } catch (Exception e) {
132                 LOG.debug("Close of {} failed", value, e);
133             }
134             map.remove(key, value);
135             throw Throwables.propagate(aborted);
136         }
137
138         return value;
139     }
140
141     @Override
142     public ClientLocalHistory createLocalHistory() {
143         final LocalHistoryIdentifier historyId = new LocalHistoryIdentifier(getIdentifier(),
144             nextHistoryId.getAndIncrement());
145         final ClientLocalHistory history = new ClientLocalHistory(this, historyId);
146         LOG.debug("{}: creating a new local history {}", persistenceId(), history);
147
148         return returnIfOperational(histories, historyId, history, aborted);
149     }
150
151     @Override
152     public ClientTransaction createTransaction() {
153         return singleHistory.createTransaction();
154     }
155
156     @Override
157     public void close() {
158         context().executeInActor(this::shutdown);
159     }
160
161     @Override
162     protected ModuleShardBackendResolver resolver() {
163         return resolver;
164     }
165
166     void sendRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> completer) {
167         sendRequest(request, response -> {
168             completer.accept(response);
169             return this;
170         });
171     }
172
173 }