NETVIRT-1630 migrate to md-sal APIs
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / l2gw / ha / listeners / HwvtepNodeBaseListener.java
1 /*
2  * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. 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.netvirt.elan.l2gw.ha.listeners;
9
10 import com.google.common.collect.ImmutableMap;
11 import java.util.Collection;
12 import java.util.List;
13 import java.util.Objects;
14 import java.util.concurrent.ExecutionException;
15 import java.util.function.Function;
16 import javax.annotation.PreDestroy;
17 import org.opendaylight.genius.datastoreutils.TaskRetryLooper;
18 import org.opendaylight.genius.infra.Datastore;
19 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
20 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
21 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
22 import org.opendaylight.genius.utils.hwvtep.HwvtepNodeHACache;
23 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundConstants;
24 import org.opendaylight.infrautils.metrics.Labeled;
25 import org.opendaylight.infrautils.metrics.Meter;
26 import org.opendaylight.infrautils.metrics.MetricDescriptor;
27 import org.opendaylight.infrautils.metrics.MetricProvider;
28 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
29 import org.opendaylight.mdsal.binding.api.DataBroker;
30 import org.opendaylight.mdsal.binding.api.DataObjectModification;
31 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
32 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
33 import org.opendaylight.mdsal.binding.api.DataTreeModification;
34 import org.opendaylight.netvirt.elan.l2gw.ha.HwvtepHAUtil;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitches;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.Managers;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteMcastMacs;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteUcastMacs;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public abstract class HwvtepNodeBaseListener<D extends Datastore>
52     implements DataTreeChangeListener<Node>, AutoCloseable {
53
54     private static final Logger LOG = LoggerFactory.getLogger(HwvtepNodeBaseListener.class);
55     private static final int STARTUP_LOOP_TICK = 500;
56     private static final int STARTUP_LOOP_MAX_RETRIES = 8;
57
58     private ListenerRegistration<HwvtepNodeBaseListener> registration;
59     private final DataBroker dataBroker;
60     final ManagedNewTransactionRunner txRunner;
61     private final HwvtepNodeHACache hwvtepNodeHACache;
62     private final Class<D> datastoreType;
63     private final Function<DataObject, String> noLogicalSwitch = (data) -> "No_Ls";
64
65     private final Labeled<Labeled<Labeled<Labeled<Labeled<Meter>>>>> childModCounter;
66     private final Labeled<Labeled<Labeled<Meter>>> nodeModCounter;
67     private final boolean updateMetrics;
68
69     private static final ImmutableMap<Class, Function<DataObject, String>> LOGICAL_SWITCH_EXTRACTOR =
70         new ImmutableMap.Builder<Class, Function<DataObject, String>>()
71             .put(LogicalSwitches.class, data -> ((LogicalSwitches) data).getHwvtepNodeName().getValue())
72             .put(RemoteMcastMacs.class,
73                 data -> logicalSwitchNameFromIid(((RemoteMcastMacs) data).key().getLogicalSwitchRef().getValue()))
74             .put(RemoteUcastMacs.class, data -> logicalSwitchNameFromIid(
75                 ((RemoteUcastMacs) data).key().getLogicalSwitchRef().getValue())).build();
76
77
78     public HwvtepNodeBaseListener(Class<D> datastoreType, DataBroker dataBroker,
79                                   HwvtepNodeHACache hwvtepNodeHACache, MetricProvider metricProvider,
80                                   boolean updateMetrics) throws Exception {
81         this.dataBroker = dataBroker;
82         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
83         this.datastoreType = datastoreType;
84         this.hwvtepNodeHACache = hwvtepNodeHACache;
85         this.updateMetrics = updateMetrics;
86         this.childModCounter = metricProvider.newMeter(
87                 MetricDescriptor.builder().anchor(this).project("netvirt").module("l2gw").id("child").build(),
88                 "datastore", "modification", "class", "nodeid", "logicalswitch");
89         this.nodeModCounter = metricProvider.newMeter(
90                 MetricDescriptor.builder().anchor(this).project("netvirt").module("l2gw").id("node").build(),
91                 "datastore", "modification", "nodeid");
92         registerListener(datastoreType, dataBroker);
93     }
94
95     protected void registerListener(Class<D> dsType, DataBroker broker) throws Exception {
96         final DataTreeIdentifier<Node> treeId = DataTreeIdentifier.create(Datastore.toType(dsType),
97                 getWildcardPath());
98         TaskRetryLooper looper = new TaskRetryLooper(STARTUP_LOOP_TICK, STARTUP_LOOP_MAX_RETRIES);
99         registration = looper.loopUntilNoException(() ->
100                 broker.registerDataTreeChangeListener(treeId, HwvtepNodeBaseListener.this));
101     }
102
103     protected DataBroker getDataBroker() {
104         return dataBroker;
105     }
106
107     protected HwvtepNodeHACache getHwvtepNodeHACache() {
108         return hwvtepNodeHACache;
109     }
110
111     /**
112      * If Normal non-ha node changes to HA node , its added to HA cache.
113      *
114      * @param childPath HA child path which got converted to HA node
115      * @param updatedChildNode updated Child node
116      * @param beforeChildNode non-ha node before updated to HA node
117      */
118     protected void addToHACacheIfBecameHAChild(InstanceIdentifier<Node> childPath, Node updatedChildNode,
119                                                Node beforeChildNode) {
120         HwvtepGlobalAugmentation updatedAugmentaion = updatedChildNode.augmentation(HwvtepGlobalAugmentation.class);
121         HwvtepGlobalAugmentation beforeAugmentaion = null;
122         if (beforeChildNode != null) {
123             beforeAugmentaion = beforeChildNode.augmentation(HwvtepGlobalAugmentation.class);
124         }
125         List<Managers> up = null;
126         List<Managers> be = null;
127         if (updatedAugmentaion != null) {
128             up = updatedAugmentaion.getManagers();
129         }
130         if (beforeAugmentaion != null) {
131             be = beforeAugmentaion.getManagers();
132         }
133
134         if (up != null) {
135             Managers m1 = up.get(0);
136             Managers m2 = be.get(0);
137             if (!Objects.equals(m1, m2)) {
138                 LOG.trace("Manager entry updated for node {} ", updatedChildNode.getNodeId().getValue());
139                 HwvtepHAUtil.addToCacheIfHAChildNode(childPath, updatedChildNode, hwvtepNodeHACache);
140             }
141         }
142     }
143
144     @Override
145     public void onDataTreeChanged(final Collection<DataTreeModification<Node>> changes) {
146         HAJobScheduler.getInstance().submitJob(() -> LoggingFutures.addErrorLogging(
147             txRunner.callWithNewReadWriteTransactionAndSubmit(datastoreType, tx -> {
148                 processConnectedNodes(changes, tx);
149                 processUpdatedNodes(changes, tx);
150                 processDisconnectedNodes(changes, tx);
151             }), LOG, "Error processing data-tree changes"));
152     }
153
154     private void processUpdatedNodes(Collection<DataTreeModification<Node>> changes,
155                                      TypedReadWriteTransaction<D> tx)
156             throws ExecutionException, InterruptedException {
157         for (DataTreeModification<Node> change : changes) {
158             final InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
159             final DataObjectModification<Node> mod = change.getRootNode();
160             String nodeId = key.firstKeyOf(Node.class).getNodeId().getValue();
161             Node updated = HwvtepHAUtil.getUpdated(mod);
162             Node original = HwvtepHAUtil.getOriginal(mod);
163             updateCounters(nodeId, mod.getModifiedChildren());
164             if (updated != null && original != null) {
165                 DataObjectModification subMod;
166                 if (!nodeId.contains(HwvtepHAUtil.PHYSICALSWITCH)) {
167                     onGlobalNodeUpdate(key, updated, original, mod, tx);
168                     subMod = change.getRootNode().getModifiedAugmentation(HwvtepGlobalAugmentation.class);
169                 } else {
170                     onPsNodeUpdate(updated, mod, tx);
171                     subMod = change.getRootNode().getModifiedAugmentation(PhysicalSwitchAugmentation.class);
172                 }
173                 if (subMod != null) {
174                     updateCounters(nodeId, subMod.getModifiedChildren());
175                 }
176             }
177         }
178     }
179
180     private String logicalSwitchNameFromChildMod(DataObjectModification<? extends DataObject> childMod) {
181         DataObject dataAfter = childMod.getDataAfter();
182         DataObject data = dataAfter != null ? dataAfter : childMod.getDataBefore();
183         return LOGICAL_SWITCH_EXTRACTOR.getOrDefault(childMod.getModificationType().getClass(), noLogicalSwitch)
184                 .apply(data);
185     }
186
187     private static String logicalSwitchNameFromIid(InstanceIdentifier<?> input) {
188         InstanceIdentifier<LogicalSwitches> iid = (InstanceIdentifier<LogicalSwitches>)input;
189         return iid.firstKeyOf(LogicalSwitches.class).getHwvtepNodeName().getValue();
190     }
191
192     private void updateCounters(String nodeId,
193                                 Collection<? extends DataObjectModification<? extends DataObject>> childModCollection) {
194         if (childModCollection == null || !updateMetrics) {
195             return;
196         }
197         childModCollection.forEach(childMod -> {
198             String childClsName = childMod.getDataType().getClass().getSimpleName();
199             String modificationType = childMod.getModificationType().toString();
200             String logicalSwitchName = logicalSwitchNameFromChildMod(childMod);
201             childModCounter.label(Datastore.toType(datastoreType).name())
202                     .label(modificationType)
203                     .label(childClsName)
204                     .label(nodeId)
205                     .label(logicalSwitchName).mark();
206         });
207     }
208
209     private void processDisconnectedNodes(Collection<DataTreeModification<Node>> changes,
210                                           TypedReadWriteTransaction<D> tx)
211             throws InterruptedException, ExecutionException {
212         for (DataTreeModification<Node> change : changes) {
213             final InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
214             final DataObjectModification<Node> mod = change.getRootNode();
215             Node deleted = HwvtepHAUtil.getRemoved(mod);
216             String nodeId = key.firstKeyOf(Node.class).getNodeId().getValue();
217             if (deleted != null) {
218                 if (updateMetrics) {
219                     nodeModCounter.label(Datastore.toType(datastoreType).name())
220                             .label(DataObjectModification.ModificationType.DELETE.name()).label(nodeId).mark();
221                 }
222                 if (!nodeId.contains(HwvtepHAUtil.PHYSICALSWITCH)) {
223                     LOG.trace("Handle global node delete {}", deleted.getNodeId().getValue());
224                     onGlobalNodeDelete(key, deleted, tx);
225                 } else {
226                     LOG.trace("Handle ps node node delete {}", deleted.getNodeId().getValue());
227                     onPsNodeDelete(key, deleted, tx);
228                 }
229             }
230         }
231     }
232
233     void processConnectedNodes(Collection<DataTreeModification<Node>> changes,
234                                TypedReadWriteTransaction<D> tx)
235             throws ExecutionException, InterruptedException {
236         for (DataTreeModification<Node> change : changes) {
237             InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
238             DataObjectModification<Node> mod = change.getRootNode();
239             Node node = HwvtepHAUtil.getCreated(mod);
240             String nodeId = key.firstKeyOf(Node.class).getNodeId().getValue();
241             if (node != null) {
242                 if (updateMetrics) {
243                     nodeModCounter.label(Datastore.toType(datastoreType).name())
244                             .label(DataObjectModification.ModificationType.WRITE.name()).label(nodeId).mark();
245                 }
246                 if (!nodeId.contains(HwvtepHAUtil.PHYSICALSWITCH)) {
247                     LOG.trace("Handle global node add {}", node.getNodeId().getValue());
248                     onGlobalNodeAdd(key, node, tx);
249                 } else {
250                     LOG.trace("Handle ps node add {}", node.getNodeId().getValue());
251                     onPsNodeAdd(key, node, tx);
252                 }
253             }
254         }
255     }
256
257     private static InstanceIdentifier<Node> getWildcardPath() {
258         InstanceIdentifier<Node> path = InstanceIdentifier
259                 .create(NetworkTopology.class)
260                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID))
261                 .child(Node.class);
262         return path;
263     }
264
265     @Override
266     @PreDestroy
267     public void close() {
268         if (registration != null) {
269             registration.close();
270         }
271     }
272
273     //default methods
274     void onGlobalNodeDelete(InstanceIdentifier<Node> key, Node added, TypedReadWriteTransaction<D> tx)
275         throws ExecutionException, InterruptedException {
276     }
277
278     void onPsNodeDelete(InstanceIdentifier<Node> key, Node addedPSNode, TypedReadWriteTransaction<D> tx)
279         throws ExecutionException, InterruptedException {
280
281     }
282
283     void onGlobalNodeAdd(InstanceIdentifier<Node> key, Node added, TypedReadWriteTransaction<D> tx) {
284
285     }
286
287     void onPsNodeAdd(InstanceIdentifier<Node> key, Node addedPSNode, TypedReadWriteTransaction<D> tx)
288             throws InterruptedException, ExecutionException {
289
290     }
291
292     void onGlobalNodeUpdate(InstanceIdentifier<Node> key, Node updated, Node original,
293                             DataObjectModification<Node> mod, TypedReadWriteTransaction<D> tx) {
294
295     }
296
297     void onPsNodeUpdate(Node updated,
298                         DataObjectModification<Node> mod, TypedReadWriteTransaction<D> tx) {
299
300     }
301
302 }