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