Stop using MDSALDataStoreUtils
[netvirt.git] / dhcpservice / impl / src / main / java / org / opendaylight / netvirt / dhcpservice / DhcpAllocationPoolManager.java
1 /*
2  * Copyright (c) 2017 Hewlett Packard Enterprise, Co. 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.dhcpservice;
9
10 import com.google.common.base.Optional;
11 import java.math.BigInteger;
12 import java.util.EventListener;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
17 import java.util.stream.Collectors;
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.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
25 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
26 import org.opendaylight.genius.mdsalutil.MDSALUtil;
27 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
28 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
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.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInputBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp_allocation_pool.rev161214.DhcpAllocationPool;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp_allocation_pool.rev161214.dhcp_allocation_pool.Network;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp_allocation_pool.rev161214.dhcp_allocation_pool.NetworkKey;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp_allocation_pool.rev161214.dhcp_allocation_pool.network.AllocationPool;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dhcpservice.config.rev150710.DhcpserviceConfig;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.RpcResult;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 @Singleton
58 public class DhcpAllocationPoolManager implements AutoCloseable, EventListener {
59     private static final Logger LOG = LoggerFactory.getLogger(DhcpAllocationPoolManager.class);
60
61     private DhcpAllocationPoolListener dhcpAllocationPoolListener;
62
63     private final DataBroker dataBroker;
64     private final IdManagerService idManager;
65     private final DhcpserviceConfig config;
66     private final JobCoordinator jobCoordinator;
67
68     @Inject
69     public DhcpAllocationPoolManager(final DataBroker dataBroker, final IdManagerService idManager,
70             final DhcpserviceConfig config, final JobCoordinator jobCoordinator) {
71         this.dataBroker = dataBroker;
72         this.idManager = idManager;
73         this.config = config;
74         this.jobCoordinator = jobCoordinator;
75     }
76
77     @PostConstruct
78     public void init() {
79         if (config.isDhcpDynamicAllocationPoolEnabled()) {
80             dhcpAllocationPoolListener = new DhcpAllocationPoolListener(this, dataBroker, jobCoordinator);
81             LOG.info("DHCP Allocation Pool Service initialized");
82         }
83     }
84
85     @Override
86     @PreDestroy
87     public void close() {
88         LOG.info("{} close", getClass().getSimpleName());
89         if (dhcpAllocationPoolListener != null) {
90             dhcpAllocationPoolListener.close();
91         }
92     }
93
94     public IpAddress getIpAllocation(String networkId, AllocationPool pool, String macAddress) {
95         String poolIdKey = getPoolKeyIdByAllocationPool(networkId, pool);
96         long allocatedIpLong = createIdAllocation(poolIdKey, macAddress);
97         LOG.debug("allocated id {} for mac {}, from pool {}", allocatedIpLong, macAddress, poolIdKey);
98         IpAddress allocatedIpAddress = allocatedIpLong != 0 ? DhcpServiceUtils.convertLongToIp(allocatedIpLong)
99                 : null;
100         return allocatedIpAddress;
101     }
102
103     public void releaseIpAllocation(String networkId, AllocationPool pool, String macAddress) {
104         String poolIdKey = getPoolKeyIdByAllocationPool(networkId, pool);
105         LOG.debug("going to release id for mac {}, from pool {}", macAddress, poolIdKey);
106         releaseIdAllocation(poolIdKey, macAddress);
107     }
108
109     public AllocationPool getAllocationPoolByNetwork(String networkId) throws ReadFailedException {
110         InstanceIdentifier<Network> network = InstanceIdentifier.builder(DhcpAllocationPool.class)
111                 .child(Network.class, new NetworkKey(networkId)).build();
112         Optional<Network> optionalNetworkConfData = SingleTransactionDataBroker.syncReadOptional(dataBroker,
113                 LogicalDatastoreType.CONFIGURATION, network);
114         if (!optionalNetworkConfData.isPresent()) {
115             LOG.info("No network configuration data for network {}", networkId);
116             return null;
117         }
118         Network networkConfData = optionalNetworkConfData.get();
119         List<AllocationPool> allocationPoolList = networkConfData.getAllocationPool();
120         // if network has allocation pool list - get the first element
121         // as we have no info about a specific subnet
122         if (allocationPoolList != null && !allocationPoolList.isEmpty()) {
123             return allocationPoolList.get(0);
124         } else {
125             LOG.warn("No allocation pools for network {}", networkId);
126             return null;
127         }
128     }
129
130     public Map<BigInteger, List<String>> getElanDpnInterfacesByName(DataBroker broker, String elanInstanceName) {
131         InstanceIdentifier<ElanDpnInterfacesList> elanDpnIfacesIid = InstanceIdentifier.builder(ElanDpnInterfaces.class)
132                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
133         Optional<ElanDpnInterfacesList> elanDpnIfacesOpc = MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL,
134                 elanDpnIfacesIid);
135         if (!elanDpnIfacesOpc.isPresent()) {
136             LOG.warn("Could not find DpnInterfaces for elan {}", elanInstanceName);
137             return null;
138         }
139
140         return elanDpnIfacesOpc.get().getDpnInterfaces().stream()
141                 .collect(Collectors.toMap(DpnInterfaces::getDpId, DpnInterfaces::getInterfaces));
142     }
143
144     public String getNetworkByPort(String portUuid) throws ReadFailedException {
145         InstanceIdentifier<ElanInterface> elanInterfaceName = InstanceIdentifier.builder(ElanInterfaces.class)
146                 .child(ElanInterface.class, new ElanInterfaceKey(portUuid)).build();
147         Optional<ElanInterface> optionalElanInterface = SingleTransactionDataBroker.syncReadOptional(dataBroker,
148                 LogicalDatastoreType.CONFIGURATION, elanInterfaceName);
149         if (!optionalElanInterface.isPresent()) {
150             LOG.info("No elan interface data for port {}", portUuid);
151             return null;
152         }
153         ElanInterface elanInterface = optionalElanInterface.get();
154         return elanInterface.getElanInstanceName();
155     }
156
157     private String getPoolKeyIdByAllocationPool(String networkId, AllocationPool pool) {
158         return "dhcpAllocationPool." + networkId + "." + String.valueOf(pool.getSubnet().getValue());
159     }
160
161     private long createIdAllocation(String groupIdKey, String idKey) {
162         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(groupIdKey).setIdKey(idKey).build();
163         try {
164             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
165             RpcResult<AllocateIdOutput> rpcResult = result.get();
166             return rpcResult.getResult().getIdValue();
167         } catch (NullPointerException | InterruptedException | ExecutionException e) {
168             LOG.trace("Failed to allocate id for DHCP Allocation Pool Service", e);
169         }
170         return 0;
171     }
172
173     private void releaseIdAllocation(String groupIdKey, String idKey) {
174         ReleaseIdInput getIdInput = new ReleaseIdInputBuilder().setPoolName(groupIdKey).setIdKey(idKey).build();
175         JdkFutures.addErrorLogging(idManager.releaseId(getIdInput), LOG, "Release Id");
176     }
177
178     protected void createIdAllocationPool(String networkId, AllocationPool pool) {
179         String poolName = getPoolKeyIdByAllocationPool(networkId, pool);
180         long low = DhcpServiceUtils.convertIpToLong(pool.getAllocateFrom());
181         long high = DhcpServiceUtils.convertIpToLong(pool.getAllocateTo());
182         CreateIdPoolInput createPool = new CreateIdPoolInputBuilder().setPoolName(poolName).setLow(low).setHigh(high)
183                 .build();
184         try {
185             Future<RpcResult<Void>> result = idManager.createIdPool(createPool);
186             if (result != null && result.get().isSuccessful()) {
187                 LOG.info("DHCP Allocation Pool Service : Created IdPool name {}", poolName);
188             } else {
189                 LOG.error("DHCP Allocation Pool Service : Unable to create IdPool name {}", poolName);
190             }
191         } catch (InterruptedException | ExecutionException e) {
192             LOG.error("Failed to create Pool for DHCP Allocation Pool Service", e);
193         }
194     }
195
196     protected void releaseIdAllocationPool(String networkId, AllocationPool pool) {
197         String poolName = getPoolKeyIdByAllocationPool(networkId, pool);
198         DeleteIdPoolInput deletePool = new DeleteIdPoolInputBuilder().setPoolName(poolName).build();
199         try {
200             Future<RpcResult<Void>> result = idManager.deleteIdPool(deletePool);
201             if (result != null && result.get().isSuccessful()) {
202                 LOG.info("DHCP Allocation Pool Service : Deleted IdPool name {}", poolName);
203             } else {
204                 LOG.error("DHCP Allocation Pool Service : Unable to delete IdPool name {}", poolName);
205             }
206         } catch (InterruptedException | ExecutionException e) {
207             LOG.error("Failed to delete Pool for DHCP Allocation Pool Service", e);
208         }
209     }
210 }