2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.databroker.actors.dds;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import akka.actor.ActorRef;
14 import akka.util.Timeout;
15 import com.google.common.primitives.UnsignedLong;
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;
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}.
52 * @author Robert Varga
55 abstract class AbstractShardBackendResolver extends BackendInfoResolver<ShardBackendInfo> {
56 static final class ShardState {
57 private final CompletionStage<ShardBackendInfo> stage;
59 private ShardBackendInfo result;
61 ShardState(final CompletionStage<ShardBackendInfo> stage) {
62 this.stage = requireNonNull(stage);
63 stage.whenComplete(this::onStageResolved);
66 @NonNull CompletionStage<ShardBackendInfo> getStage() {
70 synchronized @Nullable ShardBackendInfo getResult() {
74 private synchronized void onStageResolved(final ShardBackendInfo info, final Throwable failure) {
75 if (failure == null) {
76 this.result = requireNonNull(info);
78 LOG.warn("Failed to resolve shard", failure);
83 private static final Logger LOG = LoggerFactory.getLogger(AbstractShardBackendResolver.class);
86 * Connect request timeout. If the shard does not respond within this interval, we retry the lookup and connection.
88 // TODO: maybe make this configurable somehow?
89 private static final Timeout CONNECT_TIMEOUT = Timeout.apply(5, TimeUnit.SECONDS);
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();
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()));
104 public Registration notifyWhenBackendInfoIsStale(final Consumer<Long> callback) {
105 staleBackendInfoCallbacks.add(callback);
106 return () -> staleBackendInfoCallbacks.remove(callback);
109 protected void notifyStaleBackendInfoCallbacks(Long cookie) {
110 staleBackendInfoCallbacks.forEach(callback -> callback.accept(cookie));
113 protected ActorUtils actorUtils() {
117 protected final void flushCache(final String shardName) {
118 actorUtils.getPrimaryShardInfoCache().remove(shardName);
121 protected final ShardState resolveBackendInfo(final String shardName, final long cookie) {
122 LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
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);
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);
142 future.completeExceptionally(failure);
146 return new ShardState(future);
149 private static TimeoutException wrap(final String message, final Throwable cause) {
150 final TimeoutException ret = new TimeoutException(message);
151 ret.initCause(requireNonNull(cause));
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);
159 FutureConverters.toJava(ExplicitAsk.ask(info.getPrimaryShardActor(), connectFunction, CONNECT_TIMEOUT))
160 .whenComplete((response, failure) -> onConnectResponse(shardName, cookie, future, response, failure));
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));
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);
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()));