b633bb07b71f929362e8928ab45f5c641d5944a1
[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 java.util.Objects;
19 import javax.annotation.Nonnull;
20 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
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         Optional<ListenableFuture<Boolean>> result;
80         final NodeId nodeId = ModificationUtil.nodeId(modification);
81         final DataObjectModification<Node> nodeModification = modification.getRootNode();
82
83         if (isDelete(nodeModification) || isDeleteLogical(nodeModification)) {
84             operationalSnapshot.updateCache(nodeId, Optional.absent());
85             deviceMastershipManager.onDeviceDisconnected(nodeId);
86             result = skipModification(modification);
87         } else {
88             operationalSnapshot.updateCache(nodeId, Optional.fromNullable(ModificationUtil.flowCapableNodeAfter(modification)));
89
90             final boolean isAdd = isAdd(nodeModification) || isAddLogical(nodeModification);
91
92             if (isAdd) {
93                 deviceMastershipManager.onDeviceConnected(nodeId);
94             }
95
96             // if node is registered for reconcile we need consistent data from operational DS (skip partial collections)
97             // but we can accept first modification since all statistics are intentionally collected in one step on startup
98             if (reconciliationRegistry.isRegistered(nodeId) && (isAdd || isConsistentForReconcile(modification))) {
99                 result = reconciliation(modification);
100             } else {
101                 result = skipModification(modification);
102             }
103         }
104         return result;
105     }
106
107     private Optional<ListenableFuture<Boolean>> skipModification(final DataTreeModification<Node> modification) {
108         if (LOG.isTraceEnabled()) {
109             LOG.trace("Skipping operational modification: {}, before {}, after {}",
110                     ModificationUtil.nodeIdValue(modification),
111                     modification.getRootNode().getDataBefore() == null ? "null" : "nonnull",
112                     modification.getRootNode().getDataAfter() == null ? "null" : "nonnull");
113         }
114         return Optional.absent();
115     }
116
117     private boolean isDelete(final DataObjectModification<Node> nodeModification) {
118         return Objects.nonNull(nodeModification.getDataBefore()) && Objects.isNull(nodeModification.getDataAfter());
119     }
120
121     /**
122      * All connectors disappeared from operational store (logical delete).
123      */
124     private boolean isDeleteLogical(final DataObjectModification<Node> nodeModification) {
125         return !safeConnectorsEmpty(nodeModification.getDataBefore()) && safeConnectorsEmpty(nodeModification.getDataAfter());
126
127     }
128
129     private boolean isAdd(final DataObjectModification<Node> nodeModification) {
130         return Objects.isNull(nodeModification.getDataBefore()) && Objects.nonNull(nodeModification.getDataAfter());
131     }
132
133     /**
134      * All connectors appeared in operational store (logical add).
135      */
136     private boolean isAddLogical(final DataObjectModification<Node> nodeModification) {
137         return safeConnectorsEmpty(nodeModification.getDataBefore()) && !safeConnectorsEmpty(nodeModification.getDataAfter());
138     }
139
140     /**
141      * If node is present in config DS diff between wanted configuration (in config DS) and actual device
142      * configuration (coming from operational) should be calculated and sent to device.
143      * @param modification from DS
144      * @return optional syncup future
145      */
146     private Optional<ListenableFuture<Boolean>> reconciliation(final DataTreeModification<Node> modification) {
147         final NodeId nodeId = ModificationUtil.nodeId(modification);
148         final Optional<FlowCapableNode> nodeConfiguration = configDao.loadByNodeId(nodeId);
149
150         if (nodeConfiguration.isPresent()) {
151             LOG.debug("Reconciliation {}: {}", dsType(), nodeId.getValue());
152             final InstanceIdentifier<FlowCapableNode> nodePath = InstanceIdentifier.create(Nodes.class)
153                     .child(Node.class, new NodeKey(ModificationUtil.nodeId(modification)))
154                     .augmentation(FlowCapableNode.class);
155             final FlowCapableNode fcOperationalNode = ModificationUtil.flowCapableNodeAfter(modification);
156             final SyncupEntry syncupEntry = new SyncupEntry(nodeConfiguration.get(), LogicalDatastoreType.CONFIGURATION,
157                                                             fcOperationalNode, dsType());
158             return Optional.of(reactor.syncup(nodePath, syncupEntry));
159         } else {
160             LOG.debug("Config not present for reconciliation: {}", nodeId.getValue());
161             reconciliationRegistry.unregisterIfRegistered(nodeId);
162             return skipModification(modification);
163         }
164     }
165
166     /**
167      * Check if modification is consistent for reconciliation. We need fresh data, which means that current statistics
168      * were collected after registration for reconcile and whole bunch of statistics was collected successfully.
169      * @param modification from DS
170      * @return status of modification
171      */
172     private boolean isConsistentForReconcile(final DataTreeModification<Node> modification) {
173         final NodeId nodeId = PathUtil.digNodeId(modification.getRootPath().getRootIdentifier());
174         final FlowCapableStatisticsGatheringStatus gatheringStatus = modification.getRootNode().getDataAfter()
175                 .getAugmentation(FlowCapableStatisticsGatheringStatus.class);
176
177         if (gatheringStatus == null) {
178             LOG.trace("Statistics gathering never started: {}", nodeId.getValue());
179             return false;
180         }
181
182         final SnapshotGatheringStatusEnd gatheringStatusEnd = gatheringStatus.getSnapshotGatheringStatusEnd();
183
184         if (gatheringStatusEnd == null) {
185             LOG.trace("Statistics gathering is not over yet: {}", nodeId.getValue());
186             return false;
187         }
188
189         if (!gatheringStatusEnd.isSucceeded()) {
190             LOG.trace("Statistics gathering was not successful: {}", nodeId.getValue());
191             return false;
192         }
193
194         try {
195             Date timestampOfRegistration = reconciliationRegistry.getRegistrationTimestamp(nodeId);
196             final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
197             Date timestampOfStatistics = simpleDateFormat.parse(gatheringStatusEnd.getEnd().getValue());
198             if (timestampOfStatistics.after(timestampOfRegistration)) {
199                 LOG.debug("Fresh operational present: {}", nodeId.getValue());
200                 return true;
201             }
202         } catch (ParseException e) {
203             LOG.warn("Timestamp parsing error {}", e);
204         }
205         LOG.debug("Fresh operational not present: {}", nodeId.getValue());
206         return false;
207     }
208
209     private static boolean safeConnectorsEmpty(final Node node) {
210         if (node == null) {
211             return true;
212         }
213         final List<NodeConnector> nodeConnectors = node.getNodeConnector();
214         return nodeConnectors == null || nodeConnectors.isEmpty();
215     }
216
217     @Override
218     public LogicalDatastoreType dsType() {
219         return LogicalDatastoreType.OPERATIONAL;
220     }
221 }