Migrate NodeIdentifierWithPredicates.getKeyValues()
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / entityownership / EntityOwnershipShard.java
index 47de1195e428507599d82f81f04c1907e49654c1..6e1d1a855a5ff0c99ec2df73ab2847fa398b0412 100644 (file)
@@ -30,15 +30,17 @@ import akka.cluster.ClusterEvent.CurrentClusterState;
 import akka.cluster.Member;
 import akka.cluster.MemberStatus;
 import akka.pattern.Patterns;
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import org.opendaylight.controller.cluster.access.concepts.MemberName;
@@ -54,14 +56,17 @@ import org.opendaylight.controller.cluster.datastore.entityownership.messages.Un
 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategy;
 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
+import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
+import org.opendaylight.controller.cluster.datastore.modification.Modification;
 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
 import org.opendaylight.controller.cluster.raft.RaftState;
+import org.opendaylight.controller.cluster.raft.VotingState;
 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -88,7 +93,7 @@ class EntityOwnershipShard extends Shard {
     private final EntityOwnershipStatistics entityOwnershipStatistics;
     private boolean removeAllInitialCandidates = true;
 
-    protected EntityOwnershipShard(Builder builder) {
+    protected EntityOwnershipShard(final Builder builder) {
         super(builder);
         this.localMemberName = builder.localMemberName;
         this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(builder.localMemberName, LOG);
@@ -98,12 +103,12 @@ class EntityOwnershipShard extends Shard {
         this.entityOwnershipStatistics.init(getDataStore());
     }
 
-    private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
+    private static DatastoreContext noPersistenceDatastoreContext(final DatastoreContext datastoreContext) {
         return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
     }
 
     @Override
-    protected void onDatastoreContext(DatastoreContext context) {
+    protected void onDatastoreContext(final DatastoreContext context) {
         super.onDatastoreContext(noPersistenceDatastoreContext(context));
     }
 
@@ -142,13 +147,13 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private void onRemoveAllCandidates(RemoveAllCandidates message) {
+    private void onRemoveAllCandidates(final RemoveAllCandidates message) {
         LOG.debug("{}: onRemoveAllCandidates: {}", persistenceId(), message);
 
         removeCandidateFromEntities(message.getMemberName());
     }
 
-    private void onSelectOwner(SelectOwner selectOwner) {
+    private void onSelectOwner(final SelectOwner selectOwner) {
         LOG.debug("{}: onSelectOwner: {}", persistenceId(), selectOwner);
 
         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
@@ -166,11 +171,9 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
+    private void onRegisterCandidateLocal(final RegisterCandidateLocal registerCandidate) {
         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
 
-        listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
-
         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
                 registerCandidate.getEntity().getIdentifier(), localMemberName.getName());
         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
@@ -178,12 +181,10 @@ class EntityOwnershipShard extends Shard {
         getSender().tell(SuccessReply.INSTANCE, getSelf());
     }
 
-    private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
+    private void onUnregisterCandidateLocal(final UnregisterCandidateLocal unregisterCandidate) {
         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
 
         DOMEntity entity = unregisterCandidate.getEntity();
-        listenerSupport.unsetHasCandidateForEntity(entity);
-
         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getIdentifier(),
                 localMemberName.getName());
         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
@@ -223,7 +224,7 @@ class EntityOwnershipShard extends Shard {
         });
     }
 
-    private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
+    private void onUnregisterListenerLocal(final UnregisterListenerLocal unregisterListener) {
         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
 
         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(),
@@ -258,7 +259,7 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    void possiblyRemoveAllInitialCandidates(ActorSelection leader) {
+    void possiblyRemoveAllInitialCandidates(final ActorSelection leader) {
         // The following handles removing all candidates on startup when re-joining with a remote leader. When a
         // follower is detected as down, the leader will re-assign new owners to entities that were owned by the
         // down member but doesn't remove the down member as a candidate, as the down node may actually be isolated
@@ -341,7 +342,7 @@ class EntityOwnershipShard extends Shard {
     }
 
     @Override
-    protected void onLeaderChanged(String oldLeader, String newLeader) {
+    protected void onLeaderChanged(final String oldLeader, final String newLeader) {
         boolean isLeader = isLeader();
         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
                 newLeader, isLeader);
@@ -378,8 +379,32 @@ class EntityOwnershipShard extends Shard {
         super.onLeaderChanged(oldLeader, newLeader);
     }
 
+    @Override
+    protected void onVotingStateChangeComplete() {
+        // Re-evaluate ownership for all entities - if a member changed from voting to non-voting it should lose
+        // ownership and vice versa it now is a candidate to become owner.
+        final List<Modification> modifications = new ArrayList<>();
+        searchForEntities((entityTypeNode, entityNode) -> {
+            YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH)
+                    .node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier())
+                    .node(ENTITY_OWNER_NODE_ID).build();
+
+            Optional<String> possibleOwner =
+                    entityNode.getChild(ENTITY_OWNER_NODE_ID).map(node -> node.getValue().toString());
+            String newOwner = newOwner(possibleOwner.orElse(null), getCandidateNames(entityNode),
+                    getEntityOwnerElectionStrategy(entityPath));
+
+            if (!newOwner.equals(possibleOwner.orElse(""))) {
+                modifications.add(new WriteModification(entityPath,
+                        ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
+            }
+        });
+
+        commitCoordinator.commitModifications(modifications, this);
+    }
+
     private void initializeDownPeerMemberNamesFromClusterState() {
-        java.util.Optional<Cluster> cluster = getRaftActorContext().getCluster();
+        Optional<Cluster> cluster = getRaftActorContext().getCluster();
         if (!cluster.isPresent()) {
             return;
         }
@@ -406,7 +431,7 @@ class EntityOwnershipShard extends Shard {
         LOG.debug("{}: new downPeerMemberNames: {}", persistenceId(), downPeerMemberNames);
     }
 
-    private void onCandidateRemoved(CandidateRemoved message) {
+    private void onCandidateRemoved(final CandidateRemoved message) {
         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
 
         if (isLeader()) {
@@ -417,12 +442,12 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
+    private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(final YangInstanceIdentifier entityPath) {
         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
         return strategyConfig.createStrategy(entityType, entityOwnershipStatistics.byEntityType(entityType));
     }
 
-    private void onCandidateAdded(CandidateAdded message) {
+    private void onCandidateAdded(final CandidateAdded message) {
         if (!isLeader()) {
             return;
         }
@@ -456,7 +481,7 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private void onPeerDown(PeerDown peerDown) {
+    private void onPeerDown(final PeerDown peerDown) {
         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
 
         MemberName downMemberName = peerDown.getMemberName();
@@ -472,8 +497,8 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private void selectNewOwnerForEntitiesOwnedBy(Set<String> ownedBy) {
-        final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
+    private void selectNewOwnerForEntitiesOwnedBy(final Set<String> ownedBy) {
+        final List<Modification> modifications = new ArrayList<>();
         searchForEntitiesOwnedBy(ownedBy, (entityTypeNode, entityNode) -> {
             YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH)
                     .node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier())
@@ -484,19 +509,19 @@ class EntityOwnershipShard extends Shard {
             if (!newOwner.isEmpty()) {
                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
 
-                modifications.addModification(new WriteModification(entityPath,
-                        ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
+                modifications.add(new WriteModification(entityPath,
+                    ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
 
             } else {
                 LOG.debug("{}: Found entity {} but no other candidates - not clearing owner", persistenceId(),
-                        entityPath, newOwner);
+                        entityPath);
             }
         });
 
         commitCoordinator.commitModifications(modifications, this);
     }
 
-    private void onPeerUp(PeerUp peerUp) {
+    private void onPeerUp(final PeerUp peerUp) {
         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
 
         downPeerMemberNames.remove(peerUp.getMemberName());
@@ -518,17 +543,18 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private Collection<String> getCandidateNames(MapEntryNode entity) {
-        Collection<MapEntryNode> candidates = ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
-        Collection<String> candidateNames = new ArrayList<>(candidates.size());
-        for (MapEntryNode candidate: candidates) {
-            candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
-        }
-
-        return candidateNames;
+    private static Collection<String> getCandidateNames(final MapEntryNode entity) {
+        return entity.getChild(CANDIDATE_NODE_ID).map(child -> {
+            Collection<MapEntryNode> candidates = ((MapNode) child).getValue();
+            Collection<String> candidateNames = new ArrayList<>(candidates.size());
+            for (MapEntryNode candidate: candidates) {
+                candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
+            }
+            return candidateNames;
+        }).orElse(ImmutableList.of());
     }
 
-    private void searchForEntitiesOwnedBy(Set<String> ownedBy, EntityWalker walker) {
+    private void searchForEntitiesOwnedBy(final Set<String> ownedBy, final EntityWalker walker) {
         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), ownedBy);
 
         searchForEntities((entityTypeNode, entityNode) -> {
@@ -542,37 +568,37 @@ class EntityOwnershipShard extends Shard {
     }
 
     private void removeCandidateFromEntities(final MemberName member) {
-        final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
+        final List<Modification> modifications = new ArrayList<>();
         searchForEntities((entityTypeNode, entityNode) -> {
             if (hasCandidate(entityNode, member)) {
-                YangInstanceIdentifier entityId =
-                        (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
-                YangInstanceIdentifier candidatePath = candidatePath(
-                        entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
-                        entityId, member.getName());
+                YangInstanceIdentifier entityId = (YangInstanceIdentifier) entityNode.getIdentifier()
+                        .getValue(ENTITY_ID_QNAME);
+                YangInstanceIdentifier candidatePath = candidatePath(entityTypeNode.getIdentifier()
+                    .getValue(ENTITY_TYPE_QNAME).toString(), entityId, member.getName());
 
                 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
                         member, candidatePath);
 
-                modifications.addModification(new DeleteModification(candidatePath));
+                modifications.add(new DeleteModification(candidatePath));
             }
         });
 
         commitCoordinator.commitModifications(modifications, this);
     }
 
-    private static boolean hasCandidate(MapEntryNode entity, MemberName candidateName) {
-        return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName.getName()))
+    private static boolean hasCandidate(final MapEntryNode entity, final MemberName candidateName) {
+        return entity.getChild(CANDIDATE_NODE_ID)
+                .flatMap(child -> ((MapNode)child).getChild(candidateNodeKey(candidateName.getName())))
                 .isPresent();
     }
 
-    private void searchForEntities(EntityWalker walker) {
+    private void searchForEntities(final EntityWalker walker) {
         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
         if (!possibleEntityTypes.isPresent()) {
             return;
         }
 
-        for (MapEntryNode entityType ((MapNode) possibleEntityTypes.get()).getValue()) {
+        for (MapEntryNode entityType : ((MapNode) possibleEntityTypes.get()).getValue()) {
             Optional<DataContainerChild<?, ?>> possibleEntities = entityType.getChild(ENTITY_NODE_ID);
             if (!possibleEntities.isPresent()) {
                 // shouldn't happen but handle anyway
@@ -585,7 +611,7 @@ class EntityOwnershipShard extends Shard {
         }
     }
 
-    private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
+    private void writeNewOwner(final YangInstanceIdentifier entityPath, final String newOwner) {
         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
 
         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
@@ -595,8 +621,8 @@ class EntityOwnershipShard extends Shard {
     /**
      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
      */
-    private void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
-                                       EntityOwnerSelectionStrategy strategy) {
+    private void scheduleOwnerSelection(final YangInstanceIdentifier entityPath, final Collection<String> allCandidates,
+                                       final EntityOwnerSelectionStrategy strategy) {
         cancelOwnerSelectionTask(entityPath);
 
         LOG.debug("{}: Scheduling owner selection after {} ms", persistenceId(), strategy.getSelectionDelayInMillis());
@@ -608,15 +634,15 @@ class EntityOwnershipShard extends Shard {
         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
     }
 
-    private void cancelOwnerSelectionTask(YangInstanceIdentifier entityPath) {
+    private void cancelOwnerSelectionTask(final YangInstanceIdentifier entityPath) {
         final Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
         if (lastScheduledTask != null && !lastScheduledTask.isCancelled()) {
             lastScheduledTask.cancel();
         }
     }
 
-    private String newOwner(String currentOwner, Collection<String> candidates,
-            EntityOwnerSelectionStrategy ownerSelectionStrategy) {
+    private String newOwner(final String currentOwner, final Collection<String> candidates,
+            final EntityOwnerSelectionStrategy ownerSelectionStrategy) {
         Collection<String> viableCandidates = getViableCandidates(candidates);
         if (viableCandidates.isEmpty()) {
             return "";
@@ -624,23 +650,27 @@ class EntityOwnershipShard extends Shard {
         return ownerSelectionStrategy.newOwner(currentOwner, viableCandidates);
     }
 
-    private Collection<String> getViableCandidates(Collection<String> candidates) {
+    private Collection<String> getViableCandidates(final Collection<String> candidates) {
+        Map<MemberName, VotingState> memberToVotingState = new HashMap<>();
+        getRaftActorContext().getPeers().forEach(peerInfo -> memberToVotingState.put(
+                ShardIdentifier.fromShardIdString(peerInfo.getId()).getMemberName(), peerInfo.getVotingState()));
+
         Collection<String> viableCandidates = new ArrayList<>();
 
         for (String candidate : candidates) {
-            if (!downPeerMemberNames.contains(MemberName.forName(candidate))) {
+            MemberName memberName = MemberName.forName(candidate);
+            if (memberToVotingState.get(memberName) != VotingState.NON_VOTING
+                    && !downPeerMemberNames.contains(memberName)) {
                 viableCandidates.add(candidate);
             }
         }
         return viableCandidates;
     }
 
-    private String getCurrentOwner(YangInstanceIdentifier entityId) {
-        Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
-        if (optionalEntityOwner.isPresent()) {
-            return optionalEntityOwner.get().getValue().toString();
-        }
-        return null;
+    private String getCurrentOwner(final YangInstanceIdentifier entityId) {
+        return getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME))
+                .map(owner -> owner.getValue().toString())
+                .orElse(null);
     }
 
     @FunctionalInterface
@@ -660,13 +690,13 @@ class EntityOwnershipShard extends Shard {
             super(EntityOwnershipShard.class);
         }
 
-        Builder localMemberName(MemberName newLocalMemberName) {
+        Builder localMemberName(final MemberName newLocalMemberName) {
             checkSealed();
             this.localMemberName = newLocalMemberName;
             return this;
         }
 
-        Builder ownerSelectionStrategyConfig(EntityOwnerSelectionStrategyConfig newOwnerSelectionStrategyConfig) {
+        Builder ownerSelectionStrategyConfig(final EntityOwnerSelectionStrategyConfig newOwnerSelectionStrategyConfig) {
             checkSealed();
             this.ownerSelectionStrategyConfig = newOwnerSelectionStrategyConfig;
             return this;