Add Delayed Owner selection base on strategy
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / entityownership / EntityOwnershipShard.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_NAME_NODE_ID;
11 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NODE_ID;
12 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_NODE_ID;
13 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_QNAME;
14 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_NODE_ID;
15 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
16 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_NODE_ID;
17 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_QNAME;
18 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPES_PATH;
19 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPE_NODE_ID;
20 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPE_QNAME;
21 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidateMapEntry;
22 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidateNodeKey;
23 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
24 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.createEntity;
25 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
26 import akka.actor.ActorRef;
27 import akka.actor.ActorSelection;
28 import akka.actor.Props;
29 import akka.pattern.Patterns;
30 import com.google.common.annotations.VisibleForTesting;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Strings;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.concurrent.TimeUnit;
40 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
41 import org.opendaylight.controller.cluster.datastore.Shard;
42 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
43 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.SelectOwner;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
49 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategy;
50 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyWrapper;
51 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.FirstCandidateSelectionStrategy;
52 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
53 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
54 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
55 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
56 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
57 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
58 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
59 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
60 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
68 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import scala.concurrent.Future;
71
72 /**
73  * Special Shard for EntityOwnership.
74  *
75  * @author Thomas Pantelis
76  */
77 class EntityOwnershipShard extends Shard {
78     private final String localMemberName;
79     private final EntityOwnershipShardCommitCoordinator commitCoordinator;
80     private final EntityOwnershipListenerSupport listenerSupport;
81     private final Set<String> downPeerMemberNames = new HashSet<>();
82     private final Map<String, String> peerIdToMemberNames = new HashMap<>();
83     private final Map<String, EntityOwnerSelectionStrategyWrapper> ownerSelectionStrategies = new HashMap<>();
84     private final EntityOwnerSelectionStrategyWrapper defaultEntityOwnerSelectionStrategy;
85
86     private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
87         return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
88     }
89
90     protected EntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
91             DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName) {
92         super(name, peerAddresses, noPersistenceDatastoreContext(datastoreContext), schemaContext);
93         this.localMemberName = localMemberName;
94         this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(localMemberName, LOG);
95         this.listenerSupport = new EntityOwnershipListenerSupport(getContext(), persistenceId());
96         this.defaultEntityOwnerSelectionStrategy =
97                 createEntityOwnerSelectionStrategyWrapper(FirstCandidateSelectionStrategy.INSTANCE);
98
99         for(String peerId: peerAddresses.keySet()) {
100             ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
101             peerIdToMemberNames.put(peerId, shardId.getMemberName());
102         }
103     }
104
105     @Override
106     protected void onDatastoreContext(DatastoreContext context) {
107         super.onDatastoreContext(noPersistenceDatastoreContext(context));
108     }
109
110     @Override
111     protected void onRecoveryComplete() {
112         super.onRecoveryComplete();
113
114         new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
115         new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
116     }
117
118     @Override
119     public void onReceiveCommand(final Object message) throws Exception {
120         if(message instanceof RegisterCandidateLocal) {
121             onRegisterCandidateLocal((RegisterCandidateLocal) message);
122         } else if(message instanceof UnregisterCandidateLocal) {
123             onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
124         } else if(message instanceof CandidateAdded){
125             onCandidateAdded((CandidateAdded) message);
126         } else if(message instanceof CandidateRemoved){
127             onCandidateRemoved((CandidateRemoved) message);
128         } else if(message instanceof PeerDown) {
129             onPeerDown((PeerDown) message);
130         } else if(message instanceof PeerUp) {
131             onPeerUp((PeerUp) message);
132         } else if(message instanceof RegisterListenerLocal) {
133             onRegisterListenerLocal((RegisterListenerLocal)message);
134         } else if(message instanceof UnregisterListenerLocal) {
135             onUnregisterListenerLocal((UnregisterListenerLocal) message);
136         } else if(message instanceof SelectOwner) {
137             onSelectOwner((SelectOwner) message);
138         } else if(!commitCoordinator.handleMessage(message, this)) {
139             super.onReceiveCommand(message);
140         }
141     }
142
143     private void onSelectOwner(SelectOwner selectOwner) {
144         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
145         if(Strings.isNullOrEmpty(currentOwner)) {
146             writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
147                     selectOwner.getOwnerSelectionStrategy()));
148         }
149     }
150
151     private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
152         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
153
154         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
155
156         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
157                 registerCandidate.getEntity().getId(), localMemberName);
158         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
159
160         getSender().tell(SuccessReply.INSTANCE, getSelf());
161     }
162
163     private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
164         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
165
166         Entity entity = unregisterCandidate.getEntity();
167         listenerSupport.unsetHasCandidateForEntity(entity);
168
169         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
170         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
171
172         getSender().tell(SuccessReply.INSTANCE, getSelf());
173     }
174
175     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
176         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
177
178         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
179
180         getSender().tell(SuccessReply.INSTANCE, getSelf());
181
182         searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
183             @Override
184             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
185                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
186                         entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
187                 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
188                 if (registerListener.getEntityType().equals(entityType)) {
189                     Entity entity = new Entity(entityType,
190                             (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
191                     listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
192                 }
193             }
194         });
195     }
196
197     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
198         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
199
200         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
201
202         getSender().tell(SuccessReply.INSTANCE, getSelf());
203     }
204
205     void tryCommitModifications(final BatchedModifications modifications) {
206         if(isLeader()) {
207             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
208
209             // Note that it's possible the commit won't get consensus and will timeout and not be applied
210             // to the state. However we don't need to retry it in that case b/c it will be committed to
211             // the journal first and, once a majority of followers come back on line and it is replicated,
212             // it will be applied at that point.
213             handleBatchedModificationsLocal(modifications, self());
214         } else {
215             final ActorSelection leader = getLeader();
216             if (leader != null) {
217                 if(LOG.isDebugEnabled()) {
218                     LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
219                             modifications.getTransactionID(), leader);
220                 }
221
222                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
223                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
224
225                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
226             }
227         }
228     }
229
230     boolean hasLeader() {
231         return getLeader() != null && !isIsolatedLeader();
232     }
233
234     @Override
235     protected void onStateChanged() {
236         super.onStateChanged();
237
238         commitCoordinator.onStateChanged(this, isLeader());
239     }
240
241     @Override
242     protected void onLeaderChanged(String oldLeader, String newLeader) {
243         super.onLeaderChanged(oldLeader, newLeader);
244
245         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
246                 newLeader, isLeader());
247
248         if(isLeader()) {
249             // We were just elected leader. If the old leader is down, select new owners for the entities
250             // owned by the down leader.
251
252             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
253
254             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
255
256             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
257                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
258             }
259         }
260     }
261
262     private void onCandidateRemoved(CandidateRemoved message) {
263         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
264
265         if(isLeader()) {
266             String currentOwner = getCurrentOwner(message.getEntityPath());
267             if(message.getRemovedCandidate().equals(currentOwner)){
268                 writeNewOwner(message.getEntityPath(),
269                         newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategyWrapper(message.getEntityPath())));
270             }
271         } else {
272             // We're not the leader. If the removed candidate is our local member then check if we actually
273             // have a local candidate registered. If we do then we must have been partitioned from the leader
274             // and the leader removed our candidate since the leader can't tell the difference between a
275             // temporary network partition and a node's process actually restarted. So, in that case, re-add
276             // our candidate.
277             if(localMemberName.equals(message.getRemovedCandidate()) &&
278                     listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
279                 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
280                     " - adding back local candidate", message.getEntityPath());
281
282                 commitCoordinator.commitModification(new MergeModification(
283                         candidatePath(message.getEntityPath(), localMemberName),
284                         candidateMapEntry(localMemberName)), this);
285             }
286         }
287     }
288
289     private EntityOwnerSelectionStrategyWrapper getEntityOwnerElectionStrategyWrapper(YangInstanceIdentifier entityPath) {
290         String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
291         EntityOwnerSelectionStrategyWrapper entityOwnerSelectionStrategy = ownerSelectionStrategies.get(entityType);
292
293         if(entityOwnerSelectionStrategy == null){
294             entityOwnerSelectionStrategy = defaultEntityOwnerSelectionStrategy;
295             ownerSelectionStrategies.put(entityType, entityOwnerSelectionStrategy);
296         }
297
298         return entityOwnerSelectionStrategy;
299     }
300
301     private void onCandidateAdded(CandidateAdded message) {
302         if(!isLeader()){
303             return;
304         }
305
306         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
307
308         // Since a node's candidate member is only added by the node itself, we can assume the node is up so
309         // remove it from the downPeerMemberNames.
310         downPeerMemberNames.remove(message.getNewCandidate());
311
312         String currentOwner = getCurrentOwner(message.getEntityPath());
313         if(Strings.isNullOrEmpty(currentOwner)){
314             EntityOwnerSelectionStrategyWrapper strategy = getEntityOwnerElectionStrategyWrapper(message.getEntityPath());
315             if(strategy.selectionDelayInMillis() == 0L) {
316                 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
317             } else {
318                 strategy.scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates());
319             }
320         }
321     }
322
323     private void onPeerDown(PeerDown peerDown) {
324         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
325
326         String downMemberName = peerDown.getMemberName();
327         if(downPeerMemberNames.add(downMemberName) && isLeader()) {
328             // Remove the down peer as a candidate from all entities.
329             removeCandidateFromEntities(downMemberName);
330         }
331     }
332
333     private void onPeerUp(PeerUp peerUp) {
334         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
335
336         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
337         downPeerMemberNames.remove(peerUp.getMemberName());
338     }
339
340     private void selectNewOwnerForEntitiesOwnedBy(String owner) {
341         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
342         searchForEntitiesOwnedBy(owner, new EntityWalker() {
343             @Override
344             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
345
346                 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
347                         node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
348                         node(ENTITY_OWNER_NODE_ID).build();
349
350                 Object newOwner = newOwner(getCandidateNames(entityNode), getEntityOwnerElectionStrategyWrapper(entityPath));
351
352                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
353
354                 modifications.addModification(new WriteModification(entityPath,
355                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
356             }
357         });
358
359         commitCoordinator.commitModifications(modifications, this);
360     }
361
362     private void removeCandidateFromEntities(final String owner) {
363         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
364         searchForEntities(new EntityWalker() {
365             @Override
366             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
367                 if (hasCandidate(entityNode, owner)) {
368                     YangInstanceIdentifier entityId =
369                             (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
370                     YangInstanceIdentifier candidatePath = candidatePath(
371                             entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
372                             entityId, owner);
373
374                     LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
375                             owner, candidatePath);
376
377                     modifications.addModification(new DeleteModification(candidatePath));
378                 }
379             }
380         });
381
382         commitCoordinator.commitModifications(modifications, this);
383     }
384
385     private boolean hasCandidate(MapEntryNode entity, String candidateName) {
386         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
387     }
388
389     private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
390         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
391         Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
392         if(!possibleEntityTypes.isPresent()) {
393             return;
394         }
395
396         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
397
398         searchForEntities(new EntityWalker() {
399             @Override
400             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
401                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
402                         entityNode.getChild(ENTITY_OWNER_NODE_ID);
403                 if(possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
404                     walker.onEntity(entityTypeNode, entityNode);
405                 }
406             }
407         });
408     }
409
410     private void searchForEntities(EntityWalker walker) {
411         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
412         Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
413         if(!possibleEntityTypes.isPresent()) {
414             return;
415         }
416
417         for(MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
418             Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
419                     entityType.getChild(ENTITY_NODE_ID);
420             if(!possibleEntities.isPresent()) {
421                 continue; // shouldn't happen but handle anyway
422             }
423
424             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
425                 walker.onEntity(entityType, entity);
426             }
427         }
428     }
429
430     private Collection<String> getCandidateNames(MapEntryNode entity) {
431         Collection<MapEntryNode> candidates = ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
432         Collection<String> candidateNames = new ArrayList<>(candidates.size());
433         for(MapEntryNode candidate: candidates) {
434             candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
435         }
436
437         return candidateNames;
438     }
439
440     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
441         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
442
443         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
444                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
445     }
446
447     private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
448         Collection<String> viableCandidates = getViableCandidates(candidates);
449         if(viableCandidates.size() == 0){
450             return "";
451         }
452         return ownerSelectionStrategy.newOwner(viableCandidates);
453     }
454
455     private Collection<String> getViableCandidates(Collection<String> candidates) {
456         Collection<String> viableCandidates = new ArrayList<>();
457
458         for (String candidate : candidates) {
459             if (!downPeerMemberNames.contains(candidate)) {
460                 viableCandidates.add(candidate);
461             }
462         }
463         return viableCandidates;
464     }
465
466     private String getCurrentOwner(YangInstanceIdentifier entityId) {
467         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
468         Optional<NormalizedNode<?, ?>> optionalEntityOwner = snapshot.readNode(entityId.node(ENTITY_OWNER_QNAME));
469         if(optionalEntityOwner.isPresent()){
470             return optionalEntityOwner.get().getValue().toString();
471         }
472         return null;
473     }
474
475     private EntityOwnerSelectionStrategyWrapper createEntityOwnerSelectionStrategyWrapper(EntityOwnerSelectionStrategy entityOwnerSelectionStrategy){
476         return new EntityOwnerSelectionStrategyWrapper(context().system().scheduler(), self(),
477                 context().system().dispatcher(), entityOwnerSelectionStrategy);
478     }
479
480     @VisibleForTesting
481     void addEntityOwnerSelectionStrategy(String entityType, Class<? extends EntityOwnerSelectionStrategy> ownerSelectionStrategyClass){
482         try {
483             EntityOwnerSelectionStrategyWrapper strategy =
484                     createEntityOwnerSelectionStrategyWrapper(ownerSelectionStrategyClass.newInstance());
485             ownerSelectionStrategies.put(entityType, strategy);
486         } catch (InstantiationException | IllegalAccessException e) {
487             LOG.error("Exception occurred when adding election strategy", e);
488         }
489     }
490
491     public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
492             final DatastoreContext datastoreContext, final SchemaContext schemaContext, final String localMemberName) {
493         return Props.create(new Creator(name, peerAddresses, datastoreContext, schemaContext, localMemberName));
494     }
495
496     private static class Creator extends AbstractShardCreator {
497         private static final long serialVersionUID = 1L;
498
499         private final String localMemberName;
500
501         Creator(final ShardIdentifier name, final Map<String, String> peerAddresses,
502                 final DatastoreContext datastoreContext, final SchemaContext schemaContext,
503                 final String localMemberName) {
504             super(name, peerAddresses, datastoreContext, schemaContext);
505             this.localMemberName = localMemberName;
506         }
507
508         @Override
509         public Shard create() throws Exception {
510             return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
511         }
512     }
513
514     private static interface EntityWalker {
515         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
516     }
517
518 }