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