2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.databroker.actors.dds;
10 import static akka.pattern.Patterns.ask;
11 import static com.google.common.base.Verify.verifyNotNull;
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;
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}.
41 * @author Robert Varga
44 final class ModuleShardBackendResolver extends AbstractShardBackendResolver {
45 private static final Logger LOG = LoggerFactory.getLogger(ModuleShardBackendResolver.class);
47 private final ConcurrentMap<Long, ShardState> backends = new ConcurrentHashMap<>();
49 private final Future<Registration> shardAvailabilityChangesRegFuture;
52 private long nextShard = 1;
54 private volatile BiMap<String, Long> shards = ImmutableBiMap.of(DefaultShardStrategy.DEFAULT_SHARD, 0L);
56 // FIXME: we really need just ActorContext.findPrimaryShardAsync()
57 ModuleShardBackendResolver(final ClientIdentifier clientId, final ActorContext actorContext) {
58 super(clientId, actorContext);
60 shardAvailabilityChangesRegFuture = ask(actorContext.getShardManager(), new RegisterForShardAvailabilityChanges(
61 this::onShardAvailabilityChange), Timeout.apply(60, TimeUnit.MINUTES))
62 .map(reply -> (Registration)reply, ExecutionContexts.global());
64 shardAvailabilityChangesRegFuture.onComplete(new OnComplete<Registration>() {
66 public void onComplete(Throwable failure, Registration reply) {
67 if (failure != null) {
68 LOG.error("RegisterForShardAvailabilityChanges failed", failure);
71 }, ExecutionContexts.global());
74 private void onShardAvailabilityChange(String shardName) {
75 LOG.debug("onShardAvailabilityChange for {}", shardName);
77 Long cookie = shards.get(shardName);
79 LOG.debug("No shard cookie found for {}", shardName);
83 notifyStaleBackendInfoCallbacks(cookie);
86 Long resolveShardForPath(final YangInstanceIdentifier path) {
87 final String shardName = actorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
88 Long cookie = shards.get(shardName);
91 cookie = shards.get(shardName);
95 Builder<String, Long> builder = ImmutableBiMap.builder();
96 builder.putAll(shards);
97 builder.put(shardName, cookie);
98 shards = builder.build();
107 public CompletionStage<ShardBackendInfo> getBackendInfo(final Long cookie) {
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).
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.
116 final ShardState existing = backends.get(cookie);
117 if (existing != null) {
118 return existing.getStage();
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");
127 LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
128 final ShardState toInsert = resolveBackendInfo(shardName, cookie);
130 final ShardState raced = backends.putIfAbsent(cookie, toInsert);
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();
137 // We have succeeded in populating the map, now we need to take care of pruning the entry if it fails to
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);
145 // Remove cache state in case someone else forgot to invalidate it
146 flushCache(shardName);
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();
162 LOG.debug("Invalidating backend information {}", staleInfo);
163 flushCache(staleInfo.getName());
165 LOG.trace("Invalidated cache {}", staleInfo);
166 backends.remove(cookie, existing);
169 return getBackendInfo(cookie);
173 public void close() {
174 shardAvailabilityChangesRegFuture.onComplete(new OnComplete<Registration>() {
176 public void onComplete(Throwable failure, Registration reply) {
179 }, ExecutionContexts.global());
183 public String resolveCookieName(Long cookie) {
184 return verifyNotNull(shards.inverse().get(cookie), "Unexpected null cookie: %s", cookie);