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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.