Adjust to yangtools-2.0.0 changes
[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.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;
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 ActorContext context;
73
74     private volatile ActorRef localEntityOwnershipShard;
75     private volatile DataTree localEntityOwnershipShardDataTree;
76
77     DistributedEntityOwnershipService(final ActorContext context) {
78         this.context = Preconditions.checkNotNull(context);
79     }
80
81     public static DistributedEntityOwnershipService start(final ActorContext 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.absent();
188         }
189
190         java.util.Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
191                 entityPath(forEntity.getType(), forEntity.getIdentifier()));
192         if (!entityNode.isPresent()) {
193             return Optional.absent();
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 java.util.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();
204         }
205
206         MemberName localMemberName = context.getCurrentMemberName();
207         java.util.Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = entity.getChild(
208             ENTITY_OWNER_NODE_ID);
209         String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
210         boolean hasOwner = !Strings.isNullOrEmpty(owner);
211         boolean isOwner = hasOwner && localMemberName.getName().equals(owner);
212
213         return Optional.of(EntityOwnershipState.from(isOwner, hasOwner));
214     }
215
216     @Override
217     public boolean isCandidateRegistered(@Nonnull final DOMEntity entity) {
218         return registeredEntities.get(entity) != null;
219     }
220
221     @VisibleForTesting
222     @SuppressWarnings("checkstyle:IllegalCatch")
223     DataTree getLocalEntityOwnershipShardDataTree() {
224         if (localEntityOwnershipShardDataTree == null) {
225             try {
226                 if (localEntityOwnershipShard == null) {
227                     localEntityOwnershipShard = Await.result(context.findLocalShardAsync(
228                             ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
229                 }
230
231                 localEntityOwnershipShardDataTree = (DataTree) Await.result(Patterns.ask(localEntityOwnershipShard,
232                         GetShardDataTree.INSTANCE, MESSAGE_TIMEOUT), Duration.Inf());
233             } catch (Exception e) {
234                 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, e);
235             }
236         }
237
238         return localEntityOwnershipShardDataTree;
239     }
240
241     void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
242         LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
243
244         executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));
245     }
246
247     @Override
248     public void close() {
249     }
250
251     private static EntityOwnershipShard.Builder newShardBuilder(final ActorContext context,
252             final EntityOwnerSelectionStrategyConfig strategyConfig) {
253         return EntityOwnershipShard.newBuilder().localMemberName(context.getCurrentMemberName())
254                 .ownerSelectionStrategyConfig(strategyConfig);
255     }
256
257     @VisibleForTesting
258     ActorRef getLocalEntityOwnershipShard() {
259         return localEntityOwnershipShard;
260     }
261 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.