a2a63f42293372b67a9bd10d2062fd3b6dffe155
[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 import akka.actor.ActorRef;
14 import akka.dispatch.OnComplete;
15 import akka.pattern.Patterns;
16 import akka.util.Timeout;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Optional;
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Strings;
21 import java.util.Collection;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
27 import org.opendaylight.controller.cluster.datastore.config.Configuration;
28 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
29 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
30 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
31 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
32 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
33 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
34 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
35 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
36 import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
37 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
38 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
39 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
40 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
41 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
42 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
43 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.EntityOwners;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
46 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
47 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import scala.concurrent.Await;
54 import scala.concurrent.Future;
55 import scala.concurrent.duration.Duration;
56
57 /**
58  * The distributed implementation of the EntityOwnershipService.
59  *
60  * @author Thomas Pantelis
61  */
62 public class DistributedEntityOwnershipService implements EntityOwnershipService, AutoCloseable {
63     private static final Logger LOG = LoggerFactory.getLogger(DistributedEntityOwnershipService.class);
64     static final String ENTITY_OWNERSHIP_SHARD_NAME = "entity-ownership";
65     private static final Timeout MESSAGE_TIMEOUT = new Timeout(1, TimeUnit.MINUTES);
66
67     private final DistributedDataStore datastore;
68     private final EntityOwnerSelectionStrategyConfig strategyConfig;
69     private final ConcurrentMap<Entity, Entity> registeredEntities = new ConcurrentHashMap<>();
70     private volatile ActorRef localEntityOwnershipShard;
71     private volatile DataTree localEntityOwnershipShardDataTree;
72
73     public DistributedEntityOwnershipService(DistributedDataStore datastore, EntityOwnerSelectionStrategyConfig strategyConfig) {
74         this.datastore = Preconditions.checkNotNull(datastore);
75         this.strategyConfig = Preconditions.checkNotNull(strategyConfig);
76     }
77
78     public void start() {
79         ActorRef shardManagerActor = datastore.getActorContext().getShardManager();
80
81         Configuration configuration = datastore.getActorContext().getConfiguration();
82         Collection<String> entityOwnersMemberNames = configuration.getUniqueMemberNamesForAllShards();
83         CreateShard createShard = new CreateShard(new ModuleShardConfiguration(EntityOwners.QNAME.getNamespace(),
84                 "entity-owners", ENTITY_OWNERSHIP_SHARD_NAME, ModuleShardStrategy.NAME, entityOwnersMemberNames),
85                         newShardBuilder(), null);
86
87         Future<Object> createFuture = datastore.getActorContext().executeOperationAsync(shardManagerActor,
88                 createShard, MESSAGE_TIMEOUT);
89
90         createFuture.onComplete(new OnComplete<Object>() {
91             @Override
92             public void onComplete(Throwable failure, Object response) {
93                 if(failure != null) {
94                     LOG.error("Failed to create {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
95                 } else {
96                     LOG.info("Successfully created {} shard", ENTITY_OWNERSHIP_SHARD_NAME);
97                 }
98             }
99         }, datastore.getActorContext().getClientDispatcher());
100     }
101
102     private void executeEntityOwnershipShardOperation(final ActorRef shardActor, final Object message) {
103         Future<Object> future = datastore.getActorContext().executeOperationAsync(shardActor, message, MESSAGE_TIMEOUT);
104         future.onComplete(new OnComplete<Object>() {
105             @Override
106             public void onComplete(Throwable failure, Object response) {
107                 if(failure != null) {
108                     LOG.debug("Error sending message {} to {}", message, shardActor, failure);
109                 } else {
110                     LOG.debug("{} message to {} succeeded", message, shardActor, failure);
111                 }
112             }
113         }, datastore.getActorContext().getClientDispatcher());
114     }
115
116     private void executeLocalEntityOwnershipShardOperation(final Object message) {
117         if(localEntityOwnershipShard == null) {
118             Future<ActorRef> future = datastore.getActorContext().findLocalShardAsync(ENTITY_OWNERSHIP_SHARD_NAME);
119             future.onComplete(new OnComplete<ActorRef>() {
120                 @Override
121                 public void onComplete(Throwable failure, ActorRef shardActor) {
122                     if(failure != null) {
123                         LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
124                     } else {
125                         localEntityOwnershipShard = shardActor;
126                         executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
127                     }
128                 }
129             }, datastore.getActorContext().getClientDispatcher());
130
131         } else {
132             executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
133         }
134     }
135
136     @Override
137     public EntityOwnershipCandidateRegistration registerCandidate(Entity entity)
138             throws CandidateAlreadyRegisteredException {
139         Preconditions.checkNotNull(entity, "entity cannot be null");
140
141         if(registeredEntities.putIfAbsent(entity, entity) != null) {
142             throw new CandidateAlreadyRegisteredException(entity);
143         }
144
145         RegisterCandidateLocal registerCandidate = new RegisterCandidateLocal(entity);
146
147         LOG.debug("Registering candidate with message: {}", registerCandidate);
148
149         executeLocalEntityOwnershipShardOperation(registerCandidate);
150         return new DistributedEntityOwnershipCandidateRegistration(entity, this);
151     }
152
153     void unregisterCandidate(Entity entity) {
154         LOG.debug("Unregistering candidate for {}", entity);
155
156         executeLocalEntityOwnershipShardOperation(new UnregisterCandidateLocal(entity));
157         registeredEntities.remove(entity);
158     }
159
160     @Override
161     public EntityOwnershipListenerRegistration registerListener(String entityType, EntityOwnershipListener listener) {
162         Preconditions.checkNotNull(entityType, "entityType cannot be null");
163         Preconditions.checkNotNull(listener, "listener cannot be null");
164
165         RegisterListenerLocal registerListener = new RegisterListenerLocal(listener, entityType);
166
167         LOG.debug("Registering listener with message: {}", registerListener);
168
169         executeLocalEntityOwnershipShardOperation(registerListener);
170         return new DistributedEntityOwnershipListenerRegistration(listener, entityType, this);
171     }
172
173     @Override
174     public Optional<EntityOwnershipState> getOwnershipState(Entity forEntity) {
175         Preconditions.checkNotNull(forEntity, "forEntity cannot be null");
176
177         DataTree dataTree = getLocalEntityOwnershipShardDataTree();
178         if (dataTree == null) {
179             return Optional.absent();
180         }
181
182         Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
183                 entityPath(forEntity.getType(), forEntity.getId()));
184         if (!entityNode.isPresent()) {
185             return Optional.absent();
186         }
187
188         // Check if there are any candidates, if there are none we do not really have ownership state
189         final MapEntryNode entity = (MapEntryNode) entityNode.get();
190         final Optional<DataContainerChild<? extends PathArgument, ?>> optionalCandidates = entity.getChild(CANDIDATE_NODE_ID);
191         final boolean hasCandidates = optionalCandidates.isPresent() && ((MapNode) optionalCandidates.get()).getValue().size() > 0;
192         if(!hasCandidates){
193             return Optional.absent();
194         }
195
196         String localMemberName = datastore.getActorContext().getCurrentMemberName();
197         Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = entity.getChild(ENTITY_OWNER_NODE_ID);
198         String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
199         boolean hasOwner = !Strings.isNullOrEmpty(owner);
200         boolean isOwner = hasOwner && localMemberName.equals(owner);
201
202         return Optional.of(new EntityOwnershipState(isOwner, hasOwner));
203     }
204
205     @Override
206     public boolean isCandidateRegistered(@Nonnull Entity entity) {
207         return registeredEntities.get(entity) != null;
208     }
209
210     private DataTree getLocalEntityOwnershipShardDataTree() {
211         if(localEntityOwnershipShardDataTree == null) {
212             try {
213                 if(localEntityOwnershipShard == null) {
214                     localEntityOwnershipShard = Await.result(datastore.getActorContext().findLocalShardAsync(
215                             ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
216                 }
217
218                 localEntityOwnershipShardDataTree = (DataTree) Await.result(Patterns.ask(localEntityOwnershipShard,
219                         GetShardDataTree.INSTANCE, MESSAGE_TIMEOUT), Duration.Inf());
220             } catch (Exception e) {
221                 LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, e);
222             }
223         }
224
225         return localEntityOwnershipShardDataTree;
226     }
227
228     void unregisterListener(String entityType, EntityOwnershipListener listener) {
229         LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
230
231         executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));
232     }
233
234     @Override
235     public void close() {
236     }
237
238     protected EntityOwnershipShard.Builder newShardBuilder() {
239         return EntityOwnershipShard.newBuilder().localMemberName(datastore.getActorContext().getCurrentMemberName())
240                 .ownerSelectionStrategyConfig(this.strategyConfig);
241     }
242
243     @VisibleForTesting
244     ActorRef getLocalEntityOwnershipShard() {
245         return localEntityOwnershipShard;
246     }
247 }