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 java.util.Collection;
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 private DistributedEntityOwnershipService(final ActorContext context) {
78 this.context = Preconditions.checkNotNull(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,
92 createShard, MESSAGE_TIMEOUT);
94 createFuture.onComplete(new OnComplete<Object>() {
96 public void onComplete(final Throwable failure, final Object response) {
97 if (failure != null) {
98 LOG.error("Failed to create {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
100 LOG.info("Successfully created {} shard", ENTITY_OWNERSHIP_SHARD_NAME);
103 }, context.getClientDispatcher());
105 return new DistributedEntityOwnershipService(context);
108 private void executeEntityOwnershipShardOperation(final ActorRef shardActor, final Object message) {
109 Future<Object> future = context.executeOperationAsync(shardActor, message, MESSAGE_TIMEOUT);
110 future.onComplete(new OnComplete<Object>() {
112 public void onComplete(final Throwable failure, final Object response) {
113 if (failure != null) {
114 LOG.debug("Error sending message {} to {}", message, shardActor, failure);
116 LOG.debug("{} message to {} succeeded", message, shardActor);
119 }, context.getClientDispatcher());
123 void executeLocalEntityOwnershipShardOperation(final Object message) {
124 if (localEntityOwnershipShard == null) {
125 Future<ActorRef> future = context.findLocalShardAsync(ENTITY_OWNERSHIP_SHARD_NAME);
126 future.onComplete(new OnComplete<ActorRef>() {
128 public void onComplete(final Throwable failure, final ActorRef shardActor) {
129 if (failure != null) {
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 Preconditions.checkNotNull(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 Preconditions.checkNotNull(entityType, "entityType cannot be null");
171 Preconditions.checkNotNull(listener, "listener cannot be null");
173 RegisterListenerLocal registerListener = new RegisterListenerLocal(listener, entityType);
175 LOG.debug("Registering listener with message: {}", registerListener);
177 executeLocalEntityOwnershipShardOperation(registerListener);
178 return new DistributedEntityOwnershipListenerRegistration(listener, entityType, this);
182 public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity forEntity) {
183 Preconditions.checkNotNull(forEntity, "forEntity cannot be null");
185 DataTree dataTree = getLocalEntityOwnershipShardDataTree();
186 if (dataTree == null) {
187 return Optional.absent();
190 Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
191 entityPath(forEntity.getType(), forEntity.getIdentifier()));
192 if (!entityNode.isPresent()) {
193 return Optional.absent();
196 // Check if there are any candidates, if there are none we do not really have ownership state
197 final MapEntryNode entity = (MapEntryNode) entityNode.get();
198 final Optional<DataContainerChild<? extends PathArgument, ?>> optionalCandidates =
199 entity.getChild(CANDIDATE_NODE_ID);
200 final boolean hasCandidates = optionalCandidates.isPresent()
201 && ((MapNode) optionalCandidates.get()).getValue().size() > 0;
202 if (!hasCandidates) {
203 return Optional.absent();
206 MemberName localMemberName = context.getCurrentMemberName();
207 Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = entity.getChild(ENTITY_OWNER_NODE_ID);
208 String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
209 boolean hasOwner = !Strings.isNullOrEmpty(owner);
210 boolean isOwner = hasOwner && localMemberName.getName().equals(owner);
212 return Optional.of(EntityOwnershipState.from(isOwner, hasOwner));
216 public boolean isCandidateRegistered(@Nonnull final DOMEntity entity) {
217 return registeredEntities.get(entity) != null;
221 @SuppressWarnings("checkstyle:IllegalCatch")
222 DataTree getLocalEntityOwnershipShardDataTree() {
223 if (localEntityOwnershipShardDataTree == null) {
225 if (localEntityOwnershipShard == null) {
226 localEntityOwnershipShard = Await.result(context.findLocalShardAsync(
227 ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
230 localEntityOwnershipShardDataTree = (DataTree) Await.result(Patterns.ask(localEntityOwnershipShard,
231 GetShardDataTree.INSTANCE, MESSAGE_TIMEOUT), Duration.Inf());
232 } catch (Exception e) {
233 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, e);
237 return localEntityOwnershipShardDataTree;
240 void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
241 LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
243 executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));
247 public void close() {
250 private static EntityOwnershipShard.Builder newShardBuilder(final ActorContext context,
251 final EntityOwnerSelectionStrategyConfig strategyConfig) {
252 return EntityOwnershipShard.newBuilder().localMemberName(context.getCurrentMemberName())
253 .ownerSelectionStrategyConfig(strategyConfig);
257 ActorRef getLocalEntityOwnershipShard() {
258 return localEntityOwnershipShard;