Improve error reporting for tell-based reads
[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 static akka.pattern.Patterns.ask;
11 import static com.google.common.base.Verify.verifyNotNull;
12
13 import akka.dispatch.ExecutionContexts;
14 import akka.dispatch.OnComplete;
15 import akka.util.Timeout;
16 import com.google.common.collect.BiMap;
17 import com.google.common.collect.ImmutableBiMap;
18 import com.google.common.collect.ImmutableBiMap.Builder;
19 import java.util.concurrent.CompletionStage;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import java.util.concurrent.TimeUnit;
23 import javax.annotation.concurrent.GuardedBy;
24 import javax.annotation.concurrent.ThreadSafe;
25 import org.opendaylight.controller.cluster.access.client.BackendInfoResolver;
26 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
27 import org.opendaylight.controller.cluster.datastore.shardmanager.RegisterForShardAvailabilityChanges;
28 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
29 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
30 import org.opendaylight.yangtools.concepts.Registration;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import scala.concurrent.Future;
35
36 /**
37  * {@link BackendInfoResolver} implementation for static shard configuration based on ShardManager. Each string-named
38  * shard is assigned a single cookie and this mapping is stored in a bidirectional map. Information about corresponding
39  * shard leader is resolved via {@link ActorContext}. The product of resolution is {@link ShardBackendInfo}.
40  *
41  * @author Robert Varga
42  */
43 @ThreadSafe
44 final class ModuleShardBackendResolver extends AbstractShardBackendResolver {
45     private static final Logger LOG = LoggerFactory.getLogger(ModuleShardBackendResolver.class);
46
47     private final ConcurrentMap<Long, ShardState> backends = new ConcurrentHashMap<>();
48
49     private final Future<Registration> shardAvailabilityChangesRegFuture;
50
51     @GuardedBy("this")
52     private long nextShard = 1;
53
54     private volatile BiMap<String, Long> shards = ImmutableBiMap.of(DefaultShardStrategy.DEFAULT_SHARD, 0L);
55
56     // FIXME: we really need just ActorContext.findPrimaryShardAsync()
57     ModuleShardBackendResolver(final ClientIdentifier clientId, final ActorContext actorContext) {
58         super(clientId, actorContext);
59
60         shardAvailabilityChangesRegFuture = ask(actorContext.getShardManager(), new RegisterForShardAvailabilityChanges(
61             this::onShardAvailabilityChange), Timeout.apply(60, TimeUnit.MINUTES))
62                 .map(reply -> (Registration)reply, ExecutionContexts.global());
63
64         shardAvailabilityChangesRegFuture.onComplete(new OnComplete<Registration>() {
65             @Override
66             public void onComplete(Throwable failure, Registration reply) {
67                 if (failure != null) {
68                     LOG.error("RegisterForShardAvailabilityChanges failed", failure);
69                 }
70             }
71         }, ExecutionContexts.global());
72     }
73
74     private void onShardAvailabilityChange(String shardName) {
75         LOG.debug("onShardAvailabilityChange for {}", shardName);
76
77         Long cookie = shards.get(shardName);
78         if (cookie == null) {
79             LOG.debug("No shard cookie found for {}", shardName);
80             return;
81         }
82
83         notifyStaleBackendInfoCallbacks(cookie);
84     }
85
86     Long resolveShardForPath(final YangInstanceIdentifier path) {
87         final String shardName = actorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
88         Long cookie = shards.get(shardName);
89         if (cookie == null) {
90             synchronized (this) {
91                 cookie = shards.get(shardName);
92                 if (cookie == null) {
93                     cookie = nextShard++;
94
95                     Builder<String, Long> builder = ImmutableBiMap.builder();
96                     builder.putAll(shards);
97                     builder.put(shardName, cookie);
98                     shards = builder.build();
99                 }
100             }
101         }
102
103         return cookie;
104     }
105
106     @Override
107     public CompletionStage<ShardBackendInfo> getBackendInfo(final Long cookie) {
108         /*
109          * We cannot perform a simple computeIfAbsent() here because we need to control sequencing of when the state
110          * is inserted into the map and retired from it (based on the stage result).
111          *
112          * We do not want to hook another stage one processing completes and hooking a removal on failure from a compute
113          * method runs the inherent risk of stage completing before the insertion does (i.e. we have a removal of
114          * non-existent element.
115          */
116         final ShardState existing = backends.get(cookie);
117         if (existing != null) {
118             return existing.getStage();
119         }
120
121         final String shardName = shards.inverse().get(cookie);
122         if (shardName == null) {
123             LOG.warn("Failing request for non-existent cookie {}", cookie);
124             throw new IllegalArgumentException("Cookie " + cookie + " does not have a shard assigned");
125         }
126
127         LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
128         final ShardState toInsert = resolveBackendInfo(shardName, cookie);
129
130         final ShardState raced = backends.putIfAbsent(cookie, toInsert);
131         if (raced != null) {
132             // We have had a concurrent insertion, return that
133             LOG.debug("Race during insertion of state for cookie {} shard {}", cookie, shardName);
134             return raced.getStage();
135         }
136
137         // We have succeeded in populating the map, now we need to take care of pruning the entry if it fails to
138         // complete
139         final CompletionStage<ShardBackendInfo> stage = toInsert.getStage();
140         stage.whenComplete((info, failure) -> {
141             if (failure != null) {
142                 LOG.debug("Resolution of cookie {} shard {} failed, removing state", cookie, shardName, failure);
143                 backends.remove(cookie, toInsert);
144
145                 // Remove cache state in case someone else forgot to invalidate it
146                 flushCache(shardName);
147             }
148         });
149
150         return stage;
151     }
152
153     @Override
154     public CompletionStage<ShardBackendInfo> refreshBackendInfo(final Long cookie,
155             final ShardBackendInfo staleInfo) {
156         final ShardState existing = backends.get(cookie);
157         if (existing != null) {
158             if (!staleInfo.equals(existing.getResult())) {
159                 return existing.getStage();
160             }
161
162             LOG.debug("Invalidating backend information {}", staleInfo);
163             flushCache(staleInfo.getName());
164
165             LOG.trace("Invalidated cache {}", staleInfo);
166             backends.remove(cookie, existing);
167         }
168
169         return getBackendInfo(cookie);
170     }
171
172     @Override
173     public void close() {
174         shardAvailabilityChangesRegFuture.onComplete(new OnComplete<Registration>() {
175             @Override
176             public void onComplete(Throwable failure, Registration reply) {
177                 reply.close();
178             }
179         }, ExecutionContexts.global());
180     }
181
182     @Override
183     public String resolveCookieName(Long cookie) {
184         return verifyNotNull(shards.inverse().get(cookie), "Unexpected null cookie: %s", cookie);
185     }
186 }