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.pattern.Patterns;
29 import com.google.common.annotations.VisibleForTesting;
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.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.impl.schema.ImmutableNodes;
68 import scala.concurrent.Future;
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 Map<String, EntityOwnerSelectionStrategyWrapper> ownerSelectionStrategies = new HashMap<>();
82     private final EntityOwnerSelectionStrategyWrapper defaultEntityOwnerSelectionStrategy;
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.defaultEntityOwnerSelectionStrategy =
94                 createEntityOwnerSelectionStrategyWrapper(FirstCandidateSelectionStrategy.INSTANCE);
95
96         for(String peerId: getRaftActorContext().getPeerIds()) {
97             ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
98             peerIdToMemberNames.put(peerId, shardId.getMemberName());
99         }
100     }
101
102     @Override
103     protected void onDatastoreContext(DatastoreContext context) {
104         super.onDatastoreContext(noPersistenceDatastoreContext(context));
105     }
106
107     @Override
108     protected void onRecoveryComplete() {
109         super.onRecoveryComplete();
110
111         new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
112         new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
113     }
114
115     @Override
116     public void onReceiveCommand(final Object message) throws Exception {
117         if(message instanceof RegisterCandidateLocal) {
118             onRegisterCandidateLocal((RegisterCandidateLocal) message);
119         } else if(message instanceof UnregisterCandidateLocal) {
120             onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
121         } else if(message instanceof CandidateAdded){
122             onCandidateAdded((CandidateAdded) message);
123         } else if(message instanceof CandidateRemoved){
124             onCandidateRemoved((CandidateRemoved) message);
125         } else if(message instanceof PeerDown) {
126             onPeerDown((PeerDown) message);
127         } else if(message instanceof PeerUp) {
128             onPeerUp((PeerUp) message);
129         } else if(message instanceof RegisterListenerLocal) {
130             onRegisterListenerLocal((RegisterListenerLocal)message);
131         } else if(message instanceof UnregisterListenerLocal) {
132             onUnregisterListenerLocal((UnregisterListenerLocal) message);
133         } else if(message instanceof SelectOwner) {
134             onSelectOwner((SelectOwner) message);
135         } else if(!commitCoordinator.handleMessage(message, this)) {
136             super.onReceiveCommand(message);
137         }
138     }
139
140     private void onSelectOwner(SelectOwner selectOwner) {
141         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
142         if(Strings.isNullOrEmpty(currentOwner)) {
143             writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
144                     selectOwner.getOwnerSelectionStrategy()));
145         }
146     }
147
148     private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
149         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
150
151         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
152
153         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
154                 registerCandidate.getEntity().getId(), localMemberName);
155         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
156
157         getSender().tell(SuccessReply.INSTANCE, getSelf());
158     }
159
160     private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
161         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
162
163         Entity entity = unregisterCandidate.getEntity();
164         listenerSupport.unsetHasCandidateForEntity(entity);
165
166         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
167         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
168
169         getSender().tell(SuccessReply.INSTANCE, getSelf());
170     }
171
172     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
173         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
174
175         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
176
177         getSender().tell(SuccessReply.INSTANCE, getSelf());
178
179         searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
180             @Override
181             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
182                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
183                         entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
184                 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
185                 if (registerListener.getEntityType().equals(entityType)) {
186                     Entity entity = new Entity(entityType,
187                             (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
188                     listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
189                 }
190             }
191         });
192     }
193
194     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
195         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
196
197         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
198
199         getSender().tell(SuccessReply.INSTANCE, getSelf());
200     }
201
202     void tryCommitModifications(final BatchedModifications modifications) {
203         if(isLeader()) {
204             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
205
206             // Note that it's possible the commit won't get consensus and will timeout and not be applied
207             // to the state. However we don't need to retry it in that case b/c it will be committed to
208             // the journal first and, once a majority of followers come back on line and it is replicated,
209             // it will be applied at that point.
210             handleBatchedModificationsLocal(modifications, self());
211         } else {
212             final ActorSelection leader = getLeader();
213             if (leader != null) {
214                 if(LOG.isDebugEnabled()) {
215                     LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
216                             modifications.getTransactionID(), leader);
217                 }
218
219                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
220                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
221
222                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
223             }
224         }
225     }
226
227     boolean hasLeader() {
228         return getLeader() != null && !isIsolatedLeader();
229     }
230
231     @Override
232     protected void onStateChanged() {
233         super.onStateChanged();
234
235         commitCoordinator.onStateChanged(this, isLeader());
236     }
237
238     @Override
239     protected void onLeaderChanged(String oldLeader, String newLeader) {
240         super.onLeaderChanged(oldLeader, newLeader);
241
242         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
243                 newLeader, isLeader());
244
245         if(isLeader()) {
246             // We were just elected leader. If the old leader is down, select new owners for the entities
247             // owned by the down leader.
248
249             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
250
251             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
252
253             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
254                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
255             }
256         }
257     }
258
259     private void onCandidateRemoved(CandidateRemoved message) {
260         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
261
262         if(isLeader()) {
263             String currentOwner = getCurrentOwner(message.getEntityPath());
264             if(message.getRemovedCandidate().equals(currentOwner)){
265                 writeNewOwner(message.getEntityPath(),
266                         newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategyWrapper(message.getEntityPath())));
267             }
268         } else {
269             // We're not the leader. If the removed candidate is our local member then check if we actually
270             // have a local candidate registered. If we do then we must have been partitioned from the leader
271             // and the leader removed our candidate since the leader can't tell the difference between a
272             // temporary network partition and a node's process actually restarted. So, in that case, re-add
273             // our candidate.
274             if(localMemberName.equals(message.getRemovedCandidate()) &&
275                     listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
276                 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
277                     " - adding back local candidate", message.getEntityPath());
278
279                 commitCoordinator.commitModification(new MergeModification(
280                         candidatePath(message.getEntityPath(), localMemberName),
281                         candidateMapEntry(localMemberName)), this);
282             }
283         }
284     }
285
286     private EntityOwnerSelectionStrategyWrapper getEntityOwnerElectionStrategyWrapper(YangInstanceIdentifier entityPath) {
287         String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
288         EntityOwnerSelectionStrategyWrapper entityOwnerSelectionStrategy = ownerSelectionStrategies.get(entityType);
289
290         if(entityOwnerSelectionStrategy == null){
291             entityOwnerSelectionStrategy = defaultEntityOwnerSelectionStrategy;
292             ownerSelectionStrategies.put(entityType, entityOwnerSelectionStrategy);
293         }
294
295         return entityOwnerSelectionStrategy;
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         if(Strings.isNullOrEmpty(currentOwner)){
311             EntityOwnerSelectionStrategyWrapper strategy = getEntityOwnerElectionStrategyWrapper(message.getEntityPath());
312             if(strategy.selectionDelayInMillis() == 0L) {
313                 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
314             } else {
315                 strategy.scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates());
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), getEntityOwnerElectionStrategyWrapper(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 static 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     private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
443         Collection<String> viableCandidates = getViableCandidates(candidates);
444         if(viableCandidates.size() == 0){
445             return "";
446         }
447         return ownerSelectionStrategy.newOwner(viableCandidates);
448     }
449
450     private Collection<String> getViableCandidates(Collection<String> candidates) {
451         Collection<String> viableCandidates = new ArrayList<>();
452
453         for (String candidate : candidates) {
454             if (!downPeerMemberNames.contains(candidate)) {
455                 viableCandidates.add(candidate);
456             }
457         }
458         return viableCandidates;
459     }
460
461     private String getCurrentOwner(YangInstanceIdentifier entityId) {
462         Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
463         if(optionalEntityOwner.isPresent()){
464             return optionalEntityOwner.get().getValue().toString();
465         }
466         return null;
467     }
468
469     private static interface EntityWalker {
470         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
471     }
472
473     private EntityOwnerSelectionStrategyWrapper createEntityOwnerSelectionStrategyWrapper(EntityOwnerSelectionStrategy entityOwnerSelectionStrategy){
474         return new EntityOwnerSelectionStrategyWrapper(context().system().scheduler(), self(),
475                 context().system().dispatcher(), entityOwnerSelectionStrategy);
476     }
477
478     @VisibleForTesting
479     void addEntityOwnerSelectionStrategy(String entityType, Class<? extends EntityOwnerSelectionStrategy> ownerSelectionStrategyClass){
480         try {
481             EntityOwnerSelectionStrategyWrapper strategy =
482                     createEntityOwnerSelectionStrategyWrapper(ownerSelectionStrategyClass.newInstance());
483             ownerSelectionStrategies.put(entityType, strategy);
484         } catch (InstantiationException | IllegalAccessException e) {
485             LOG.error("Exception occurred when adding election strategy", e);
486         }
487     }
488
489     public static Builder newBuilder() {
490         return new Builder();
491     }
492
493     static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
494         private String localMemberName;
495
496         protected Builder() {
497             super(EntityOwnershipShard.class);
498         }
499
500         Builder localMemberName(String localMemberName) {
501             checkSealed();
502             this.localMemberName = localMemberName;
503             return this;
504         }
505
506         @Override
507         protected void verify() {
508             super.verify();
509             Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
510         }
511     }
512 }