L2 Gw create changes related to ITM Tunnels creation in neutronvpn module
[vpnservice.git] / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / vpnservice / neutronvpn / l2gw / L2GatewayListener.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.vpnservice.neutronvpn.l2gw;
9
10 import java.util.ArrayList;
11 import java.util.List;
12 import java.util.concurrent.Callable;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.Future;
15
16 import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
17 import org.opendaylight.yangtools.concepts.ListenerRegistration;
18 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
19 import org.opendaylight.yangtools.yang.common.RpcResult;
20 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
21 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataChangeListener;
25 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
26 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
28 import org.opendaylight.vpnservice.utils.clustering.ClusteringUtils;
29 import org.opendaylight.vpnservice.datastoreutils.AsyncClusteredDataChangeListenerBase;
30 import org.opendaylight.vpnservice.neutronvpn.api.l2gw.L2GatewayDevice;
31 import org.opendaylight.vpnservice.neutronvpn.api.l2gw.utils.L2GatewayCacheUtils;
32 import org.opendaylight.vpnservice.utils.hwvtep.HwvtepSouthboundConstants;
33 import org.opendaylight.vpnservice.utils.hwvtep.HwvtepSouthboundUtils;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
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.l2gateways.attributes.L2gateways;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateways.attributes.l2gateways.L2gateway;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.ItmRpcService;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.google.common.util.concurrent.ListenableFuture;
46 import com.google.common.util.concurrent.FutureCallback;
47 import com.google.common.util.concurrent.Futures;
48
49 public class L2GatewayListener extends AsyncClusteredDataChangeListenerBase<L2gateway, L2GatewayListener>
50         implements AutoCloseable {
51     private static final Logger LOG = LoggerFactory.getLogger(L2GatewayListener.class);
52
53     private ListenerRegistration<DataChangeListener> listenerRegistration;
54     private final DataBroker broker;
55     private ItmRpcService itmRpcService;
56     private EntityOwnershipService entityOwnershipService;
57     private BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer;
58
59     public L2GatewayListener(final DataBroker db, RpcProviderRegistry rpcRegistry,
60             EntityOwnershipService entityOwnershipService,
61             BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer) {
62         super(L2gateway.class, L2GatewayListener.class);
63         broker = db;
64         this.entityOwnershipService = entityOwnershipService;
65         this.bindingNormalizedNodeSerializer = bindingNormalizedNodeSerializer;
66         itmRpcService = rpcRegistry.getRpcService(ItmRpcService.class);
67         registerListener(db);
68     }
69
70     @Override
71     public void close() throws Exception {
72         if (listenerRegistration != null) {
73             try {
74                 listenerRegistration.close();
75             } catch (final Exception e) {
76                 LOG.error("Error when cleaning up DataChangeListener.", e);
77             }
78             listenerRegistration = null;
79         }
80         LOG.info("L2 Gateway listener Closed");
81     }
82
83     private void registerListener(final DataBroker db) {
84         try {
85             listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
86                     InstanceIdentifier.create(Neutron.class).child(L2gateways.class).child(L2gateway.class),
87                     L2GatewayListener.this, DataChangeScope.SUBTREE);
88         } catch (final Exception e) {
89             LOG.error("Neutron Manager L2 Gateway DataChange listener registration fail!", e);
90             throw new IllegalStateException("Neutron Manager L2 Gateway DataChange listener registration failed.", e);
91         }
92     }
93
94     @Override
95     protected void add(final InstanceIdentifier<L2gateway> identifier, final L2gateway input) {
96         LOG.info("Adding L2gateway with ID: {}", input.getUuid());
97
98         List<Devices> l2Devices = input.getDevices();
99         for (Devices l2Device : l2Devices) {
100             if (LOG.isTraceEnabled()) {
101                 LOG.trace("Adding L2gateway device: {}", l2Device);
102             }
103             addL2Device(l2Device, input);
104         }
105     }
106
107     @Override
108     protected void remove(final InstanceIdentifier<L2gateway> identifier, final L2gateway input) {
109         LOG.info("Removing L2gateway with ID: {}", input.getUuid());
110
111         List<Devices> l2Devices = input.getDevices();
112         for (Devices l2Device : l2Devices) {
113             if (LOG.isTraceEnabled()) {
114                 LOG.trace("Removing L2gateway device: {}", l2Device);
115             }
116             removeL2Device(l2Device, input);
117         }
118     }
119
120     @Override
121     protected void update(InstanceIdentifier<L2gateway> identifier, L2gateway original, L2gateway update) {
122         if (LOG.isTraceEnabled()) {
123             LOG.trace("Updating L2gateway : key: " + identifier + ", original value=" + original + ", update value="
124                     + update);
125         }
126     }
127
128     private void addL2Device(Devices l2Device, L2gateway input) {
129         final String l2DeviceName = l2Device.getDeviceName();
130         L2GatewayDevice l2GwDevice = L2GatewayCacheUtils.getL2DeviceFromCache(l2DeviceName);
131         if (l2GwDevice != null) {
132             if (!L2GatewayUtils.isGatewayAssociatedToL2Device(l2GwDevice)
133                     && L2GatewayUtils.isL2GwDeviceConnected(l2GwDevice)) {
134                 // VTEP already discovered; create ITM tunnels
135                 final String hwvtepId = l2GwDevice.getHwvtepNodeId();
136                 InstanceIdentifier<Node> iid = HwvtepSouthboundUtils.createInstanceIdentifier(new NodeId(hwvtepId));
137                 ListenableFuture<Boolean> checkEntityOwnerFuture = ClusteringUtils.checkNodeEntityOwner(
138                         entityOwnershipService, HwvtepSouthboundConstants.HWVTEP_ENTITY_TYPE,
139                         bindingNormalizedNodeSerializer.toYangInstanceIdentifier(iid));
140                 final List<IpAddress> tunnelIps = l2GwDevice.getTunnelIps();
141                 Futures.addCallback(checkEntityOwnerFuture, new FutureCallback<Boolean>() {
142                     @Override
143                     public void onSuccess(Boolean isOwner) {
144                         if (isOwner) {
145                             LOG.info("Creating ITM Tunnels for {} connected to cluster node owner", l2DeviceName);
146                             for (IpAddress tunnelIp : tunnelIps) {
147                                 L2GatewayUtils.createItmTunnels(itmRpcService, hwvtepId, l2DeviceName, tunnelIp);
148                             }
149                         } else {
150                             LOG.info("ITM Tunnels are not created on the cluster node as this is not owner for {}",
151                                     l2DeviceName);
152                         }
153                     }
154
155                     @Override
156                     public void onFailure(Throwable error) {
157                         LOG.error("Failed to create ITM tunnels", error);
158                     }
159                 });
160             } else {
161                 LOG.trace("ITM tunnels are already created for device {}", l2DeviceName);
162             }
163         } else {
164             LOG.trace("{} is not connected; ITM tunnels will be created when device comes up", l2DeviceName);
165             // Pre-provision scenario. Create L2GatewayDevice without VTEP
166             // details for pushing configurations as soon as device discovered
167             l2GwDevice = new L2GatewayDevice();
168             l2GwDevice.setDeviceName(l2DeviceName);
169             L2GatewayCacheUtils.addL2DeviceToCache(l2DeviceName, l2GwDevice);
170         }
171         l2GwDevice.addL2GatewayId(input.getUuid());
172     }
173
174     private void removeL2Device(Devices l2Device, L2gateway input) {
175         final String l2DeviceName = l2Device.getDeviceName();
176         L2GatewayDevice l2GwDevice = L2GatewayCacheUtils.getL2DeviceFromCache(l2DeviceName);
177         if (l2GwDevice != null) {
178             // Delete ITM tunnels if it's last Gateway deleted and device is connected
179             // Also, do not delete device from cache if it's connected
180             if (L2GatewayUtils.isLastL2GatewayBeingDeleted(l2GwDevice)) {
181                 if (L2GatewayUtils.isL2GwDeviceConnected(l2GwDevice)) {
182                     l2GwDevice.removeL2GatewayId(input.getUuid());
183                     // Delete ITM tunnels
184                     final String hwvtepId = l2GwDevice.getHwvtepNodeId();
185                     InstanceIdentifier<Node> iid = HwvtepSouthboundUtils.createInstanceIdentifier(new NodeId(hwvtepId));
186                     ListenableFuture<Boolean> checkEntityOwnerFuture = ClusteringUtils.checkNodeEntityOwner(
187                             entityOwnershipService, HwvtepSouthboundConstants.HWVTEP_ENTITY_TYPE,
188                             bindingNormalizedNodeSerializer.toYangInstanceIdentifier(iid));
189                     final List<IpAddress> tunnelIps = l2GwDevice.getTunnelIps();
190                     Futures.addCallback(checkEntityOwnerFuture, new FutureCallback<Boolean>() {
191                         @Override
192                         public void onSuccess(Boolean isOwner) {
193                             if (isOwner) {
194                                 LOG.info("Deleting ITM Tunnels for {} connected to cluster node owner", l2DeviceName);
195                                 for (IpAddress tunnelIp : tunnelIps) {
196                                     L2GatewayUtils.deleteItmTunnels(itmRpcService, hwvtepId, l2DeviceName, tunnelIp);
197                                 }
198                             } else {
199                                 LOG.info("ITM Tunnels are not deleted on the cluster node as this is not owner for {}",
200                                         l2DeviceName);
201                             }
202                         }
203
204                         @Override
205                         public void onFailure(Throwable error) {
206                             LOG.error("Failed to delete ITM tunnels", error);
207                         }
208                     });
209                 } else {
210                     L2GatewayCacheUtils.removeL2DeviceFromCache(l2DeviceName);
211                 }
212             } else {
213                 l2GwDevice.removeL2GatewayId(input.getUuid());
214                 LOG.trace("ITM tunnels are not deleted for {} as this device has other L2gateway associations",
215                         l2DeviceName);
216             }
217         } else {
218             LOG.error("Unable to find L2 Gateway details for {}", l2DeviceName);
219         }
220     }
221
222     @Override
223     protected InstanceIdentifier<L2gateway> getWildCardPath() {
224         return InstanceIdentifier.create(L2gateway.class);
225     }
226
227     @Override
228     protected ClusteredDataChangeListener getDataChangeListener() {
229         return L2GatewayListener.this;
230     }
231
232     @Override
233     protected DataChangeScope getDataChangeScope() {
234         return AsyncDataBroker.DataChangeScope.BASE;
235     }
236 }