Bug 6745 Improve compression queue locking and handle InterruptedException
[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 javax.annotation.Nonnull;
19 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
20 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
21 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
24 import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeDao;
25 import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeSnapshotDao;
26 import org.opendaylight.openflowplugin.applications.frsync.impl.clustering.DeviceMastershipManager;
27 import org.opendaylight.openflowplugin.applications.frsync.util.ModificationUtil;
28 import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;
29 import org.opendaylight.openflowplugin.applications.frsync.util.ReconciliationRegistry;
30 import org.opendaylight.openflowplugin.applications.frsync.util.SyncupEntry;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Listens to operational changes and starts reconciliation through {@link SyncReactor} when necessary.
45  */
46 public class SimplifiedOperationalListener extends AbstractFrmSyncListener<Node> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(SimplifiedOperationalListener.class);
49     public static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
50     private final SyncReactor reactor;
51     private final FlowCapableNodeSnapshotDao operationalSnapshot;
52     private final FlowCapableNodeDao configDao;
53     private final ReconciliationRegistry reconciliationRegistry;
54     private final DeviceMastershipManager deviceMastershipManager;
55
56     public SimplifiedOperationalListener(final SyncReactor reactor,
57                                          final FlowCapableNodeSnapshotDao operationalSnapshot,
58                                          final FlowCapableNodeDao configDao,
59                                          final ReconciliationRegistry reconciliationRegistry,
60                                          final DeviceMastershipManager deviceMastershipManager) {
61         this.reactor = reactor;
62         this.operationalSnapshot = operationalSnapshot;
63         this.configDao = configDao;
64         this.reconciliationRegistry = reconciliationRegistry;
65         this.deviceMastershipManager = deviceMastershipManager;
66     }
67
68     @Override
69     public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Node>> modifications) {
70         super.onDataTreeChanged(modifications);
71     }
72
73     /**
74      * Update cache, register for device mastership when device connected and start reconciliation if device
75      * is registered and actual modification is consistent.Skip the event otherwise.
76      */
77     protected Optional<ListenableFuture<Boolean>> processNodeModification(
78             final DataTreeModification<Node> modification) {
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      */
153     private Optional<ListenableFuture<Boolean>> reconciliation(final DataTreeModification<Node> modification) {
154         final NodeId nodeId = ModificationUtil.nodeId(modification);
155         final Optional<FlowCapableNode> nodeConfiguration = configDao.loadByNodeId(nodeId);
156
157         if (nodeConfiguration.isPresent()) {
158             LOG.debug("Reconciliation {}: {}", dsType(), nodeId.getValue());
159             final InstanceIdentifier<FlowCapableNode> nodePath = InstanceIdentifier.create(Nodes.class)
160                     .child(Node.class, new NodeKey(ModificationUtil.nodeId(modification)))
161                     .augmentation(FlowCapableNode.class);
162             final FlowCapableNode fcOperationalNode = ModificationUtil.flowCapableNodeAfter(modification);
163             final SyncupEntry syncupEntry = new SyncupEntry(nodeConfiguration.get(), LogicalDatastoreType.CONFIGURATION,
164                                                             fcOperationalNode, dsType());
165             return Optional.of(reactor.syncup(nodePath, syncupEntry));
166         } else {
167             LOG.debug("Config not present for reconciliation: {}", nodeId.getValue());
168             reconciliationRegistry.unregisterIfRegistered(nodeId);
169             return skipModification(modification);
170         }
171     }
172
173     private boolean isConsistentForReconcile(final DataTreeModification<Node> modification) {
174         final NodeId nodeId = PathUtil.digNodeId(modification.getRootPath().getRootIdentifier());
175         final FlowCapableStatisticsGatheringStatus gatheringStatus = modification.getRootNode().getDataAfter()
176                 .getAugmentation(FlowCapableStatisticsGatheringStatus.class);
177
178         if (gatheringStatus == null) {
179             LOG.trace("Statistics gathering never started: {}", nodeId.getValue());
180             return false;
181         }
182
183         final SnapshotGatheringStatusEnd gatheringStatusEnd = gatheringStatus.getSnapshotGatheringStatusEnd();
184
185         if (gatheringStatusEnd == null) {
186             LOG.trace("Statistics gathering is not over yet: {}", nodeId.getValue());
187             return false;
188         }
189
190         if (!gatheringStatusEnd.isSucceeded()) {
191             LOG.trace("Statistics gathering was not successful: {}", nodeId.getValue());
192             return false;
193         }
194
195         try {
196             Date timestampOfRegistration = reconciliationRegistry.getRegistrationTimestamp(nodeId);
197             final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
198             Date timestampOfStatistics = simpleDateFormat.parse(gatheringStatusEnd.getEnd().getValue());
199             if (timestampOfStatistics.after(timestampOfRegistration)) {
200                 LOG.debug("Fresh operational present: {}", nodeId.getValue());
201                 return true;
202             }
203         } catch (ParseException e) {
204             LOG.warn("Timestamp parsing error {}", e);
205         }
206         LOG.debug("Fresh operational not present: {}", nodeId.getValue());
207         return false;
208     }
209
210     private static boolean safeConnectorsEmpty(final Node node) {
211         if (node == null) {
212             return true;
213         }
214         final List<NodeConnector> nodeConnectors = node.getNodeConnector();
215         return nodeConnectors == null || nodeConnectors.isEmpty();
216     }
217
218     @Override
219     public LogicalDatastoreType dsType() {
220         return LogicalDatastoreType.OPERATIONAL;
221     }
222 }