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