Fix prefix shard configuration update handling
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / sharding / PrefixedShardConfigUpdateHandler.java
1 /*
2  * Copyright (c) 2017 Cisco 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
9 package org.opendaylight.controller.cluster.sharding;
10
11 import static akka.actor.ActorRef.noSender;
12 import static org.opendaylight.controller.cluster.datastore.utils.ClusterUtils.SHARD_PREFIX_QNAME;
13 import static org.opendaylight.controller.cluster.datastore.utils.ClusterUtils.SHARD_REPLICAS_QNAME;
14 import static org.opendaylight.controller.cluster.datastore.utils.ClusterUtils.SHARD_REPLICA_QNAME;
15
16 import akka.actor.ActorRef;
17 import com.google.common.base.Preconditions;
18 import java.util.Collection;
19 import java.util.EnumMap;
20 import java.util.List;
21 import java.util.stream.Collectors;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.cluster.access.concepts.MemberName;
24 import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
25 import org.opendaylight.controller.cluster.datastore.config.PrefixShardConfiguration;
26 import org.opendaylight.controller.cluster.datastore.shardstrategy.PrefixShardStrategy;
27 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
28 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardCreated;
29 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardRemoved;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
34 import org.opendaylight.yangtools.concepts.ListenerRegistration;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
42 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Listens on changes on prefix-shard-configuration. Resolves the changes and
48  * notifies handling actor with {@link PrefixShardCreated} and
49  * {@link PrefixShardRemoved} messages.
50  */
51 public class PrefixedShardConfigUpdateHandler {
52
53     private static final Logger LOG = LoggerFactory.getLogger(PrefixedShardConfigUpdateHandler.class);
54     private final ActorRef handlingActor;
55     private final MemberName memberName;
56
57     private final EnumMap<LogicalDatastoreType,ListenerRegistration<DOMDataTreeChangeListener>> registrations =
58             new EnumMap<>(LogicalDatastoreType.class);
59
60     public PrefixedShardConfigUpdateHandler(final ActorRef handlingActor, final MemberName memberName) {
61         this.handlingActor = Preconditions.checkNotNull(handlingActor);
62         this.memberName = Preconditions.checkNotNull(memberName);
63     }
64
65     public void initListener(final AbstractDataStore dataStore, final LogicalDatastoreType type) {
66         registrations.put(type, dataStore.registerShardConfigListener(
67                 ClusterUtils.SHARD_LIST_PATH, new ShardConfigHandler(memberName, type, handlingActor)));
68     }
69
70     public void close() {
71         registrations.values().forEach(ListenerRegistration::close);
72         registrations.clear();
73     }
74
75     public static final class ShardConfigHandler implements ClusteredDOMDataTreeChangeListener {
76
77         private final MemberName memberName;
78         private final LogicalDatastoreType type;
79         private final ActorRef handlingActor;
80         private final String logName;
81
82         public ShardConfigHandler(final MemberName memberName,
83                            final LogicalDatastoreType type,
84                            final ActorRef handlingActor) {
85             this.memberName = memberName;
86             this.type = type;
87             this.handlingActor = handlingActor;
88             logName = memberName.getName() + "-" + type;
89         }
90
91         @Override
92         public void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
93             changes.forEach(this::resolveChange);
94         }
95
96         private void resolveChange(final DataTreeCandidate candidate) {
97             switch (candidate.getRootNode().getModificationType()) {
98                 case UNMODIFIED:
99                     break;
100                 case APPEARED:
101                 case DELETE:
102                 case DISAPPEARED:
103                 case SUBTREE_MODIFIED:
104                 case WRITE:
105                     resolveModifiedRoot(candidate.getRootNode());
106                     break;
107                 default:
108                     break;
109             }
110         }
111
112         private void resolveModifiedRoot(final DataTreeCandidateNode rootNode) {
113
114             LOG.debug("{}: New config received {}", logName, rootNode);
115             LOG.debug("{}: Data after: {}", logName, rootNode.getDataAfter());
116
117             // were in the shards list, iter children and resolve
118             for (final DataTreeCandidateNode childNode : rootNode.getChildNodes()) {
119                 switch (childNode.getModificationType()) {
120                     case UNMODIFIED:
121                         break;
122                     case SUBTREE_MODIFIED:
123                     case APPEARED:
124                     case WRITE:
125                         resolveWrittenShard(childNode);
126                         break;
127                     case DELETE:
128                     case DISAPPEARED:
129                         resolveDeletedShard(childNode);
130                         break;
131                     default:
132                         break;
133                 }
134             }
135         }
136
137         @SuppressWarnings("unchecked")
138         private void resolveWrittenShard(final DataTreeCandidateNode childNode) {
139             final MapEntryNode entryNode = (MapEntryNode) childNode.getDataAfter().get();
140             final LeafNode<YangInstanceIdentifier> prefix =
141                     (LeafNode<YangInstanceIdentifier>) entryNode.getChild(new NodeIdentifier(SHARD_PREFIX_QNAME)).get();
142
143             final YangInstanceIdentifier identifier = prefix.getValue();
144
145             LOG.debug("{}: Deserialized {} from datastore", logName, identifier);
146
147             final ContainerNode replicas =
148                     (ContainerNode) entryNode.getChild(new NodeIdentifier(SHARD_REPLICAS_QNAME)).get();
149
150             final LeafSetNode<String> replicaList =
151                     (LeafSetNode<String>) replicas.getChild(new NodeIdentifier(SHARD_REPLICA_QNAME)).get();
152
153             final List<MemberName> retReplicas = replicaList.getValue().stream()
154                     .map(child -> MemberName.forName(child.getValue()))
155                     .collect(Collectors.toList());
156
157             LOG.debug("{}: Replicas read from ds {}", logName, retReplicas.toString());
158
159             final PrefixShardConfiguration newConfig =
160                     new PrefixShardConfiguration(new DOMDataTreeIdentifier(type, identifier),
161                             PrefixShardStrategy.NAME, retReplicas);
162
163             LOG.debug("{}: Resulting config {} - sending PrefixShardCreated to {}", logName, newConfig, handlingActor);
164
165             handlingActor.tell(new PrefixShardCreated(newConfig), noSender());
166         }
167
168         private void resolveDeletedShard(final DataTreeCandidateNode childNode) {
169
170             final MapEntryNode entryNode = (MapEntryNode) childNode.getDataBefore().get();
171
172             final LeafNode<YangInstanceIdentifier> prefix =
173                     (LeafNode<YangInstanceIdentifier>) entryNode.getChild(new NodeIdentifier(SHARD_PREFIX_QNAME)).get();
174
175             final YangInstanceIdentifier deleted = prefix.getValue();
176             LOG.debug("{}: Removing shard at {}.", memberName, deleted);
177
178             final DOMDataTreeIdentifier domDataTreeIdentifier = new DOMDataTreeIdentifier(type, deleted);
179             final PrefixShardRemoved message = new PrefixShardRemoved(domDataTreeIdentifier);
180
181             handlingActor.tell(message, noSender());
182         }
183
184         @Override
185         public String toString() {
186             return "ShardConfigHandler [logName=" + logName + ", handlingActor=" + handlingActor + "]";
187         }
188     }
189 }