e32d1bf1cff2b29a28aba11f31b7beb0ce1ed408
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / AbstractShardBackendResolver.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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import akka.actor.ActorRef;
14 import akka.util.Timeout;
15 import com.google.common.primitives.UnsignedLong;
16 import java.util.Set;
17 import java.util.concurrent.CompletableFuture;
18 import java.util.concurrent.CompletionStage;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22 import java.util.concurrent.atomic.AtomicLong;
23 import java.util.function.Consumer;
24 import javax.annotation.concurrent.GuardedBy;
25 import javax.annotation.concurrent.ThreadSafe;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.controller.cluster.access.ABIVersion;
29 import org.opendaylight.controller.cluster.access.client.BackendInfoResolver;
30 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
31 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
32 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
33 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
34 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
35 import org.opendaylight.controller.cluster.common.actor.ExplicitAsk;
36 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
37 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
38 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
39 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
40 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
41 import org.opendaylight.yangtools.concepts.Registration;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import scala.Function1;
45 import scala.compat.java8.FutureConverters;
46
47 /**
48  * {@link BackendInfoResolver} implementation for static shard configuration based on ShardManager. Each string-named
49  * shard is assigned a single cookie and this mapping is stored in a bidirectional map. Information about corresponding
50  * shard leader is resolved via {@link ActorUtils}. The product of resolution is {@link ShardBackendInfo}.
51  *
52  * @author Robert Varga
53  */
54 @ThreadSafe
55 abstract class AbstractShardBackendResolver extends BackendInfoResolver<ShardBackendInfo> {
56     static final class ShardState {
57         private final CompletionStage<ShardBackendInfo> stage;
58         @GuardedBy("this")
59         private ShardBackendInfo result;
60
61         ShardState(final CompletionStage<ShardBackendInfo> stage) {
62             this.stage = requireNonNull(stage);
63             stage.whenComplete(this::onStageResolved);
64         }
65
66         @NonNull CompletionStage<ShardBackendInfo> getStage() {
67             return stage;
68         }
69
70         synchronized @Nullable ShardBackendInfo getResult() {
71             return result;
72         }
73
74         private synchronized void onStageResolved(final ShardBackendInfo info, final Throwable failure) {
75             if (failure == null) {
76                 this.result = requireNonNull(info);
77             } else {
78                 LOG.warn("Failed to resolve shard", failure);
79             }
80         }
81     }
82
83     private static final Logger LOG = LoggerFactory.getLogger(AbstractShardBackendResolver.class);
84
85     /**
86      * Connect request timeout. If the shard does not respond within this interval, we retry the lookup and connection.
87      */
88     // TODO: maybe make this configurable somehow?
89     private static final Timeout CONNECT_TIMEOUT = Timeout.apply(5, TimeUnit.SECONDS);
90
91     private final AtomicLong nextSessionId = new AtomicLong();
92     private final Function1<ActorRef, ?> connectFunction;
93     private final ActorUtils actorUtils;
94     private final Set<Consumer<Long>> staleBackendInfoCallbacks = ConcurrentHashMap.newKeySet();
95
96     // FIXME: we really need just ActorContext.findPrimaryShardAsync()
97     AbstractShardBackendResolver(final ClientIdentifier clientId, final ActorUtils actorUtils) {
98         this.actorUtils = requireNonNull(actorUtils);
99         this.connectFunction = ExplicitAsk.toScala(t -> new ConnectClientRequest(clientId, t, ABIVersion.BORON,
100             ABIVersion.current()));
101     }
102
103     @Override
104     public Registration notifyWhenBackendInfoIsStale(final Consumer<Long> callback) {
105         staleBackendInfoCallbacks.add(callback);
106         return () -> staleBackendInfoCallbacks.remove(callback);
107     }
108
109     protected void notifyStaleBackendInfoCallbacks(Long cookie) {
110         staleBackendInfoCallbacks.forEach(callback -> callback.accept(cookie));
111     }
112
113     protected ActorUtils actorUtils() {
114         return actorUtils;
115     }
116
117     protected final void flushCache(final String shardName) {
118         actorUtils.getPrimaryShardInfoCache().remove(shardName);
119     }
120
121     protected final ShardState resolveBackendInfo(final String shardName, final long cookie) {
122         LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
123
124         final CompletableFuture<ShardBackendInfo> future = new CompletableFuture<>();
125         FutureConverters.toJava(actorUtils.findPrimaryShardAsync(shardName)).whenComplete((info, failure) -> {
126             if (failure == null) {
127                 connectShard(shardName, cookie, info, future);
128                 return;
129             }
130
131             LOG.debug("Shard {} failed to resolve", shardName, failure);
132             if (failure instanceof NoShardLeaderException) {
133                 future.completeExceptionally(wrap("Shard has no current leader", failure));
134             } else if (failure instanceof NotInitializedException) {
135                 // FIXME: this actually is an exception we can retry on
136                 LOG.info("Shard {} has not initialized yet", shardName);
137                 future.completeExceptionally(failure);
138             } else if (failure instanceof PrimaryNotFoundException) {
139                 LOG.info("Failed to find primary for shard {}", shardName);
140                 future.completeExceptionally(failure);
141             } else {
142                 future.completeExceptionally(failure);
143             }
144         });
145
146         return new ShardState(future);
147     }
148
149     private static TimeoutException wrap(final String message, final Throwable cause) {
150         final TimeoutException ret = new TimeoutException(message);
151         ret.initCause(requireNonNull(cause));
152         return ret;
153     }
154
155     private void connectShard(final String shardName, final long cookie, final PrimaryShardInfo info,
156             final CompletableFuture<ShardBackendInfo> future) {
157         LOG.debug("Shard {} resolved to {}, attempting to connect", shardName, info);
158
159         FutureConverters.toJava(ExplicitAsk.ask(info.getPrimaryShardActor(), connectFunction, CONNECT_TIMEOUT))
160             .whenComplete((response, failure) -> onConnectResponse(shardName, cookie, future, response, failure));
161     }
162
163     private void onConnectResponse(final String shardName, final long cookie,
164             final CompletableFuture<ShardBackendInfo> future, final Object response, final Throwable failure) {
165         if (failure != null) {
166             LOG.debug("Connect attempt to {} failed, will retry", shardName, failure);
167             future.completeExceptionally(wrap("Connection attempt failed", failure));
168             return;
169         }
170         if (response instanceof RequestFailure) {
171             final Throwable cause = ((RequestFailure<?, ?>) response).getCause().unwrap();
172             LOG.debug("Connect attempt to {} failed to process", shardName, cause);
173             final Throwable result = cause instanceof NotLeaderException
174                     ? wrap("Leader moved during establishment", cause) : cause;
175             future.completeExceptionally(result);
176             return;
177         }
178
179         LOG.debug("Resolved backend information to {}", response);
180         checkArgument(response instanceof ConnectClientSuccess, "Unhandled response %s", response);
181         final ConnectClientSuccess success = (ConnectClientSuccess) response;
182         future.complete(new ShardBackendInfo(success.getBackend(), nextSessionId.getAndIncrement(),
183             success.getVersion(), shardName, UnsignedLong.fromLongBits(cookie), success.getDataTree(),
184             success.getMaxMessages()));
185     }
186 }