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