ab4d9b2de08998b760a84ba16d548d70823e5b37
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / entityownership / DistributedEntityOwnershipService.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.entityownership;
9
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;
13
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.Preconditions;
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.ActorUtils;
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;
58
59 /**
60  * The distributed implementation of the EntityOwnershipService.
61  *
62  * @author Thomas Pantelis
63  */
64 public class DistributedEntityOwnershipService implements DOMEntityOwnershipService, AutoCloseable {
65     @VisibleForTesting
66     static final String ENTITY_OWNERSHIP_SHARD_NAME = "entity-ownership";
67
68     private static final Logger LOG = LoggerFactory.getLogger(DistributedEntityOwnershipService.class);
69     private static final Timeout MESSAGE_TIMEOUT = new Timeout(1, TimeUnit.MINUTES);
70
71     private final ConcurrentMap<DOMEntity, DOMEntity> registeredEntities = new ConcurrentHashMap<>();
72     private final ActorUtils context;
73
74     private volatile ActorRef localEntityOwnershipShard;
75     private volatile DataTree localEntityOwnershipShardDataTree;
76
77     DistributedEntityOwnershipService(final ActorUtils context) {
78         this.context = Preconditions.checkNotNull(context);
79     }
80
81     public static DistributedEntityOwnershipService start(final ActorUtils context,
82             final EntityOwnerSelectionStrategyConfig strategyConfig) {
83         ActorRef shardManagerActor = context.getShardManager();
84
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);
90
91         Future<Object> createFuture = context.executeOperationAsync(shardManagerActor,
92                 createShard, MESSAGE_TIMEOUT);
93
94         createFuture.onComplete(new OnComplete<Object>() {
95             @Override
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);
99                 } else {
100                     LOG.info("Successfully created {} shard", ENTITY_OWNERSHIP_SHARD_NAME);
101                 }
102             }
103         }, context.getClientDispatcher());
104
105         return new DistributedEntityOwnershipService(context);
106     }
107
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>() {
111             @Override
112             public void onComplete(final Throwable failure, final Object response) {
113                 if (failure != null) {
114                     LOG.debug("Error sending message {} to {}", message, shardActor, failure);
115                 } else {
116                     LOG.debug("{} message to {} succeeded", message, shardActor);
117                 }
118             }
119         }, context.getClientDispatcher());
120     }
121
122     @VisibleForTesting
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>() {
127                 @Override
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);
131                     } else {
132                         localEntityOwnershipShard = shardActor;
133                         executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
134                     }
135                 }
136             }, context.getClientDispatcher());
137
138         } else {
139             executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
140         }
141     }
142
143     @Override
144     public DOMEntityOwnershipCandidateRegistration registerCandidate(final DOMEntity entity)
145             throws CandidateAlreadyRegisteredException {
146         Preconditions.checkNotNull(entity, "entity cannot be null");
147
148         if (registeredEntities.putIfAbsent(entity, entity) != null) {
149             throw new CandidateAlreadyRegisteredException(entity);
150         }
151
152         RegisterCandidateLocal registerCandidate = new RegisterCandidateLocal(entity);
153
154         LOG.debug("Registering candidate with message: {}", registerCandidate);
155
156         executeLocalEntityOwnershipShardOperation(registerCandidate);
157         return new DistributedEntityOwnershipCandidateRegistration(entity, this);
158     }
159
160     void unregisterCandidate(final DOMEntity entity) {
161         LOG.debug("Unregistering candidate for {}", entity);
162
163         executeLocalEntityOwnershipShardOperation(new UnregisterCandidateLocal(entity));
164         registeredEntities.remove(entity);
165     }
166
167     @Override
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");
172
173         RegisterListenerLocal registerListener = new RegisterListenerLocal(listener, entityType);
174
175         LOG.debug("Registering listener with message: {}", registerListener);
176
177         executeLocalEntityOwnershipShardOperation(registerListener);
178         return new DistributedEntityOwnershipListenerRegistration(listener, entityType, this);
179     }
180
181     @Override
182     public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity forEntity) {
183         Preconditions.checkNotNull(forEntity, "forEntity cannot be null");
184
185         DataTree dataTree = getLocalEntityOwnershipShardDataTree();
186         if (dataTree == null) {
187             return Optional.empty();
188         }
189
190         Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
191                 entityPath(forEntity.getType(), forEntity.getIdentifier()));
192         if (!entityNode.isPresent()) {
193             return Optional.empty();
194         }
195
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.empty();
204         }
205
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);
211
212         return Optional.of(EntityOwnershipState.from(isOwner, hasOwner));
213     }
214
215     @Override
216     public boolean isCandidateRegistered(@Nonnull final DOMEntity entity) {
217         return registeredEntities.get(entity) != null;
218     }
219
220     @VisibleForTesting
221     @SuppressWarnings("checkstyle:IllegalCatch")
222     DataTree getLocalEntityOwnershipShardDataTree() {
223         if (localEntityOwnershipShardDataTree == null) {
224             try {
225                 if (localEntityOwnershipShard == null) {
226                     localEntityOwnershipShard = Await.result(context.findLocalShardAsync(
227                             ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
228                 }
229
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);
234             }
235         }
236
237         return localEntityOwnershipShardDataTree;
238     }
239
240     void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
241         LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
242
243         executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));
244     }
245
246     @Override
247     public void close() {
248     }
249
250     private static EntityOwnershipShard.Builder newShardBuilder(final ActorUtils context,
251             final EntityOwnerSelectionStrategyConfig strategyConfig) {
252         return EntityOwnershipShard.newBuilder().localMemberName(context.getCurrentMemberName())
253                 .ownerSelectionStrategyConfig(strategyConfig);
254     }
255
256     @VisibleForTesting
257     ActorRef getLocalEntityOwnershipShard() {
258         return localEntityOwnershipShard;
259     }
260 }