Bug 6745 Remove thread renaming and unnecessary logging
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / impl / SimplifiedOperationalListener.java
1 /**
2  * Copyright (c) 2016 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.openflowplugin.applications.frsync.impl;
10
11 import com.google.common.base.Optional;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import java.text.ParseException;
14 import java.text.SimpleDateFormat;
15 import java.util.Collection;
16 import java.util.Date;
17 import java.util.List;
18 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
19 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
20 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
23 import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeDao;
24 import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeSnapshotDao;
25 import org.opendaylight.openflowplugin.applications.frsync.impl.clustering.DeviceMastershipManager;
26 import org.opendaylight.openflowplugin.applications.frsync.util.ModificationUtil;
27 import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;
28 import org.opendaylight.openflowplugin.applications.frsync.util.ReconciliationRegistry;
29 import org.opendaylight.openflowplugin.applications.frsync.util.SyncupEntry;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Listens to operational changes and starts reconciliation through {@link SyncReactor} when necessary.
44  */
45 public class SimplifiedOperationalListener extends AbstractFrmSyncListener<Node> {
46
47     private static final Logger LOG = LoggerFactory.getLogger(SimplifiedOperationalListener.class);
48     public static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
49     private final SyncReactor reactor;
50     private final FlowCapableNodeSnapshotDao operationalSnapshot;
51     private final FlowCapableNodeDao configDao;
52     private final ReconciliationRegistry reconciliationRegistry;
53     private final DeviceMastershipManager deviceMastershipManager;
54
55     public SimplifiedOperationalListener(final SyncReactor reactor,
56                                          final FlowCapableNodeSnapshotDao operationalSnapshot,
57                                          final FlowCapableNodeDao configDao,
58                                          final ReconciliationRegistry reconciliationRegistry,
59                                          final DeviceMastershipManager deviceMastershipManager) {
60         this.reactor = reactor;
61         this.operationalSnapshot = operationalSnapshot;
62         this.configDao = configDao;
63         this.reconciliationRegistry = reconciliationRegistry;
64         this.deviceMastershipManager = deviceMastershipManager;
65     }
66
67     @Override
68     public void onDataTreeChanged(final Collection<DataTreeModification<Node>> modifications) {
69         super.onDataTreeChanged(modifications);
70     }
71
72     /**
73      * Update cache, register for device masterhip when device connected and start reconciliation if device
74      * is registered and actual modification is consistent.Skip the event otherwise.
75      * @throws InterruptedException from syncup
76      */
77     protected Optional<ListenableFuture<Boolean>> processNodeModification(
78             final DataTreeModification<Node> modification) throws InterruptedException {
79         final NodeId nodeId = ModificationUtil.nodeId(modification);
80         updateCache(modification);
81
82         if (isAdd(modification) || isAddLogical(modification)) {
83             deviceMastershipManager.onDeviceConnected(nodeId);
84         }
85
86         if (reconciliationRegistry.isRegistered(nodeId) && isConsistentForReconcile(modification)) {
87             return reconciliation(modification);
88         } else {
89             return skipModification(modification);
90         }
91     }
92
93     /**
94      * Remove if delete. Update only if FlowCapableNode Augmentation modified.
95      * Unregister for device mastership.
96      * @param modification Datastore modification
97      */
98     private void updateCache(final DataTreeModification<Node> modification) {
99         NodeId nodeId = ModificationUtil.nodeId(modification);
100         if (isDelete(modification) || isDeleteLogical(modification)) {
101             operationalSnapshot.updateCache(nodeId, Optional.absent());
102             deviceMastershipManager.onDeviceDisconnected(nodeId);
103             return;
104         }
105         operationalSnapshot.updateCache(nodeId, Optional.fromNullable(ModificationUtil.flowCapableNodeAfter(modification)));
106     }
107
108     private Optional<ListenableFuture<Boolean>> skipModification(final DataTreeModification<Node> modification) {
109         if (LOG.isTraceEnabled()) {
110             LOG.trace("Skipping operational modification: {}, before {}, after {}",
111                     ModificationUtil.nodeIdValue(modification),
112                     modification.getRootNode().getDataBefore() == null ? "null" : "nonnull",
113                     modification.getRootNode().getDataAfter() == null ? "null" : "nonnull");
114         }
115         return Optional.absent();
116     }
117
118     /**
119      * ModificationType.DELETE.
120      */
121     private boolean isDelete(final DataTreeModification<Node> modification) {
122         return ModificationType.DELETE == modification.getRootNode().getModificationType();
123     }
124
125     /**
126      * All connectors disappeared from operational store (logical delete).
127      */
128     private boolean isDeleteLogical(final DataTreeModification<Node> modification) {
129         final DataObjectModification<Node> rootNode = modification.getRootNode();
130         return !safeConnectorsEmpty(rootNode.getDataBefore()) && safeConnectorsEmpty(rootNode.getDataAfter());
131
132     }
133
134     private boolean isAdd(final DataTreeModification<Node> modification) {
135         final DataObjectModification<Node> rootNode = modification.getRootNode();
136         return rootNode.getDataBefore() == null && rootNode.getDataAfter() != null;
137     }
138
139     /**
140      * All connectors appeared in operational store (logical add).
141      */
142     private boolean isAddLogical(final DataTreeModification<Node> modification) {
143         final DataObjectModification<Node> rootNode = modification.getRootNode();
144         return safeConnectorsEmpty(rootNode.getDataBefore()) && !safeConnectorsEmpty(rootNode.getDataAfter());
145     }
146
147     /**
148      * If node is present in config DS diff between wanted configuration (in config DS) and actual device
149      * configuration (coming from operational) should be calculated and sent to device.
150      * @param modification from DS
151      * @return optional syncup future
152      * @throws InterruptedException from syncup
153      */
154     private Optional<ListenableFuture<Boolean>> reconciliation(final DataTreeModification<Node> modification)
155             throws InterruptedException {
156         final NodeId nodeId = ModificationUtil.nodeId(modification);
157         final Optional<FlowCapableNode> nodeConfiguration = configDao.loadByNodeId(nodeId);
158
159         if (nodeConfiguration.isPresent()) {
160             LOG.debug("Reconciliation {}: {}", dsType(), nodeId.getValue());
161             final InstanceIdentifier<FlowCapableNode> nodePath = InstanceIdentifier.create(Nodes.class)
162                     .child(Node.class, new NodeKey(ModificationUtil.nodeId(modification)))
163                     .augmentation(FlowCapableNode.class);
164             final FlowCapableNode fcOperationalNode = ModificationUtil.flowCapableNodeAfter(modification);
165             final SyncupEntry syncupEntry = new SyncupEntry(nodeConfiguration.get(), LogicalDatastoreType.CONFIGURATION,
166                                                             fcOperationalNode, dsType());
167             return Optional.of(reactor.syncup(nodePath, syncupEntry));
168         } else {
169             LOG.debug("Config not present for reconciliation: {}", nodeId.getValue());
170             reconciliationRegistry.unregisterIfRegistered(nodeId);
171             return skipModification(modification);
172         }
173     }
174
175     private boolean isConsistentForReconcile(final DataTreeModification<Node> modification) {
176         final NodeId nodeId = PathUtil.digNodeId(modification.getRootPath().getRootIdentifier());
177         final FlowCapableStatisticsGatheringStatus gatheringStatus = modification.getRootNode().getDataAfter()
178                 .getAugmentation(FlowCapableStatisticsGatheringStatus.class);
179
180         if (gatheringStatus == null) {
181             LOG.trace("Statistics gathering never started: {}", nodeId.getValue());
182             return false;
183         }
184
185         final SnapshotGatheringStatusEnd gatheringStatusEnd = gatheringStatus.getSnapshotGatheringStatusEnd();
186
187         if (gatheringStatusEnd == null) {
188             LOG.trace("Statistics gathering is not over yet: {}", nodeId.getValue());
189             return false;
190         }
191
192         if (!gatheringStatusEnd.isSucceeded()) {
193             LOG.trace("Statistics gathering was not successful: {}", nodeId.getValue());
194             return false;
195         }
196
197         try {
198             Date timestampOfRegistration = reconciliationRegistry.getRegistrationTimestamp(nodeId);
199             final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
200             Date timestampOfStatistics = simpleDateFormat.parse(gatheringStatusEnd.getEnd().getValue());
201             if (timestampOfStatistics.after(timestampOfRegistration)) {
202                 LOG.debug("Fresh operational present: {}", nodeId.getValue());
203                 return true;
204             }
205         } catch (ParseException e) {
206             LOG.warn("Timestamp parsing error {}", e);
207         }
208         LOG.debug("Fresh operational not present: {}", nodeId.getValue());
209         return false;
210     }
211
212     private static boolean safeConnectorsEmpty(final Node node) {
213         if (node == null) {
214             return true;
215         }
216         final List<NodeConnector> nodeConnectors = node.getNodeConnector();
217         return nodeConnectors == null || nodeConnectors.isEmpty();
218     }
219
220     @Override
221     public LogicalDatastoreType dsType() {
222         return LogicalDatastoreType.OPERATIONAL;
223     }
224 }