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