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

©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.