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.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;
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}.
40 * This class is thread-safe.
42 * @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 ImmutableBiMap<String, Long> shards = ImmutableBiMap.of(DefaultShardStrategy.DEFAULT_SHARD, 0L);
56 // FIXME: we really need just ActorContext.findPrimaryShardAsync()
57 ModuleShardBackendResolver(final ClientIdentifier clientId, final ActorUtils actorUtils) {
58 super(clientId, actorUtils);
60 shardAvailabilityChangesRegFuture = ask(actorUtils.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(final Throwable failure, final Registration reply) {
67 if (failure != null) {
68 LOG.error("RegisterForShardAvailabilityChanges failed", failure);
71 }, ExecutionContexts.global());
74 private void onShardAvailabilityChange(final 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 = actorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
88 final Long cookie = shards.get(shardName);
89 return cookie != null ? cookie : populateShard(shardName);
92 private synchronized @NonNull Long populateShard(final String shardName) {
93 Long cookie = shards.get(shardName);
96 shards = ImmutableBiMap.<String, Long>builder().putAll(shards).put(shardName, cookie).build();
102 public CompletionStage<ShardBackendInfo> getBackendInfo(final Long cookie) {
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).
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.
111 final ShardState existing = backends.get(cookie);
112 if (existing != null) {
113 return existing.getStage();
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");
122 LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
123 final ShardState toInsert = resolveBackendInfo(shardName, cookie);
125 final ShardState raced = backends.putIfAbsent(cookie, toInsert);
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();
132 // We have succeeded in populating the map, now we need to take care of pruning the entry if it fails to
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);
140 // Remove cache state in case someone else forgot to invalidate it
141 flushCache(shardName);
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();
157 LOG.debug("Invalidating backend information {}", staleInfo);
158 flushCache(staleInfo.getName());
160 LOG.trace("Invalidated cache {}", staleInfo);
161 backends.remove(cookie, existing);
164 return getBackendInfo(cookie);
168 public void close() {
169 shardAvailabilityChangesRegFuture.onComplete(new OnComplete<Registration>() {
171 public void onComplete(final Throwable failure, final Registration reply) {
174 }, ExecutionContexts.global());
178 public String resolveCookieName(final Long cookie) {
179 return verifyNotNull(shards.inverse().get(cookie), "Unexpected null cookie: %s", cookie);