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