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