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