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 org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NODE_ID;
11 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_NODE_ID;
12 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
14 import akka.actor.ActorRef;
15 import akka.dispatch.OnComplete;
16 import akka.pattern.Patterns;
17 import akka.util.Timeout;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Strings;
22 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
23 import java.util.Collection;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.TimeUnit;
27 import javax.annotation.Nonnull;
28 import org.opendaylight.controller.cluster.access.concepts.MemberName;
29 import org.opendaylight.controller.cluster.datastore.config.Configuration;
30 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
31 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
32 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
33 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
34 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
35 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
36 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
37 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
38 import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
39 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
40 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
41 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
42 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
43 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
44 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
45 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
46 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.EntityOwners;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import scala.concurrent.Await;
57 import scala.concurrent.Future;
58 import scala.concurrent.duration.Duration;
61 * The distributed implementation of the EntityOwnershipService.
63 * @author Thomas Pantelis
65 public class DistributedEntityOwnershipService implements DOMEntityOwnershipService, AutoCloseable {
67 static final String ENTITY_OWNERSHIP_SHARD_NAME = "entity-ownership";
69 private static final Logger LOG = LoggerFactory.getLogger(DistributedEntityOwnershipService.class);
70 private static final Timeout MESSAGE_TIMEOUT = new Timeout(1, TimeUnit.MINUTES);
72 private final ConcurrentMap<DOMEntity, DOMEntity> registeredEntities = new ConcurrentHashMap<>();
73 private final ActorContext context;
75 private volatile ActorRef localEntityOwnershipShard;
76 private volatile DataTree localEntityOwnershipShardDataTree;
78 DistributedEntityOwnershipService(final ActorContext context) {
79 this.context = Preconditions.checkNotNull(context);
82 public static DistributedEntityOwnershipService start(final ActorContext context,
83 final EntityOwnerSelectionStrategyConfig strategyConfig) {
84 ActorRef shardManagerActor = context.getShardManager();
86 Configuration configuration = context.getConfiguration();
87 Collection<MemberName> entityOwnersMemberNames = configuration.getUniqueMemberNamesForAllShards();
88 CreateShard createShard = new CreateShard(new ModuleShardConfiguration(EntityOwners.QNAME.getNamespace(),
89 "entity-owners", ENTITY_OWNERSHIP_SHARD_NAME, ModuleShardStrategy.NAME, entityOwnersMemberNames),
90 newShardBuilder(context, strategyConfig), null);
92 Future<Object> createFuture = context.executeOperationAsync(shardManagerActor,
93 createShard, MESSAGE_TIMEOUT);
95 createFuture.onComplete(new OnComplete<Object>() {
97 public void onComplete(final Throwable failure, final Object response) {
98 if (failure != null) {
99 LOG.error("Failed to create {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
101 LOG.info("Successfully created {} shard", ENTITY_OWNERSHIP_SHARD_NAME);
104 }, context.getClientDispatcher());
106 return new DistributedEntityOwnershipService(context);
109 private void executeEntityOwnershipShardOperation(final ActorRef shardActor, final Object message) {
110 Future<Object> future = context.executeOperationAsync(shardActor, message, MESSAGE_TIMEOUT);
111 future.onComplete(new OnComplete<Object>() {
113 public void onComplete(final Throwable failure, final Object response) {
114 if (failure != null) {
115 LOG.debug("Error sending message {} to {}", message, shardActor, failure);
117 LOG.debug("{} message to {} succeeded", message, shardActor);
120 }, context.getClientDispatcher());
124 void executeLocalEntityOwnershipShardOperation(final Object message) {
125 if (localEntityOwnershipShard == null) {
126 Future<ActorRef> future = context.findLocalShardAsync(ENTITY_OWNERSHIP_SHARD_NAME);
127 future.onComplete(new OnComplete<ActorRef>() {
129 public void onComplete(final Throwable failure, final ActorRef shardActor) {
130 if (failure != null) {
131 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
133 localEntityOwnershipShard = shardActor;
134 executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
137 }, context.getClientDispatcher());
140 executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
145 public DOMEntityOwnershipCandidateRegistration registerCandidate(final DOMEntity entity)
146 throws CandidateAlreadyRegisteredException {
147 Preconditions.checkNotNull(entity, "entity cannot be null");
149 if (registeredEntities.putIfAbsent(entity, entity) != null) {
150 throw new CandidateAlreadyRegisteredException(entity);
153 RegisterCandidateLocal registerCandidate = new RegisterCandidateLocal(entity);
155 LOG.debug("Registering candidate with message: {}", registerCandidate);
157 executeLocalEntityOwnershipShardOperation(registerCandidate);
158 return new DistributedEntityOwnershipCandidateRegistration(entity, this);
161 void unregisterCandidate(final DOMEntity entity) {
162 LOG.debug("Unregistering candidate for {}", entity);
164 executeLocalEntityOwnershipShardOperation(new UnregisterCandidateLocal(entity));
165 registeredEntities.remove(entity);
169 public DOMEntityOwnershipListenerRegistration registerListener(final String entityType,
170 final DOMEntityOwnershipListener listener) {
171 Preconditions.checkNotNull(entityType, "entityType cannot be null");
172 Preconditions.checkNotNull(listener, "listener cannot be null");
174 RegisterListenerLocal registerListener = new RegisterListenerLocal(listener, entityType);
176 LOG.debug("Registering listener with message: {}", registerListener);
178 executeLocalEntityOwnershipShardOperation(registerListener);
179 return new DistributedEntityOwnershipListenerRegistration(listener, entityType, this);
183 @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Unrecognised NullableDecl")
184 public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity forEntity) {
185 Preconditions.checkNotNull(forEntity, "forEntity cannot be null");
187 DataTree dataTree = getLocalEntityOwnershipShardDataTree();
188 if (dataTree == null) {
189 return Optional.absent();
192 java.util.Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
193 entityPath(forEntity.getType(), forEntity.getIdentifier()));
194 if (!entityNode.isPresent()) {
195 return Optional.absent();
198 // Check if there are any candidates, if there are none we do not really have ownership state
199 final MapEntryNode entity = (MapEntryNode) entityNode.get();
200 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optionalCandidates =
201 entity.getChild(CANDIDATE_NODE_ID);
202 final boolean hasCandidates = optionalCandidates.isPresent()
203 && ((MapNode) optionalCandidates.get()).getValue().size() > 0;
204 if (!hasCandidates) {
205 return Optional.absent();
208 MemberName localMemberName = context.getCurrentMemberName();
209 java.util.Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = entity.getChild(
210 ENTITY_OWNER_NODE_ID);
211 String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
212 boolean hasOwner = !Strings.isNullOrEmpty(owner);
213 boolean isOwner = hasOwner && localMemberName.getName().equals(owner);
215 return Optional.of(EntityOwnershipState.from(isOwner, hasOwner));
219 public boolean isCandidateRegistered(@Nonnull final DOMEntity entity) {
220 return registeredEntities.get(entity) != null;
224 @SuppressWarnings("checkstyle:IllegalCatch")
225 DataTree getLocalEntityOwnershipShardDataTree() {
226 if (localEntityOwnershipShardDataTree == null) {
228 if (localEntityOwnershipShard == null) {
229 localEntityOwnershipShard = Await.result(context.findLocalShardAsync(
230 ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
233 localEntityOwnershipShardDataTree = (DataTree) Await.result(Patterns.ask(localEntityOwnershipShard,
234 GetShardDataTree.INSTANCE, MESSAGE_TIMEOUT), Duration.Inf());
235 } catch (Exception e) {
236 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, e);
240 return localEntityOwnershipShardDataTree;
243 void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
244 LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
246 executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));
250 public void close() {
253 private static EntityOwnershipShard.Builder newShardBuilder(final ActorContext context,
254 final EntityOwnerSelectionStrategyConfig strategyConfig) {
255 return EntityOwnershipShard.newBuilder().localMemberName(context.getCurrentMemberName())
256 .ownerSelectionStrategyConfig(strategyConfig);
260 ActorRef getLocalEntityOwnershipShard() {
261 return localEntityOwnershipShard;