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