Adjust to DOMDataTreeChangeListener update
[controller.git] / opendaylight / md-sal / samples / clustering-test-app / provider / src / main / java / org / opendaylight / controller / clustering / it / provider / impl / IdIntsListener.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 package org.opendaylight.controller.clustering.it.provider.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ITEM;
12
13 import com.google.common.util.concurrent.SettableFuture;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.concurrent.Executors;
19 import java.util.concurrent.Future;
20 import java.util.concurrent.ScheduledExecutorService;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.atomic.AtomicLong;
24 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
27 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public class IdIntsListener implements ClusteredDOMDataTreeChangeListener {
35     private static final Logger LOG = LoggerFactory.getLogger(IdIntsListener.class);
36     private static final long SECOND_AS_NANO = 1000000000;
37
38     private volatile NormalizedNode localCopy;
39     private final AtomicLong lastNotifTimestamp = new AtomicLong(0);
40     private ScheduledExecutorService executorService;
41     private ScheduledFuture<?> scheduledFuture;
42
43     @Override
44     public void onInitialData() {
45         // Intentional no-op
46     }
47
48     @Override
49     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
50
51         // There should only be one candidate reported
52         checkState(changes.size() == 1);
53
54         lastNotifTimestamp.set(System.nanoTime());
55
56         // do not log the change into debug, only use trace since it will lead to OOM on default heap settings
57         LOG.debug("Received data tree changed");
58
59         changes.forEach(change -> {
60             if (change.getRootNode().getDataAfter().isPresent()) {
61                 LOG.trace("Received change, data before: {}, data after: {}",
62                         change.getRootNode().getDataBefore().isPresent()
63                                 ? change.getRootNode().getDataBefore().get() : "",
64                         change.getRootNode().getDataAfter().get());
65
66                 localCopy = change.getRootNode().getDataAfter().get();
67             } else {
68                 LOG.warn("getDataAfter() is missing from notification. change: {}", change);
69             }
70         });
71     }
72
73     public boolean hasTriggered() {
74         return localCopy != null;
75     }
76
77     public boolean checkEqual(final NormalizedNode expected) {
78         return localCopy.equals(expected);
79     }
80
81     @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
82     public String diffWithLocalCopy(final NormalizedNode expected) {
83         return diffNodes((MapNode)expected, (MapNode)localCopy);
84     }
85
86     public Future<Void> tryFinishProcessing() {
87         executorService = Executors.newSingleThreadScheduledExecutor();
88         final SettableFuture<Void> settableFuture = SettableFuture.create();
89
90         scheduledFuture = executorService.scheduleAtFixedRate(new CheckFinishedTask(settableFuture),
91                 0, 1, TimeUnit.SECONDS);
92         return settableFuture;
93     }
94
95     public static String diffNodes(final MapNode expected, final MapNode actual) {
96         StringBuilder builder = new StringBuilder("MapNodes diff:");
97
98         final YangInstanceIdentifier.NodeIdentifier itemNodeId = new YangInstanceIdentifier.NodeIdentifier(ITEM);
99
100         Map<NodeIdentifierWithPredicates, MapEntryNode> expIdIntMap = new HashMap<>();
101         expected.body().forEach(node -> expIdIntMap.put(node.getIdentifier(), node));
102
103         actual.body().forEach(actIdInt -> {
104             final MapEntryNode expIdInt = expIdIntMap.remove(actIdInt.getIdentifier());
105             if (expIdInt == null) {
106                 builder.append('\n').append("  Unexpected id-int entry for ").append(actIdInt.getIdentifier());
107                 return;
108             }
109
110             Map<NodeIdentifierWithPredicates, MapEntryNode> expItemMap = new HashMap<>();
111             ((MapNode)expIdInt.findChildByArg(itemNodeId).get()).body()
112                 .forEach(node -> expItemMap.put(node.getIdentifier(), node));
113
114             ((MapNode)actIdInt.findChildByArg(itemNodeId).get()).body().forEach(actItem -> {
115                 final MapEntryNode expItem = expItemMap.remove(actItem.getIdentifier());
116                 if (expItem == null) {
117                     builder.append('\n').append("  Unexpected item entry ").append(actItem.getIdentifier())
118                         .append(" for id-int entry ").append(actIdInt.getIdentifier());
119                 }
120             });
121
122             expItemMap.values().forEach(node -> builder.append('\n')
123                 .append("  Actual is missing item entry ").append(node.getIdentifier())
124                     .append(" for id-int entry ").append(actIdInt.getIdentifier()));
125         });
126
127         expIdIntMap.values().forEach(node -> builder.append('\n')
128             .append("  Actual is missing id-int entry for ").append(node.getIdentifier()));
129
130         return builder.toString();
131     }
132
133     private class CheckFinishedTask implements Runnable {
134
135         private final SettableFuture<Void> future;
136
137         CheckFinishedTask(final SettableFuture<Void> future) {
138             this.future = future;
139         }
140
141         @Override
142         public void run() {
143             if (System.nanoTime() - lastNotifTimestamp.get() > SECOND_AS_NANO * 4) {
144                 scheduledFuture.cancel(false);
145                 future.set(null);
146
147                 executorService.shutdown();
148             }
149         }
150     }
151 }