NETVIRT-1563: karaf cmd display in proper format
[netvirt.git] / neutronvpn / impl / src / main / java / org / opendaylight / netvirt / neutronvpn / l2gw / L2GatewayListener.java
1 /*
2  * Copyright (c) 2016, 2018 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.neutronvpn.l2gw;
9
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
11
12 import com.google.common.collect.Sets;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import javax.annotation.PostConstruct;
24 import javax.inject.Inject;
25 import javax.inject.Singleton;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.genius.datastoreutils.AsyncClusteredDataTreeChangeListenerBase;
29 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
30 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
31 import org.opendaylight.genius.mdsalutil.MDSALUtil;
32 import org.opendaylight.genius.utils.SystemPropertyReader;
33 import org.opendaylight.genius.utils.clustering.EntityOwnershipUtils;
34 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundConstants;
35 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundUtils;
36 import org.opendaylight.genius.utils.hwvtep.HwvtepUtils;
37 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
39 import org.opendaylight.netvirt.elanmanager.api.IL2gwService;
40 import org.opendaylight.netvirt.neutronvpn.api.l2gw.L2GatewayCache;
41 import org.opendaylight.netvirt.neutronvpn.api.l2gw.L2GatewayDevice;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.attributes.Devices;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.attributes.devices.Interfaces;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.connections.attributes.L2gatewayConnections;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.connections.attributes.l2gatewayconnections.L2gatewayConnection;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateways.attributes.L2gateways;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateways.attributes.l2gateways.L2gateway;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
51 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 @Singleton
57 public class L2GatewayListener extends AsyncClusteredDataTreeChangeListenerBase<L2gateway, L2GatewayListener> {
58     private static final Logger LOG = LoggerFactory.getLogger(L2GatewayListener.class);
59     private final DataBroker dataBroker;
60     private final ManagedNewTransactionRunner txRunner;
61     private final ItmRpcService itmRpcService;
62     private final IL2gwService l2gwService;
63     private final EntityOwnershipUtils entityOwnershipUtils;
64     private final JobCoordinator jobCoordinator;
65     private final L2GatewayCache l2GatewayCache;
66
67     @Inject
68     public L2GatewayListener(final DataBroker dataBroker, final EntityOwnershipService entityOwnershipService,
69                              final ItmRpcService itmRpcService, final IL2gwService l2gwService,
70                              final JobCoordinator jobCoordinator, final L2GatewayCache l2GatewayCache) {
71         this.dataBroker = dataBroker;
72         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
73         this.entityOwnershipUtils = new EntityOwnershipUtils(entityOwnershipService);
74         this.itmRpcService = itmRpcService;
75         this.l2gwService = l2gwService;
76         this.jobCoordinator = jobCoordinator;
77         this.l2GatewayCache = l2GatewayCache;
78     }
79
80     @PostConstruct
81     public void init() {
82         LOG.info("{} init", getClass().getSimpleName());
83         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
84     }
85
86     @Override
87     protected InstanceIdentifier<L2gateway> getWildCardPath() {
88         return InstanceIdentifier.create(Neutron.class).child(L2gateways.class).child(L2gateway.class);
89     }
90
91     @Override
92     protected void add(final InstanceIdentifier<L2gateway> identifier, final L2gateway input) {
93         LOG.info("Adding L2gateway with ID: {}", input.getUuid());
94
95         for (Devices l2Device : input.nonnullDevices()) {
96             LOG.trace("Adding L2gateway device: {}", l2Device);
97             addL2Device(l2Device, input);
98         }
99     }
100
101     @Override
102     protected void remove(final InstanceIdentifier<L2gateway> identifier, final L2gateway input) {
103         LOG.info("Removing L2gateway with ID: {}", input.getUuid());
104         List<L2gatewayConnection> connections = l2gwService
105                 .getL2GwConnectionsByL2GatewayId(input.getUuid());
106         Futures.addCallback(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, tx -> {
107             for (L2gatewayConnection connection : connections) {
108                 InstanceIdentifier<L2gatewayConnection> iid = InstanceIdentifier.create(Neutron.class)
109                         .child(L2gatewayConnections.class).child(L2gatewayConnection.class, connection.key());
110                 tx.delete(iid);
111             }
112         }), new FutureCallback<Void>() {
113             @Override
114             public void onSuccess(Void result) {
115                 for (Devices l2Device : input.nonnullDevices()) {
116                     LOG.trace("Removing L2gateway device: {}", l2Device);
117                     removeL2Device(l2Device, input);
118                 }
119             }
120
121             @Override
122             public void onFailure(Throwable throwable) {
123                 LOG.error("Failed to delete associated l2gwconnection while deleting l2gw {} with id",
124                         input.getUuid(), throwable);
125             }
126         }, MoreExecutors.directExecutor());
127     }
128
129     @Override
130     protected void update(InstanceIdentifier<L2gateway> identifier, L2gateway original, L2gateway update) {
131         LOG.trace("Updating L2gateway : key: {}, original value={}, update value={}", identifier, original, update);
132         List<L2gatewayConnection> connections = l2gwService.getAssociatedL2GwConnections(
133                 Sets.newHashSet(update.getUuid()));
134         if (connections == null) {
135             LOG.warn("There are no connections associated with l2 gateway uuid {} name {}",
136                     update.getUuid(), update.getName());
137             return;
138         }
139         if (original.getDevices() == null) {
140             connections.forEach(l2gwService::addL2GatewayConnection);
141             return;
142         }
143         jobCoordinator.enqueueJob("l2gw.update", () -> {
144             ListenableFuture<Void> future = txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, tx -> {
145                 DeviceInterfaces updatedDeviceInterfaces = new DeviceInterfaces(update);
146                 original.getDevices()
147                         .stream()
148                         .filter((originalDevice) -> originalDevice.getInterfaces() != null)
149                         .forEach((originalDevice) -> {
150                             String deviceName = originalDevice.getDeviceName();
151                             L2GatewayDevice l2GwDevice = l2GatewayCache.get(deviceName);
152                             NodeId physicalSwitchNodeId = HwvtepSouthboundUtils.createManagedNodeId(
153                                     new NodeId(l2GwDevice.getHwvtepNodeId()), deviceName);
154                             originalDevice.getInterfaces()
155                                     .stream()
156                                     .filter((intf) -> !updatedDeviceInterfaces.containsInterface(
157                                             deviceName, intf.getInterfaceName()))
158                                     .forEach((intf) -> connections.forEach((connection) -> {
159                                         Integer vlanId = connection.getSegmentId();
160                                         if (intf.getSegmentationIds() != null
161                                                 && !intf.getSegmentationIds().isEmpty()) {
162                                             for (Integer vlan : intf.getSegmentationIds()) {
163                                                 HwvtepUtils.deleteVlanBinding(tx,
164                                                         physicalSwitchNodeId, intf.getInterfaceName(), vlan);
165                                             }
166                                         } else {
167                                             LOG.debug("Deleting vlan binding {} {} {}",
168                                                     physicalSwitchNodeId, intf.getInterfaceName(), vlanId);
169                                             HwvtepUtils.deleteVlanBinding(tx, physicalSwitchNodeId,
170                                                     intf.getInterfaceName(), vlanId);
171                                         }
172                                     }));
173                         });
174             });
175             Futures.addCallback(future, new FutureCallback<Void>() {
176                 @Override
177                 public void onSuccess(Void success) {
178                     LOG.debug("Successfully deleted vlan bindings for l2gw update {}", update);
179                         connections.forEach((l2GwConnection) ->
180                                 l2gwService.addL2GatewayConnection(l2GwConnection, null, update));
181                 }
182
183                 @Override
184                 public void onFailure(Throwable throwable) {
185                     LOG.error("Failed to delete vlan bindings as part of l2gw udpate {}", update);
186                 }
187             }, MoreExecutors.directExecutor());
188             return Collections.singletonList(future);
189         }, SystemPropertyReader.getDataStoreJobCoordinatorMaxRetries());
190     }
191
192     private synchronized void addL2Device(Devices l2Device, L2gateway input) {
193         String l2DeviceName = l2Device.getDeviceName();
194
195         L2GatewayDevice l2GwDevice = l2GatewayCache.addOrGet(l2DeviceName);
196         l2GwDevice.addL2GatewayId(input.getUuid());
197         if (l2GwDevice.getHwvtepNodeId() == null) {
198             LOG.info("L2GW provisioning skipped for device {}",l2DeviceName);
199         } else {
200             LOG.info("Provisioning l2gw for device {}",l2DeviceName);
201             l2gwService.provisionItmAndL2gwConnection(l2GwDevice, l2DeviceName, l2GwDevice.getHwvtepNodeId(),
202                     l2GwDevice.getTunnelIp());
203         }
204     }
205
206     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
207             justification = "https://github.com/spotbugs/spotbugs/issues/811")
208     private void removeL2Device(Devices l2Device, L2gateway input) {
209         final String l2DeviceName = l2Device.getDeviceName();
210         L2GatewayDevice l2GwDevice = l2GatewayCache.get(l2DeviceName);
211         if (l2GwDevice != null) {
212             // Delete ITM tunnels if it's last Gateway deleted and device is connected
213             // Also, do not delete device from cache if it's connected
214             if (L2GatewayUtils.isLastL2GatewayBeingDeleted(l2GwDevice)) {
215                 if (l2GwDevice.isConnected()) {
216                     l2GwDevice.removeL2GatewayId(input.getUuid());
217                     // Delete ITM tunnels
218                     final String hwvtepId = l2GwDevice.getHwvtepNodeId();
219
220                     final Set<IpAddress> tunnelIps = l2GwDevice.getTunnelIps();
221                     jobCoordinator.enqueueJob(hwvtepId, () -> {
222                         if (entityOwnershipUtils.isEntityOwner(HwvtepSouthboundConstants.ELAN_ENTITY_TYPE,
223                                 HwvtepSouthboundConstants.ELAN_ENTITY_NAME)) {
224                             LOG.info("Deleting ITM Tunnels for {} connected to cluster node owner", l2DeviceName);
225                             for (IpAddress tunnelIp : tunnelIps) {
226                                 L2GatewayUtils.deleteItmTunnels(itmRpcService, hwvtepId, l2DeviceName, tunnelIp);
227                             }
228                         } else {
229                             LOG.info("ITM Tunnels are not deleted on the cluster node as this is not owner for {}",
230                                     l2DeviceName);
231                         }
232
233                         return null;
234                     });
235                 } else {
236                     l2GatewayCache.remove(l2DeviceName);
237                     // Cleaning up the config DS
238                     NodeId nodeId = new NodeId(l2GwDevice.getHwvtepNodeId());
239                     NodeId psNodeId = HwvtepSouthboundUtils.createManagedNodeId(nodeId, l2DeviceName);
240                     //FIXME: These should be removed
241                     MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION,
242                             HwvtepSouthboundUtils.createInstanceIdentifier(nodeId));
243                     MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION,
244                             HwvtepSouthboundUtils.createInstanceIdentifier(psNodeId));
245
246                 }
247             } else {
248                 l2GwDevice.removeL2GatewayId(input.getUuid());
249                 LOG.trace("ITM tunnels are not deleted for {} as this device has other L2gateway associations",
250                         l2DeviceName);
251             }
252         } else {
253             LOG.error("Unable to find L2 Gateway details for {}", l2DeviceName);
254         }
255     }
256
257     @Override
258     protected L2GatewayListener getDataTreeChangeListener() {
259         return this;
260     }
261
262     static class DeviceInterfaces {
263         Map<String, Map<String, Interfaces>> deviceInterfacesMap = new HashMap<>();
264
265         DeviceInterfaces(L2gateway l2gateway) {
266             if (l2gateway.getDevices() != null) {
267                 l2gateway.getDevices().forEach((device) -> {
268                     deviceInterfacesMap.putIfAbsent(device.getDeviceName(), new HashMap<>());
269                     if (device.getInterfaces() != null) {
270                         device.getInterfaces().forEach((intf) ->
271                                 deviceInterfacesMap.get(device.getDeviceName()).put(intf.getInterfaceName(), intf));
272                     }
273                 });
274             }
275         }
276
277         boolean containsInterface(String deviceName, String interfaceName) {
278             if (deviceInterfacesMap.containsKey(deviceName)) {
279                 return deviceInterfacesMap.get(deviceName).containsKey(interfaceName);
280             }
281             return false;
282         }
283     }
284 }