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