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