OPNFLWPLUG-1087: ODL controller to provide view of openflow node reconciliation status
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / DeviceMastershipManager.java
1 /*
2  * Copyright (c) 2016, 2017 Pantheon Technologies s.r.o. 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.openflowplugin.applications.frm.impl;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Iterables;
13 import com.google.common.collect.Sets;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.Set;
17 import java.util.concurrent.ConcurrentHashMap;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
20 import org.opendaylight.mdsal.binding.api.DataBroker;
21 import org.opendaylight.mdsal.binding.api.DataObjectModification;
22 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
23 import org.opendaylight.mdsal.binding.api.DataTreeModification;
24 import org.opendaylight.mdsal.binding.api.RpcProviderService;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
27 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
28 import org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeRegistration;
29 import org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeService;
30 import org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeServiceManager;
31 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
32 import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
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.nodes.Node;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.frm.reconciliation.service.rev180227.FrmReconciliationService;
39 import org.opendaylight.yangtools.concepts.ListenerRegistration;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Manager for clustering service registrations of {@link DeviceMastership}.
46  */
47 public class DeviceMastershipManager implements ClusteredDataTreeChangeListener<FlowCapableNode>, AutoCloseable,
48         MastershipChangeService {
49     private static final Logger LOG = LoggerFactory.getLogger(DeviceMastershipManager.class);
50     private static final InstanceIdentifier<FlowCapableNode> II_TO_FLOW_CAPABLE_NODE = InstanceIdentifier
51             .builder(Nodes.class).child(Node.class).augmentation(FlowCapableNode.class).build();
52
53     private final ClusterSingletonServiceProvider clusterSingletonService;
54     private final FlowNodeReconciliation reconcliationAgent;
55     private final DataBroker dataBroker;
56     private final ConcurrentHashMap<NodeId, DeviceMastership> deviceMasterships = new ConcurrentHashMap<>();
57     private final Object lockObj = new Object();
58     private final RpcProviderService rpcProviderService;
59     private final FrmReconciliationService reconcliationService;
60
61     private ListenerRegistration<DeviceMastershipManager> listenerRegistration;
62     private Set<InstanceIdentifier<FlowCapableNode>> activeNodes = Collections.emptySet();
63     private MastershipChangeRegistration mastershipChangeServiceRegistration;
64
65     public DeviceMastershipManager(final ClusterSingletonServiceProvider clusterSingletonService,
66                                    final FlowNodeReconciliation reconcliationAgent,
67                                    final DataBroker dataBroker,
68                                    final MastershipChangeServiceManager mastershipChangeServiceManager,
69                                    final RpcProviderService rpcProviderService,
70                                    final FrmReconciliationService reconciliationService) {
71         this.clusterSingletonService = clusterSingletonService;
72         this.reconcliationAgent = reconcliationAgent;
73         this.rpcProviderService = rpcProviderService;
74         this.reconcliationService = reconciliationService;
75         this.dataBroker = dataBroker;
76         registerNodeListener();
77         this.mastershipChangeServiceRegistration = mastershipChangeServiceManager.register(this);
78     }
79
80     public boolean isDeviceMastered(final NodeId nodeId) {
81         return deviceMasterships.get(nodeId) != null && deviceMasterships.get(nodeId).isDeviceMastered();
82     }
83
84     public boolean isNodeActive(final NodeId nodeId) {
85         final InstanceIdentifier<FlowCapableNode> flowNodeIdentifier = InstanceIdentifier.create(Nodes.class)
86                 .child(Node.class, new NodeKey(nodeId)).augmentation(FlowCapableNode.class);
87         return activeNodes.contains(flowNodeIdentifier);
88
89     }
90
91     @VisibleForTesting
92     ConcurrentHashMap<NodeId, DeviceMastership> getDeviceMasterships() {
93         return deviceMasterships;
94     }
95
96     @Override
97     public void onDataTreeChanged(@NonNull final Collection<DataTreeModification<FlowCapableNode>> changes) {
98         Preconditions.checkNotNull(changes, "Changes may not be null!");
99
100         for (DataTreeModification<FlowCapableNode> change : changes) {
101             final InstanceIdentifier<FlowCapableNode> key = change.getRootPath().getRootIdentifier();
102             final DataObjectModification<FlowCapableNode> mod = change.getRootNode();
103             final InstanceIdentifier<FlowCapableNode> nodeIdent = key.firstIdentifierOf(FlowCapableNode.class);
104
105             switch (mod.getModificationType()) {
106                 case DELETE:
107                     if (mod.getDataAfter() == null) {
108                         remove(key, mod.getDataBefore(), nodeIdent);
109                     }
110                     break;
111                 case SUBTREE_MODIFIED:
112                     // NO-OP since we do not need to reconcile on Node-updated
113                     break;
114                 case WRITE:
115                     if (mod.getDataBefore() == null) {
116                         add(key, mod.getDataAfter(), nodeIdent);
117                     }
118                     break;
119                 default:
120                     throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
121             }
122         }
123     }
124
125     public void remove(final InstanceIdentifier<FlowCapableNode> identifier, final FlowCapableNode del,
126             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
127         if (compareInstanceIdentifierTail(identifier, II_TO_FLOW_CAPABLE_NODE)) {
128             if (LOG.isDebugEnabled()) {
129                 LOG.debug("Node removed: {}", nodeIdent.firstKeyOf(Node.class).getId().getValue());
130             }
131
132             if (!nodeIdent.isWildcarded() && activeNodes.contains(nodeIdent)) {
133                 synchronized (lockObj) {
134                     if (activeNodes.contains(nodeIdent)) {
135                         Set<InstanceIdentifier<FlowCapableNode>> set = Sets.newHashSet(activeNodes);
136                         set.remove(nodeIdent);
137                         reconcliationAgent.flowNodeDisconnected(nodeIdent);
138                         activeNodes = Collections.unmodifiableSet(set);
139                         setNodeOperationalStatus(nodeIdent, false);
140                     }
141                 }
142             }
143         }
144     }
145
146     public void add(final InstanceIdentifier<FlowCapableNode> identifier, final FlowCapableNode add,
147             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
148         if (compareInstanceIdentifierTail(identifier, II_TO_FLOW_CAPABLE_NODE)) {
149             if (LOG.isDebugEnabled()) {
150                 LOG.debug("Node added: {}", nodeIdent.firstKeyOf(Node.class).getId().getValue());
151             }
152
153             if (!nodeIdent.isWildcarded() && !activeNodes.contains(nodeIdent)) {
154                 synchronized (lockObj) {
155                     if (!activeNodes.contains(nodeIdent)) {
156                         Set<InstanceIdentifier<FlowCapableNode>> set = Sets.newHashSet(activeNodes);
157                         set.add(nodeIdent);
158                         activeNodes = Collections.unmodifiableSet(set);
159                         setNodeOperationalStatus(nodeIdent, true);
160                     }
161                 }
162             }
163         }
164     }
165
166     @Override
167     public void close() throws Exception {
168         if (listenerRegistration != null) {
169             listenerRegistration.close();
170             listenerRegistration = null;
171         }
172         if (mastershipChangeServiceRegistration != null) {
173             mastershipChangeServiceRegistration.close();
174             mastershipChangeServiceRegistration = null;
175         }
176     }
177
178     private boolean compareInstanceIdentifierTail(final InstanceIdentifier<?> identifier1,
179             final InstanceIdentifier<?> identifier2) {
180         return Iterables.getLast(identifier1.getPathArguments())
181                 .equals(Iterables.getLast(identifier2.getPathArguments()));
182     }
183
184     private void setNodeOperationalStatus(final InstanceIdentifier<FlowCapableNode> nodeIid, final boolean status) {
185         NodeId nodeId = nodeIid.firstKeyOf(Node.class).getId();
186         if (nodeId != null && deviceMasterships.containsKey(nodeId)) {
187             deviceMasterships.get(nodeId).setDeviceOperationalStatus(status);
188             LOG.debug("Operational status of device {} is set to {}", nodeId, status);
189         }
190     }
191
192     @SuppressWarnings("IllegalCatch")
193     private void registerNodeListener() {
194
195         final InstanceIdentifier<FlowCapableNode> flowNodeWildCardIdentifier = InstanceIdentifier.create(Nodes.class)
196                 .child(Node.class).augmentation(FlowCapableNode.class);
197
198         final DataTreeIdentifier<FlowCapableNode> treeId = DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL,
199                 flowNodeWildCardIdentifier);
200
201         try {
202             SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(ForwardingRulesManagerImpl.STARTUP_LOOP_TICK,
203                     ForwardingRulesManagerImpl.STARTUP_LOOP_MAX_RETRIES);
204
205             listenerRegistration = looper.loopUntilNoException(
206                 () -> dataBroker.registerDataTreeChangeListener(treeId, DeviceMastershipManager.this));
207         } catch (Exception e) {
208             LOG.warn("Data listener registration failed: {}", e.getMessage());
209             LOG.debug("Data listener registration failed ", e);
210             throw new IllegalStateException("Node listener registration failed!", e);
211         }
212     }
213
214     @Override
215     public void onBecomeOwner(@NonNull final DeviceInfo deviceInfo) {
216         LOG.debug("Mastership role notification received for device : {}", deviceInfo.getDatapathId());
217         DeviceMastership membership = deviceMasterships.computeIfAbsent(deviceInfo.getNodeId(),
218             device -> new DeviceMastership(deviceInfo.getNodeId()));
219         membership.reconcile();
220         membership.registerReconciliationRpc(rpcProviderService, reconcliationService);
221     }
222
223     @Override
224     public void onLoseOwnership(@NonNull final DeviceInfo deviceInfo) {
225         final DeviceMastership mastership = deviceMasterships.remove(deviceInfo.getNodeId());
226         if (mastership != null) {
227             mastership.deregisterReconciliationRpc();
228             mastership.close();
229             LOG.debug("Unregistered deviceMastership for device : {}", deviceInfo.getNodeId());
230         }
231     }
232 }