2 * Copyright (c) 2015 Brocade Communications 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.datastore.entityownership;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NODE_ID;
12 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_NODE_ID;
13 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
15 import akka.actor.ActorRef;
16 import akka.dispatch.OnComplete;
17 import akka.pattern.Patterns;
18 import akka.util.Timeout;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Strings;
21 import java.util.Collection;
22 import java.util.Optional;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.ConcurrentMap;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.controller.cluster.access.concepts.MemberName;
28 import org.opendaylight.controller.cluster.datastore.config.Configuration;
29 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
30 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
31 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
32 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
33 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
34 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
35 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
36 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
37 import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
38 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
39 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
40 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
41 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
42 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
43 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
44 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
45 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.EntityOwners;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
49 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import scala.concurrent.Await;
56 import scala.concurrent.Future;
57 import scala.concurrent.duration.Duration;
60 * The distributed implementation of the EntityOwnershipService.
62 * @author Thomas Pantelis
64 public class DistributedEntityOwnershipService implements DOMEntityOwnershipService, AutoCloseable {
66 static final String ENTITY_OWNERSHIP_SHARD_NAME = "entity-ownership";
68 private static final Logger LOG = LoggerFactory.getLogger(DistributedEntityOwnershipService.class);
69 private static final Timeout MESSAGE_TIMEOUT = new Timeout(1, TimeUnit.MINUTES);
71 private final ConcurrentMap<DOMEntity, DOMEntity> registeredEntities = new ConcurrentHashMap<>();
72 private final ActorContext context;
74 private volatile ActorRef localEntityOwnershipShard;
75 private volatile DataTree localEntityOwnershipShardDataTree;
77 DistributedEntityOwnershipService(final ActorContext context) {
78 this.context = requireNonNull(context);
81 public static DistributedEntityOwnershipService start(final ActorContext context,
82 final EntityOwnerSelectionStrategyConfig strategyConfig) {
83 ActorRef shardManagerActor = context.getShardManager();
85 Configuration configuration = context.getConfiguration();
86 Collection<MemberName> entityOwnersMemberNames = configuration.getUniqueMemberNamesForAllShards();
87 CreateShard createShard = new CreateShard(new ModuleShardConfiguration(EntityOwners.QNAME.getNamespace(),
88 "entity-owners", ENTITY_OWNERSHIP_SHARD_NAME, ModuleShardStrategy.NAME, entityOwnersMemberNames),
89 newShardBuilder(context, strategyConfig), null);
91 Future<Object> createFuture = context.executeOperationAsync(shardManagerActor, createShard, MESSAGE_TIMEOUT);
92 createFuture.onComplete(new OnComplete<Object>() {
94 public void onComplete(final Throwable failure, final Object response) {
95 if (failure != null) {
96 LOG.error("Failed to create {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
98 LOG.info("Successfully created {} shard", ENTITY_OWNERSHIP_SHARD_NAME);
101 }, context.getClientDispatcher());
103 return new DistributedEntityOwnershipService(context);
106 private void executeEntityOwnershipShardOperation(final ActorRef shardActor, final Object message) {
107 Future<Object> future = context.executeOperationAsync(shardActor, message, MESSAGE_TIMEOUT);
108 future.onComplete(new OnComplete<Object>() {
110 public void onComplete(final Throwable failure, final Object response) {
111 if (failure != null) {
112 // FIXME: CONTROLLER-1904: reduce the severity to info once we have a retry mechanism
113 LOG.error("Error sending message {} to {}", message, shardActor, failure);
115 LOG.debug("{} message to {} succeeded", message, shardActor);
118 }, context.getClientDispatcher());
122 void executeLocalEntityOwnershipShardOperation(final Object message) {
123 if (localEntityOwnershipShard == null) {
124 Future<ActorRef> future = context.findLocalShardAsync(ENTITY_OWNERSHIP_SHARD_NAME);
125 future.onComplete(new OnComplete<ActorRef>() {
127 public void onComplete(final Throwable failure, final ActorRef shardActor) {
128 if (failure != null) {
129 // FIXME: CONTROLLER-1904: reduce the severity to info once we have a retry mechanism
130 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
132 localEntityOwnershipShard = shardActor;
133 executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
136 }, context.getClientDispatcher());
139 executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
144 public DOMEntityOwnershipCandidateRegistration registerCandidate(final DOMEntity entity)
145 throws CandidateAlreadyRegisteredException {
146 requireNonNull(entity, "entity cannot be null");
148 if (registeredEntities.putIfAbsent(entity, entity) != null) {
149 throw new CandidateAlreadyRegisteredException(entity);
152 RegisterCandidateLocal registerCandidate = new RegisterCandidateLocal(entity);
154 LOG.debug("Registering candidate with message: {}", registerCandidate);
156 executeLocalEntityOwnershipShardOperation(registerCandidate);
157 return new DistributedEntityOwnershipCandidateRegistration(entity, this);
160 void unregisterCandidate(final DOMEntity entity) {
161 LOG.debug("Unregistering candidate for {}", entity);
163 executeLocalEntityOwnershipShardOperation(new UnregisterCandidateLocal(entity));
164 registeredEntities.remove(entity);
168 public DOMEntityOwnershipListenerRegistration registerListener(final String entityType,
169 final DOMEntityOwnershipListener listener) {
170 RegisterListenerLocal registerListener = new RegisterListenerLocal(listener, entityType);
172 LOG.debug("Registering listener with message: {}", registerListener);
174 executeLocalEntityOwnershipShardOperation(registerListener);
175 return new DistributedEntityOwnershipListenerRegistration(listener, entityType, this);
179 public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity forEntity) {
180 requireNonNull(forEntity, "forEntity cannot be null");
182 DataTree dataTree = getLocalEntityOwnershipShardDataTree();
183 if (dataTree == null) {
184 return Optional.empty();
187 Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
188 entityPath(forEntity.getType(), forEntity.getIdentifier()));
189 if (!entityNode.isPresent()) {
190 return Optional.empty();
193 // Check if there are any candidates, if there are none we do not really have ownership state
194 final MapEntryNode entity = (MapEntryNode) entityNode.get();
195 final Optional<DataContainerChild<? extends PathArgument, ?>> optionalCandidates =
196 entity.getChild(CANDIDATE_NODE_ID);
197 final boolean hasCandidates = optionalCandidates.isPresent()
198 && ((MapNode) optionalCandidates.get()).getValue().size() > 0;
199 if (!hasCandidates) {
200 return Optional.empty();
203 MemberName localMemberName = context.getCurrentMemberName();
204 Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = entity.getChild(ENTITY_OWNER_NODE_ID);
205 String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
206 boolean hasOwner = !Strings.isNullOrEmpty(owner);
207 boolean isOwner = hasOwner && localMemberName.getName().equals(owner);
209 return Optional.of(EntityOwnershipState.from(isOwner, hasOwner));
213 public boolean isCandidateRegistered(@Nonnull final DOMEntity entity) {
214 return registeredEntities.get(entity) != null;
218 @SuppressWarnings("checkstyle:IllegalCatch")
219 DataTree getLocalEntityOwnershipShardDataTree() {
220 if (localEntityOwnershipShardDataTree == null) {
222 if (localEntityOwnershipShard == null) {
223 localEntityOwnershipShard = Await.result(context.findLocalShardAsync(
224 ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
227 localEntityOwnershipShardDataTree = (DataTree) Await.result(Patterns.ask(localEntityOwnershipShard,
228 GetShardDataTree.INSTANCE, MESSAGE_TIMEOUT), Duration.Inf());
229 } catch (Exception e) {
230 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, e);
234 return localEntityOwnershipShardDataTree;
237 void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
238 LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
240 executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));
244 public void close() {
247 private static EntityOwnershipShard.Builder newShardBuilder(final ActorContext context,
248 final EntityOwnerSelectionStrategyConfig strategyConfig) {
249 return EntityOwnershipShard.newBuilder().localMemberName(context.getCurrentMemberName())
250 .ownerSelectionStrategyConfig(strategyConfig);
254 ActorRef getLocalEntityOwnershipShard() {
255 return localEntityOwnershipShard;