c371cd0e89a2536509a6d3a5ede7e9333f1f805c
[netvirt.git] / dhcpservice / impl / src / main / java / org / opendaylight / netvirt / dhcpservice / DhcpSubnetListener.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
9 package org.opendaylight.netvirt.dhcpservice;
10
11 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
12
13 import java.util.List;
14 import java.util.Objects;
15 import java.util.Optional;
16 import java.util.concurrent.ExecutionException;
17 import javax.annotation.PreDestroy;
18 import javax.inject.Inject;
19 import javax.inject.Singleton;
20 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
21 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
22 import org.opendaylight.genius.mdsalutil.MDSALUtil;
23 import org.opendaylight.genius.mdsalutil.NwConstants;
24 import org.opendaylight.infrautils.utils.concurrent.Executors;
25 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
26 import org.opendaylight.mdsal.binding.api.DataBroker;
27 import org.opendaylight.mdsal.binding.api.ReadTransaction;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.serviceutils.tools.listener.AbstractClusteredAsyncDataTreeChangeListener;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dhcpservice.config.rev150710.DhcpserviceConfig;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.common.Uint64;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 @Singleton
50 public class DhcpSubnetListener extends AbstractClusteredAsyncDataTreeChangeListener<Subnet> {
51     private static final Logger LOG = LoggerFactory.getLogger(DhcpSubnetListener.class);
52
53     private final DataBroker dataBroker;
54     private final ManagedNewTransactionRunner txRunner;
55     private final DhcpManager dhcpManager;
56     private final DhcpExternalTunnelManager dhcpExternalTunnelManager;
57     private final DhcpserviceConfig config;
58
59     @Inject
60     public DhcpSubnetListener(final DhcpManager dhcpManager, final DhcpExternalTunnelManager
61             dhcpExternalTunnelManager, final DataBroker broker, final DhcpserviceConfig config) {
62         super(broker, LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Neutron.class).child(Subnets.class)
63                 .child(Subnet.class), Executors.newListeningSingleThreadExecutor("DhcpSubnetListener", LOG));
64         this.dhcpManager = dhcpManager;
65         this.dataBroker = broker;
66         this.txRunner = new ManagedNewTransactionRunnerImpl(broker);
67         this.dhcpExternalTunnelManager = dhcpExternalTunnelManager;
68         this.config = config;
69         init();
70     }
71
72     public void init() {
73         if (config.isControllerDhcpEnabled()) {
74             LOG.info("{} init", getClass().getSimpleName());
75         }
76     }
77
78     @Override
79     public void add(InstanceIdentifier<Subnet> identifier, Subnet add) {
80
81     }
82
83     @Override
84     public void remove(InstanceIdentifier<Subnet> identifier, Subnet del) {
85
86     }
87
88     @Override
89     public void update(InstanceIdentifier<Subnet> identifier, Subnet original, Subnet update) {
90         if (!config.isControllerDhcpEnabled()) {
91             return;
92         }
93         LOG.trace("DhcpSubnetListener Update : Original dhcpstatus: {}, Updated dhcpstatus {}", original.isEnableDhcp(),
94                 update.isEnableDhcp());
95
96         if (!Objects.equals(original.isEnableDhcp(), update.isEnableDhcp())) {
97             // write api to get port list
98             SubnetmapBuilder subnetmapBuilder = getSubnetMapBuilder(dataBroker, update.getUuid());
99             List<Uuid> portList = subnetmapBuilder.getPortList();
100             List<Uuid> directPortList = subnetmapBuilder.getDirectPortList();
101
102             if (update.isEnableDhcp()) {
103                 if (null != portList) {
104                     //Install Entries for neutron ports
105                     installNeutronPortEntries(portList);
106                 }
107                 if (null != directPortList) {
108                     //install Entries for direct ports
109                     installDirectPortEntries(directPortList);
110                 }
111             } else {
112                 if (null != portList) {
113                     //UnInstall Entries for neutron ports
114                     uninstallNeutronPortEntries(portList);
115                 }
116                 if (null != directPortList) {
117                     //Uninstall Entries for direct ports
118                     uninstallDirectPortEntries(directPortList);
119                 }
120             }
121         }
122     }
123
124     private void installNeutronPortEntries(List<Uuid> portList) {
125         LOG.trace("DhcpSubnetListener installNeutronPortEntries : portList: {}", portList);
126         for (Uuid portIntf : portList) {
127             NodeConnectorId nodeConnectorId = getNodeConnectorIdForPortIntf(portIntf);
128             Uint64 dpId = DhcpServiceUtils.getDpnIdFromNodeConnectorId(nodeConnectorId);
129             String interfaceName = portIntf.getValue();
130             Port port = dhcpManager.getNeutronPort(interfaceName);
131             String vmMacAddress = port.getMacAddress().getValue();
132             //check whether any changes have happened
133             LOG.trace("DhcpSubnetListener installNeutronPortEntries dpId: {} vmMacAddress : {}", dpId, vmMacAddress);
134             //Bind the dhcp service when enabled
135             ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
136                 tx -> DhcpServiceUtils.bindDhcpService(interfaceName, NwConstants.DHCP_TABLE, tx)), LOG,
137                 "Error writing to the datastore");
138             //install the entries
139             ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
140                 tx -> dhcpManager.installDhcpEntries(dpId, vmMacAddress, tx)), LOG,
141                 "Error writing to the datastore");
142         }
143     }
144
145     private void uninstallNeutronPortEntries(List<Uuid> portList) {
146         LOG.trace("DhcpSubnetListener uninstallNeutronPortEntries : portList: {}", portList);
147         for (Uuid portIntf : portList) {
148             NodeConnectorId nodeConnectorId = getNodeConnectorIdForPortIntf(portIntf);
149             Uint64 dpId = DhcpServiceUtils.getDpnIdFromNodeConnectorId(nodeConnectorId);
150             String interfaceName = portIntf.getValue();
151             Port port = dhcpManager.getNeutronPort(interfaceName);
152             String vmMacAddress = port.getMacAddress().getValue();
153             //check whether any changes have happened
154             LOG.trace("DhcpSubnetListener uninstallNeutronPortEntries dpId: {} vmMacAddress : {}",
155                     dpId, vmMacAddress);
156             //Unbind the dhcp service when disabled
157             ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
158                 tx -> DhcpServiceUtils.unbindDhcpService(interfaceName, tx)), LOG,
159                 "Error writing to the datastore");
160
161             //uninstall the entries
162             ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
163                 tx -> dhcpManager.unInstallDhcpEntries(dpId, vmMacAddress, tx)), LOG,
164                 "Error writing to the datastore");
165         }
166     }
167
168     private void installDirectPortEntries(List<Uuid> directPortList) {
169         LOG.trace("DhcpSubnetListener installDirectPortEntries : directPortList: {}", directPortList);
170         for (Uuid portIntf : directPortList) {
171             Port port = dhcpManager.getNeutronPort(portIntf.getValue());
172             String vmMacAddress = port.getMacAddress().getValue();
173             Uuid networkId = port.getNetworkId();
174             //install the entries on designated dpnId
175             List<Uint64> listOfDpns = DhcpServiceUtils.getListOfDpns(dataBroker);
176             IpAddress tunnelIp = dhcpExternalTunnelManager.getTunnelIpBasedOnElan(networkId.getValue(), vmMacAddress);
177             if (null == tunnelIp) {
178                 LOG.warn("DhcpSubnetListener installDirectPortEntries tunnelIP is null for  port {}", portIntf);
179                 continue;
180             }
181             Uint64 designatedDpnId =
182                     dhcpExternalTunnelManager.readDesignatedSwitchesForExternalTunnel(tunnelIp, networkId.getValue());
183             LOG.trace("CR-DHCP DhcpSubnetListener update Install DIRECT vmMacAddress: {} tunnelIp: {} "
184                     + "designatedDpnId : {} ListOf Dpn: {}",
185                     vmMacAddress, tunnelIp, designatedDpnId, listOfDpns);
186             dhcpExternalTunnelManager.installDhcpFlowsForVms(tunnelIp, networkId.getValue(), listOfDpns,
187                     designatedDpnId, vmMacAddress);
188
189         }
190     }
191
192     private void uninstallDirectPortEntries(List<Uuid> directPortList) {
193         LOG.trace("DhcpSubnetListener uninstallDirectPortEntries : directPortList: {}", directPortList);
194         for (Uuid portIntf : directPortList) {
195             Port port = dhcpManager.getNeutronPort(portIntf.getValue());
196             String vmMacAddress = port.getMacAddress().getValue();
197             Uuid networkId = port.getNetworkId();
198             List<Uint64> listOfDpns = DhcpServiceUtils.getListOfDpns(dataBroker);
199             LOG.trace("DhcpSubnetListener uninstallDirectPortEntries  vmMacAddress: {} networkId: {} ListOf Dpn: {}",
200                     vmMacAddress, networkId, listOfDpns);
201             dhcpExternalTunnelManager.unInstallDhcpFlowsForVms(networkId.getValue(), listOfDpns, vmMacAddress);
202         }
203     }
204
205
206     private NodeConnectorId getNodeConnectorIdForPortIntf(Uuid interfaceName) {
207         LOG.trace("DhcpSubnetListener getNodeConnectorIdForPortIntf  interfaceName: {}", interfaceName);
208         NodeConnectorId nodeConnectorId = null;
209         InstanceIdentifier.InstanceIdentifierBuilder<Interface> idBuilder =
210                 InstanceIdentifier.builder(InterfacesState.class)
211                         .child(Interface.class,
212                                 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
213                                         .rev140508.interfaces.state.InterfaceKey(interfaceName.getValue()));
214
215         InstanceIdentifier<Interface> ifStateId = idBuilder.build();
216
217         Optional<Interface> ifStateOptional = MDSALUtil.read(LogicalDatastoreType.OPERATIONAL, ifStateId, dataBroker);
218         Interface interfaceState = null;
219         if (ifStateOptional.isPresent()) {
220             interfaceState = ifStateOptional.get();
221         }
222         if (interfaceState != null) {
223             List<String> ofportIds = interfaceState.getLowerLayerIf();
224             nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
225             LOG.trace(
226                     "DhcpSubnetListener getNodeConnectorIdForPortIntf returned nodeConnectorId {} for the interface {}",
227                     nodeConnectorId.getValue(), interfaceName);
228         }
229         return nodeConnectorId;
230     }
231
232     private SubnetmapBuilder getSubnetMapBuilder(DataBroker broker, Uuid subnetId) {
233         SubnetmapBuilder builder = null ;
234         InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class)
235                 .child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
236         ReadTransaction tx = broker.newReadOnlyTransaction();
237
238         Optional<Subnetmap> sn ;
239         try {
240             sn = tx.read(LogicalDatastoreType.CONFIGURATION, id).get();
241         } catch (InterruptedException | ExecutionException e) {
242             throw new RuntimeException(e);
243         } finally {
244             tx.close();
245         }
246
247         if (sn.isPresent()) {
248             builder = new SubnetmapBuilder(sn.get());
249         } else {
250             builder = new SubnetmapBuilder().withKey(new SubnetmapKey(subnetId)).setId(subnetId);
251         }
252         return builder;
253     }
254
255     @Override
256     @PreDestroy
257     public void close() {
258         super.close();
259         Executors.shutdownAndAwaitTermination(getExecutorService());
260         LOG.info("DhcpSubnetListener Closed");
261     }
262 }