Fix remaining CS warnings in sal-distributed-datastore
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / ModuleShardBackendResolver.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.base.Throwables;
14 import com.google.common.collect.BiMap;
15 import com.google.common.collect.ImmutableBiMap;
16 import com.google.common.collect.ImmutableBiMap.Builder;
17 import com.google.common.primitives.UnsignedLong;
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.CompletionStage;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.atomic.AtomicLong;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.opendaylight.controller.cluster.access.ABIVersion;
24 import org.opendaylight.controller.cluster.access.client.BackendInfo;
25 import org.opendaylight.controller.cluster.access.client.BackendInfoResolver;
26 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
27 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
28 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
29 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
30 import org.opendaylight.controller.cluster.common.actor.ExplicitAsk;
31 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
32 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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 final class ModuleShardBackendResolver extends BackendInfoResolver<ShardBackendInfo> {
47     private static final CompletableFuture<ShardBackendInfo> NULL_FUTURE = CompletableFuture.completedFuture(null);
48     private static final Logger LOG = LoggerFactory.getLogger(ModuleShardBackendResolver.class);
49
50     /**
51      * Fall-over-dead timeout. If we do not make progress in this long, just fall over and propagate the failure.
52      * All users are expected to fail, possibly attempting to recover by restarting. It is fair to remain
53      * non-operational.
54      */
55     // TODO: maybe make this configurable somehow?
56     private static final Timeout DEAD_TIMEOUT = Timeout.apply(15, TimeUnit.MINUTES);
57
58     private final ActorContext actorContext;
59     // FIXME: this counter should be in superclass somewhere
60     private final AtomicLong nextSessionId = new AtomicLong();
61     private final Function1<ActorRef, ?> connectFunction;
62
63     @GuardedBy("this")
64     private long nextShard = 1;
65
66     private volatile BiMap<String, Long> shards = ImmutableBiMap.of(DefaultShardStrategy.DEFAULT_SHARD, 0L);
67
68     // FIXME: we really need just ActorContext.findPrimaryShardAsync()
69     ModuleShardBackendResolver(final ClientIdentifier clientId, final ActorContext actorContext) {
70         this.actorContext = Preconditions.checkNotNull(actorContext);
71         this.connectFunction = ExplicitAsk.toScala(t -> new ConnectClientRequest(clientId, t, ABIVersion.BORON,
72             ABIVersion.current()));
73     }
74
75     @Override
76     protected void invalidateBackendInfo(final CompletionStage<? extends BackendInfo> info) {
77         LOG.trace("Initiated invalidation of backend information {}", info);
78         info.thenAccept(this::invalidate);
79     }
80
81     private void invalidate(final BackendInfo result) {
82         Preconditions.checkArgument(result instanceof ShardBackendInfo);
83         LOG.debug("Invalidating backend information {}", result);
84         actorContext.getPrimaryShardInfoCache().remove(((ShardBackendInfo)result).getShardName());
85     }
86
87     Long resolveShardForPath(final YangInstanceIdentifier path) {
88         final String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
89         Long cookie = shards.get(shardName);
90         if (cookie == null) {
91             synchronized (this) {
92                 cookie = shards.get(shardName);
93                 if (cookie == null) {
94                     cookie = nextShard++;
95
96                     Builder<String, Long> builder = ImmutableBiMap.builder();
97                     builder.putAll(shards);
98                     builder.put(shardName, cookie);
99                     shards = builder.build();
100                 }
101             }
102         }
103
104         return cookie;
105     }
106
107     @Override
108     protected CompletableFuture<ShardBackendInfo> resolveBackendInfo(final Long cookie) {
109         final String shardName = shards.inverse().get(cookie);
110         if (shardName == null) {
111             LOG.warn("Failing request for non-existent cookie {}", cookie);
112             return NULL_FUTURE;
113         }
114
115         final CompletableFuture<ShardBackendInfo> ret = new CompletableFuture<>();
116
117         FutureConverters.toJava(actorContext.findPrimaryShardAsync(shardName)).thenCompose(info -> {
118             LOG.debug("Looking up primary info for {} from {}", shardName, info);
119             return FutureConverters.toJava(ExplicitAsk.ask(info.getPrimaryShardActor(), connectFunction, DEAD_TIMEOUT));
120         }).thenApply(response -> {
121             if (response instanceof RequestFailure) {
122                 final RequestFailure<?, ?> failure = (RequestFailure<?, ?>) response;
123                 LOG.debug("Connect request failed {}", failure, failure.getCause());
124                 throw Throwables.propagate(failure.getCause());
125             }
126
127             LOG.debug("Resolved backend information to {}", response);
128
129             Preconditions.checkArgument(response instanceof ConnectClientSuccess, "Unhandled response {}", response);
130             final ConnectClientSuccess success = (ConnectClientSuccess) response;
131
132             return new ShardBackendInfo(success.getBackend(),
133                 nextSessionId.getAndIncrement(), success.getVersion(), shardName, UnsignedLong.fromLongBits(cookie),
134                 success.getDataTree(), success.getMaxMessages());
135         }).whenComplete((info, throwablw) -> {
136             if (throwablw != null) {
137                 ret.completeExceptionally(throwablw);
138             } else {
139                 ret.complete(info);
140             }
141         });
142
143         LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
144         return ret;
145     }
146 }