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