Fix a few non-null collections
[netvirt.git] / vpnservice / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / netvirt / elan / l2gw / listeners / HwvtepTerminationPointListener.java
1 /*
2  * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. 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.netvirt.elan.l2gw.listeners;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.SettableFuture;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.concurrent.ConcurrentHashMap;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
21 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
25 import org.opendaylight.genius.datastoreutils.hwvtep.HwvtepClusteredDataTreeChangeListener;
26 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundConstants;
27 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundUtils;
28 import org.opendaylight.genius.utils.hwvtep.HwvtepUtils;
29 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
30 import org.opendaylight.netvirt.elan.l2gw.utils.L2GatewayConnectionUtils;
31 import org.opendaylight.netvirt.elan.l2gw.utils.SettableFutureCallback;
32 import org.opendaylight.netvirt.elan.utils.ElanClusterUtils;
33 import org.opendaylight.netvirt.elan.utils.ElanUtils;
34 import org.opendaylight.netvirt.neutronvpn.api.l2gw.L2GatewayDevice;
35 import org.opendaylight.netvirt.neutronvpn.api.l2gw.utils.L2GatewayCacheUtils;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.attributes.Devices;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.attributes.devices.Interfaces;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.connections.attributes.l2gatewayconnections.L2gatewayConnection;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateways.attributes.l2gateways.L2gateway;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalPortAugmentation;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.VlanBindings;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
49 import org.opendaylight.yangtools.concepts.ListenerRegistration;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54
55 /**
56  * Listener for physical locator presence in operational datastore.
57  */
58 public class HwvtepTerminationPointListener
59         extends HwvtepClusteredDataTreeChangeListener<TerminationPoint, HwvtepTerminationPointListener>
60         implements AutoCloseable {
61
62     private static final Logger LOG = LoggerFactory.getLogger(HwvtepTerminationPointListener.class);
63
64     private DataBroker broker;
65     private ListenerRegistration<DataChangeListener> lstnerRegistration;
66     private final ElanL2GatewayUtils elanL2GatewayUtils;
67     private final EntityOwnershipService entityOwnershipService;
68
69     public HwvtepTerminationPointListener(DataBroker broker, ElanUtils elanUtils,
70                                           EntityOwnershipService entityOwnershipService) {
71         super(TerminationPoint.class, HwvtepTerminationPointListener.class);
72
73         this.broker = broker;
74         this.elanL2GatewayUtils = elanUtils.getElanL2GatewayUtils();
75         this.entityOwnershipService = entityOwnershipService;
76         registerListener(LogicalDatastoreType.OPERATIONAL, broker);
77         LOG.debug("created HwvtepTerminationPointListener");
78     }
79
80     static Map<InstanceIdentifier<TerminationPoint>, List<Runnable>> waitingJobsList = new ConcurrentHashMap<>();
81     static Map<InstanceIdentifier<TerminationPoint>, Boolean> teps = new ConcurrentHashMap<>();
82
83     public static void runJobAfterPhysicalLocatorIsAvialable(InstanceIdentifier<TerminationPoint> key,
84                                                              Runnable runnable) {
85         if (teps.get(key) != null) {
86             LOG.debug("physical locator already available {} running job ", key);
87             runnable.run();
88             return;
89         }
90         synchronized (HwvtepTerminationPointListener.class) {
91             waitingJobsList.computeIfAbsent(key, k -> new ArrayList<>()).add(runnable);
92             LOG.debug("added the job to wait list of physical locator {}", key);
93         }
94     }
95
96     @Override
97     @SuppressWarnings("checkstyle:IllegalCatch")
98     public void close() {
99         if (lstnerRegistration != null) {
100             try {
101                 // TODO use https://git.opendaylight.org/gerrit/#/c/44145/ when merged, and remove @SuppressWarnings
102                 lstnerRegistration.close();
103             } catch (final Exception e) {
104                 LOG.error("Error when cleaning up DataChangeListener.", e);
105             }
106             lstnerRegistration = null;
107         }
108     }
109
110     @Override
111     protected void removed(InstanceIdentifier<TerminationPoint> identifier, TerminationPoint del) {
112         LOG.trace("physical locator removed {}", identifier);
113         teps.remove(identifier);
114         final HwvtepPhysicalPortAugmentation portAugmentation =
115                 del.getAugmentation(HwvtepPhysicalPortAugmentation.class);
116         if (portAugmentation != null) {
117             final NodeId nodeId = identifier.firstIdentifierOf(Node.class).firstKeyOf(Node.class).getNodeId();
118             ElanClusterUtils.runOnlyInLeaderNode(entityOwnershipService, HwvtepSouthboundConstants.ELAN_ENTITY_NAME,
119                     "Handling Physical port delete", () ->
120                             handlePortDeleted(identifier, portAugmentation, del, nodeId));
121             return;
122         }
123     }
124
125     @Override
126     protected void updated(InstanceIdentifier<TerminationPoint> identifier, TerminationPoint original,
127                            TerminationPoint update) {
128         LOG.trace("physical locator available {}", identifier);
129     }
130
131     @Override
132     protected void added(InstanceIdentifier<TerminationPoint> identifier, final TerminationPoint add) {
133         final HwvtepPhysicalPortAugmentation portAugmentation =
134                 add.getAugmentation(HwvtepPhysicalPortAugmentation.class);
135         if (portAugmentation != null) {
136             final NodeId nodeId = identifier.firstIdentifierOf(Node.class).firstKeyOf(Node.class).getNodeId();
137             ElanClusterUtils.runOnlyInLeaderNode(entityOwnershipService, HwvtepSouthboundConstants.ELAN_ENTITY_NAME,
138                     "handling Physical Switch add", () -> handlePortAdded(portAugmentation, add, nodeId));
139             return;
140         }
141
142         LOG.trace("physical locator available {}", identifier);
143         teps.put(identifier, true);
144         List<Runnable> runnableList;
145         synchronized (HwvtepTerminationPointListener.class) {
146             runnableList = waitingJobsList.get(identifier);
147             waitingJobsList.remove(identifier);
148         }
149         if (runnableList != null) {
150             LOG.debug("physical locator available {} running jobs ", identifier);
151             runnableList.forEach(Runnable::run);
152         } else {
153             LOG.debug("no jobs are waiting for physical locator {}", identifier);
154         }
155     }
156
157     @Override
158     protected InstanceIdentifier<TerminationPoint> getWildCardPath() {
159         return InstanceIdentifier.create(NetworkTopology.class)
160                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID)).child(Node.class)
161                 .child(TerminationPoint.class);
162     }
163
164     @Override
165     protected HwvtepTerminationPointListener getDataTreeChangeListener() {
166         return this;
167     }
168
169     private List<ListenableFuture<Void>> handlePortAdded(HwvtepPhysicalPortAugmentation portAugmentation,
170                                                          TerminationPoint portAdded, NodeId psNodeId) {
171         Node psNode = HwvtepUtils.getHwVtepNode(broker, LogicalDatastoreType.OPERATIONAL, psNodeId);
172         if (psNode != null) {
173             String psName = psNode.getAugmentation(PhysicalSwitchAugmentation.class).getHwvtepNodeName().getValue();
174             L2GatewayDevice l2GwDevice = L2GatewayCacheUtils.getL2DeviceFromCache(psName);
175             if (l2GwDevice != null) {
176                 if (isL2GatewayConfigured(l2GwDevice)) {
177                     List<L2gatewayConnection> l2GwConns = L2GatewayConnectionUtils.getAssociatedL2GwConnections(broker,
178                             l2GwDevice.getL2GatewayIds());
179                     String newPortId = portAdded.getTpId().getValue();
180                     NodeId hwvtepNodeId = new NodeId(l2GwDevice.getHwvtepNodeId());
181                     List<VlanBindings> vlanBindings = getVlanBindings(l2GwConns, hwvtepNodeId, psName, newPortId);
182                     List<ListenableFuture<Void>> futures = new ArrayList<>();
183                     futures.add(elanL2GatewayUtils.updateVlanBindingsInL2GatewayDevice(hwvtepNodeId, psName,
184                             newPortId, vlanBindings));
185                     return futures;
186                 }
187             } else {
188                 LOG.error("{} details are not present in L2Gateway Cache", psName);
189             }
190         } else {
191             LOG.error("{} entry not in config datastore", psNodeId);
192         }
193         return Collections.emptyList();
194     }
195
196     private List<ListenableFuture<Void>> handlePortDeleted(InstanceIdentifier<TerminationPoint> identifier,
197                                                            HwvtepPhysicalPortAugmentation portAugmentation,
198                                                            TerminationPoint portDeleted,
199                                                            NodeId psNodeId) throws ReadFailedException {
200         List<ListenableFuture<Void>> futures = new ArrayList<>();
201         InstanceIdentifier<Node> psNodeIid = identifier.firstIdentifierOf(Node.class);
202         final ReadWriteTransaction tx = broker.newReadWriteTransaction();
203         final SettableFuture settableFuture = SettableFuture.create();
204         futures.add(settableFuture);
205         Futures.addCallback(
206                 tx.read(LogicalDatastoreType.CONFIGURATION, psNodeIid), new SettableFutureCallback(settableFuture) {
207                     @Override
208                     public void onSuccess(Object resultNode) {
209                         Optional<Node> nodeOptional = (Optional<Node>) resultNode;
210                         if (nodeOptional.isPresent()) {
211                             //case of port deleted
212                             tx.delete(LogicalDatastoreType.CONFIGURATION, identifier);
213                             Futures.addCallback(tx.submit(), new SettableFutureCallback(settableFuture));
214                         }
215                     }
216                 });
217         return futures;
218     }
219
220     private List<VlanBindings> getVlanBindings(List<L2gatewayConnection> l2GwConns, NodeId hwvtepNodeId, String psName,
221                                                String newPortId) {
222         List<VlanBindings> vlanBindings = new ArrayList<>();
223         for (L2gatewayConnection l2GwConn : l2GwConns) {
224             L2gateway l2Gateway = L2GatewayConnectionUtils.getNeutronL2gateway(broker, l2GwConn.getL2gatewayId());
225             if (l2Gateway == null) {
226                 LOG.error("L2Gateway with id {} is not present", l2GwConn.getL2gatewayId().getValue());
227             } else {
228                 String logicalSwitchName = ElanL2GatewayUtils.getLogicalSwitchFromElan(
229                         l2GwConn.getNetworkId().getValue());
230                 List<Devices> l2Devices = l2Gateway.getDevices();
231                 for (Devices l2Device : l2Devices) {
232                     String l2DeviceName = l2Device.getDeviceName();
233                     if (l2DeviceName != null && l2DeviceName.equals(psName)) {
234                         for (Interfaces deviceInterface : l2Device.getInterfaces()) {
235                             if (deviceInterface.getInterfaceName().equals(newPortId)) {
236                                 if (deviceInterface.getSegmentationIds() != null
237                                         && !deviceInterface.getSegmentationIds().isEmpty()) {
238                                     for (Integer vlanId : deviceInterface.getSegmentationIds()) {
239                                         vlanBindings.add(HwvtepSouthboundUtils.createVlanBinding(hwvtepNodeId, vlanId,
240                                                 logicalSwitchName));
241                                     }
242                                 } else {
243                                     // Use defaultVlanId (specified in L2GatewayConnection) if Vlan
244                                     // ID not specified at interface level.
245                                     Integer segmentationId = l2GwConn.getSegmentId();
246                                     int defaultVlanId = segmentationId != null ? segmentationId : 0;
247                                     vlanBindings.add(HwvtepSouthboundUtils.createVlanBinding(hwvtepNodeId,
248                                             defaultVlanId, logicalSwitchName));
249                                 }
250                             }
251                         }
252                     }
253                 }
254             }
255         }
256         return vlanBindings;
257     }
258
259     private boolean isL2GatewayConfigured(L2GatewayDevice l2GwDevice) {
260         return l2GwDevice.getHwvtepNodeId() != null && l2GwDevice.isConnected()
261                 && l2GwDevice.getL2GatewayIds().size() > 0 && l2GwDevice.getTunnelIp() != null;
262     }
263 }