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