Merge "Cleanup Optional uses"
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / listeners / VtepConfigSchemaListener.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.genius.itm.listeners;
10
11 import com.google.common.base.Optional;
12 import org.apache.commons.lang3.StringUtils;
13 import org.apache.commons.net.util.SubnetUtils;
14 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
15 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
16 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.genius.itm.cli.TepCommandHelper;
20 import org.opendaylight.genius.itm.cli.TepException;
21 import org.opendaylight.genius.itm.globals.ITMConstants;
22 import org.opendaylight.genius.itm.impl.ItmUtils;
23 import org.opendaylight.genius.mdsalutil.AbstractDataChangeListener;
24 import org.opendaylight.genius.mdsalutil.MDSALUtil;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepConfigSchemas;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.SubnetsKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.Vteps;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.VtepsKey;
41 import org.opendaylight.yangtools.concepts.ListenerRegistration;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import java.math.BigInteger;
47 import java.util.ArrayList;
48 import java.util.List;
49
50 /**
51  * The listener class interested in processing data change on
52  * {@code VtepConfigSchema} objects.
53  *
54  * @see VtepConfigSchema
55  */
56 public class VtepConfigSchemaListener extends AbstractDataChangeListener<VtepConfigSchema> implements AutoCloseable {
57
58     /** The Constant LOG. */
59     private static final Logger LOG = LoggerFactory.getLogger(VtepConfigSchemaListener.class);
60
61     /** The listener registration. */
62     private ListenerRegistration<DataChangeListener> listenerRegistration;
63
64     /** The data broker. */
65     private final DataBroker dataBroker;
66
67     /**
68      * Instantiates a new vtep config schema listener.
69      *
70      * @param db
71      *            the db
72      */
73     public VtepConfigSchemaListener(final DataBroker db) {
74         super(VtepConfigSchema.class);
75         this.dataBroker = db;
76         registerListener(db);
77     }
78
79     /*
80      * (non-Javadoc)
81      *
82      * @see java.lang.AutoCloseable#close()
83      */
84     @Override
85     public void close() throws Exception {
86         if (this.listenerRegistration != null) {
87             try {
88                 this.listenerRegistration.close();
89             } catch (final Exception e) {
90                 LOG.error("Error when cleaning up DataChangeListener.", e);
91             }
92             this.listenerRegistration = null;
93         }
94         LOG.info("VtepConfigSchemaListener Closed");
95     }
96
97     /**
98      * Register listener.
99      *
100      * @param db
101      *            the db
102      */
103     private void registerListener(final DataBroker db) {
104         try {
105             this.listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
106                     getWildCardPath(), VtepConfigSchemaListener.this, AsyncDataBroker.DataChangeScope.SUBTREE);
107         } catch (final Exception e) {
108             LOG.error("VtepConfigSchemaListener DataChange listener registration fail!", e);
109             throw new IllegalStateException("VtepConfigSchemaListener registration Listener failed.", e);
110         }
111     }
112
113     /**
114      * Gets the wild card path.
115      *
116      * @return the wild card path
117      */
118     private InstanceIdentifier<VtepConfigSchema> getWildCardPath() {
119         return ItmUtils.getVtepConfigSchemaIdentifier();
120     }
121
122     /*
123      * (non-Javadoc)
124      *
125      * @see
126      * org.opendaylight.genius.mdsalutil.AbstractDataChangeListener#remove(
127      * org.opendaylight.yangtools.yang.binding.InstanceIdentifier,
128      * org.opendaylight.yangtools.yang.binding.DataObject)
129      */
130     @Override
131     protected void remove(InstanceIdentifier<VtepConfigSchema> identifier, VtepConfigSchema schema) {
132         LOG.trace("Received notification for VTEP config schema [{}] deleted.", schema.getSchemaName());
133         try {
134             List<BigInteger> lstDpnIds = ItmUtils.getDpnIdList(schema.getDpnIds());
135             if (lstDpnIds != null && !lstDpnIds.isEmpty()) {
136                 deleteVteps(schema, lstDpnIds);
137             }
138
139             // Delete IP pool corresponding to schema
140             // TODO: Ensure no schema exists with same subnet before deleting
141             String subnetCidr = ItmUtils.getSubnetCidrAsString(schema.getSubnet());
142             deleteVtepIpPool(subnetCidr);
143         } catch (Exception e) {
144             String error = "Failed to handle DCN for delete VtepConfigSchema: " + schema;
145             LOG.error(error, e);
146         }
147     }
148
149     /*
150      * (non-Javadoc)
151      *
152      * @see
153      * org.opendaylight.genius.mdsalutil.AbstractDataChangeListener#update(
154      * org.opendaylight.yangtools.yang.binding.InstanceIdentifier,
155      * org.opendaylight.yangtools.yang.binding.DataObject,
156      * org.opendaylight.yangtools.yang.binding.DataObject)
157      */
158     @Override
159     protected void update(InstanceIdentifier<VtepConfigSchema> identifier, VtepConfigSchema original,
160                           VtepConfigSchema updated) {
161         LOG.error("Receivedn DCN for updating VTEP Original schema: {}. Updated schema: {}",
162                 original, updated);
163         //LOG.trace("Received notification for VTEP config schema [{}] updated.", original.getSchemaName());
164
165         try {
166             VtepConfigSchema orignalSchema = ItmUtils.validateVtepConfigSchema(original);
167             VtepConfigSchema updatedSchema = ItmUtils.validateVtepConfigSchema(updated);
168
169             if (doesDeleteAndAddSchemaRequired(original, updated)) {
170                 LOG.error("Failed to handle DCN for updating VTEP schema {}. Original schema: {}. Updated schema: {}",
171                         original, updated);
172                 // TODO: handle updates
173                 return;
174             }
175
176             handleUpdateOfDpnIds(orignalSchema, updatedSchema);
177
178         } catch (Exception e) {
179             String error = "Failed to handle DCN for update VtepConfigSchema original:" +
180                     original + ", updated: " + updated;
181             LOG.error(error, e);
182         }
183     }
184
185     /*
186      * (non-Javadoc)
187      *
188      * @see
189      * org.opendaylight.genius.mdsalutil.AbstractDataChangeListener#add(org.
190      * opendaylight.yangtools.yang.binding.InstanceIdentifier,
191      * org.opendaylight.yangtools.yang.binding.DataObject)
192      */
193     @Override
194     protected void add(InstanceIdentifier<VtepConfigSchema> identifier, VtepConfigSchema schema) {
195         // Construct the transport zones from the provided schemas and push it
196         // to config DS.
197         LOG.trace("Add VtepConfigSchema: key: {} , value: {}", identifier, schema);
198
199         try {
200             VtepConfigSchema validatedSchema = ItmUtils.validateForAddVtepConfigSchema(schema,
201                     getAllVtepConfigSchemas());
202
203             VtepIpPool vtepIpPool = processAvailableIps(validatedSchema);
204             addVteps(validatedSchema, vtepIpPool);
205         } catch (Exception e) {
206             LOG.error("Failed to handle DCN for add VtepConfigSchema: {}", e);
207         }
208     }
209
210     /**
211      * Handle update of dpn ids.
212      *
213      * @param original
214      *            the original
215      * @param updated
216      *            the updated
217      */
218     private void handleUpdateOfDpnIds(VtepConfigSchema original, VtepConfigSchema updated) {
219         // Handling add/delete DPNs from schema
220         List<DpnIds> originalDpnIds = (original.getDpnIds() == null) ? new ArrayList<>()
221                 : original.getDpnIds();
222         List<DpnIds> updatedDpnIds = (updated.getDpnIds() == null) ? new ArrayList<>()
223                 : updated.getDpnIds();
224
225         handleDeletedDpnsFromSchema(original, originalDpnIds, updatedDpnIds);
226         handleNewlyAddedDpnsToSchema(original, originalDpnIds, updatedDpnIds);
227     }
228
229     /**
230      * Does delete and add schema required.
231      *
232      * @param original
233      *            the original
234      * @param updated
235      *            the updated
236      * @return true, if successful
237      */
238     private boolean doesDeleteAndAddSchemaRequired(VtepConfigSchema original, VtepConfigSchema updated) {
239         boolean delnAddRequired = false;
240         if (!StringUtils.equalsIgnoreCase(original.getPortName(), updated.getPortName())) {
241             delnAddRequired = true;
242         } else if (original.getVlanId() != updated.getVlanId()) {
243             delnAddRequired = true;
244         } else if (original.getSubnet() != null && !original.getSubnet().equals(updated.getSubnet())) {
245             delnAddRequired = true;
246         } else if (original.getGatewayIp() != null && !original.getGatewayIp().equals(updated.getGatewayIp())) {
247             delnAddRequired = true;
248         } else if (!StringUtils.equalsIgnoreCase(original.getTransportZoneName(), updated.getTransportZoneName())) {
249             delnAddRequired = true;
250         } else if (!(original.getTunnelType().equals(updated.getTunnelType()) )) {
251             delnAddRequired = true;
252         }
253         return delnAddRequired;
254     }
255
256     /**
257      * Handle newly added dpns to schema.
258      *
259      * @param original
260      *            the original
261      * @param originalDpnIds
262      *            the original dpn ids
263      * @param updatedDpnIds
264      *            the updated dpn ids
265      */
266     private void handleNewlyAddedDpnsToSchema(VtepConfigSchema original, List<DpnIds> originalDpnIds,
267                                               List<DpnIds> updatedDpnIds) {
268         LOG.trace("Handle Addition of DPNs from VTEP Original Dpn: {}. Updated Dpn: {}", originalDpnIds, updatedDpnIds) ;
269         ArrayList<DpnIds> newlyAddedDpns = new ArrayList<>(updatedDpnIds);
270         newlyAddedDpns.removeAll(originalDpnIds);
271         LOG.debug("Newly added DPNs {} to VTEP config schema [{}].", newlyAddedDpns, original.getSchemaName());
272         if (!newlyAddedDpns.isEmpty()) {
273             VtepConfigSchema diffSchema = new VtepConfigSchemaBuilder(original).setDpnIds(newlyAddedDpns).build();
274             String subnetCidr = ItmUtils.getSubnetCidrAsString(original.getSubnet());
275             VtepIpPool vtepIpPool = getVtepIpPool(subnetCidr);
276             LOG.debug("Adding of DPNs in Diff Schema: {}", diffSchema) ;
277             addVteps(diffSchema, vtepIpPool);
278         }
279     }
280
281     /**
282      * Handle deleted dpns from schema.
283      *
284      * @param original
285      *            the original
286      * @param originalDpnIds
287      *            the original dpn ids
288      * @param updatedDpnIds
289      *            the updated dpn ids
290      */
291     private void handleDeletedDpnsFromSchema(VtepConfigSchema original, List<DpnIds> originalDpnIds,
292                                              List<DpnIds> updatedDpnIds) {
293         ArrayList<DpnIds> deletedDpns = new ArrayList<>(originalDpnIds);
294         deletedDpns.removeAll(updatedDpnIds);
295         LOG.debug("DPNs to be removed DPNs {} from VTEP config schema [{}].", deletedDpns, original.getSchemaName());
296         if (!deletedDpns.isEmpty()) {
297             LOG.debug("Deleting of DPNs from VTEP Schema: {}. To be deleted Dpns: {}", original, deletedDpns) ;
298             deleteVteps(original, ItmUtils.getDpnIdList(deletedDpns));
299         }
300     }
301
302     /**
303      * Gets all vtep config schemas.
304      *
305      * @return the all vtep config schemas
306      */
307     private List<VtepConfigSchema> getAllVtepConfigSchemas() {
308         return ItmUtils.read(LogicalDatastoreType.CONFIGURATION, ItmUtils.getVtepConfigSchemasIdentifier(),
309                 this.dataBroker).transform(VtepConfigSchemas::getVtepConfigSchema).orNull();
310     }
311
312     /**
313      * Adds the vteps.
314      *
315      * @param schema
316      *            the schema
317      * @param vtepIpPool
318      *            the vtep ip pool
319      */
320     private void addVteps(VtepConfigSchema schema, VtepIpPool vtepIpPool) {
321         if (schema.getDpnIds() == null || schema.getDpnIds().isEmpty()) {
322             LOG.debug("DPN list is empty, skipping addVteps for schema: {}", schema);
323             return;
324         }
325
326         String subnetCidr = ItmUtils.getSubnetCidrAsString(schema.getSubnet());
327         if (vtepIpPool == null) {
328             LOG.error("VTEP config pool not found for subnetCidr {}. Failed to add VTEPs for schema {}", subnetCidr,
329                     schema);
330             return;
331         }
332         TepCommandHelper tepCommandHelper = new TepCommandHelper(this.dataBroker);
333         // Check this later
334         String tunType ;
335         Class<? extends TunnelTypeBase> tunnelType = schema.getTunnelType() ;
336         if( tunnelType.equals(TunnelTypeVxlan.class))
337             tunType = ITMConstants.TUNNEL_TYPE_VXLAN ;
338         else
339             tunType =  ITMConstants.TUNNEL_TYPE_GRE;
340         tepCommandHelper.configureTunnelType(schema.getTransportZoneName(),
341                 StringUtils.upperCase(tunType));
342
343         List<IpAddress> availableIps = vtepIpPool.getAvailableIpaddress();
344         List<IpAddress> newlyAllocatedIps = new ArrayList<>();
345         List<BigInteger> skippedDpnIds = new ArrayList<>();
346
347         String gatewayIp = handleGatewayIp(schema.getGatewayIp());
348         for (BigInteger dpnId : ItmUtils.getDpnIdList(schema.getDpnIds())) {
349             IpAddress ipAddress = getAnAvailableIP(availableIps);
350             if (ipAddress == null) {
351                 skippedDpnIds.add(dpnId);
352                 continue;
353             }
354             try {
355                 tepCommandHelper.createLocalCache(dpnId, schema.getPortName(), schema.getVlanId(),
356                         String.valueOf(ipAddress.getValue()), subnetCidr, gatewayIp, schema.getTransportZoneName(), null);
357             } catch (TepException e) {
358                 LOG.error(e.getMessage());
359             }
360             newlyAllocatedIps.add(ipAddress);
361         }
362         if (!skippedDpnIds.isEmpty()) {
363             LOG.error("No available IP addresses in the VTEP config pool {}, skipping VTEP configurations for DPN's {}",
364                     subnetCidr, skippedDpnIds);
365         }
366
367         if (!newlyAllocatedIps.isEmpty()) {
368             LOG.debug( "Delete OnCommit and buildTeps in NewlyAddedDpns");
369             tepCommandHelper.deleteOnCommit();
370             tepCommandHelper.buildTeps();
371             allocateIpAddresses(newlyAllocatedIps, vtepIpPool, subnetCidr);
372         }
373     }
374
375     /**
376      * Handle gateway ip.
377      *
378      * @param gatewayIp
379      *            the gateway ip
380      * @return the string
381      */
382     private String handleGatewayIp(IpAddress gatewayIp) {
383         String strGatewayIp = (gatewayIp == null) ? null : String.valueOf(gatewayIp.getValue());
384         if (StringUtils.isBlank(strGatewayIp) || StringUtils.equals(ITMConstants.DUMMY_IP_ADDRESS, strGatewayIp)) {
385             // To avoid a validation exception in TepCommandHelper
386             strGatewayIp = null;
387         }
388         return strGatewayIp;
389     }
390
391     /**
392      * Delete vteps.
393      *
394      * @param schema
395      *            the schema
396      * @param lstDpnIdsToBeDeleted
397      *            the dpn ids list to be deleted
398      */
399     private void deleteVteps(VtepConfigSchema schema, List<BigInteger> lstDpnIdsToBeDeleted) {
400         TepCommandHelper tepCommandHelper = new TepCommandHelper(this.dataBroker);
401         List<IpAddress> freeIps = new ArrayList<>();
402
403         String subnetCidr = ItmUtils.getSubnetCidrAsString(schema.getSubnet());
404         String gatewayIp = handleGatewayIp(schema.getGatewayIp());
405
406         for (BigInteger dpnId : lstDpnIdsToBeDeleted) {
407             VtepsKey vtepkey = new VtepsKey(dpnId, schema.getPortName());
408
409             InstanceIdentifier<Vteps> vpath = InstanceIdentifier.builder(TransportZones.class)
410                     .child(TransportZone.class, new TransportZoneKey(schema.getTransportZoneName()))
411                     .child(Subnets.class, new SubnetsKey(schema.getSubnet())).child(Vteps.class, vtepkey).build();
412
413             Vteps vtep = null;
414             Optional<Vteps> vtepOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, vpath, dataBroker);
415             if (vtepOptional.isPresent()) {
416                 vtep = vtepOptional.get();
417             } else {
418                 LOG.warn("VTEP doesn't exist for DPN [{}] and port [{}].", dpnId, schema.getPortName());
419                 continue;
420             }
421
422             IpAddress ipAddress = vtep.getIpAddress();
423             try {
424                 tepCommandHelper.deleteVtep(dpnId, vtep.getPortname(), schema.getVlanId(),
425                     String.valueOf(ipAddress.getValue()), subnetCidr, gatewayIp, schema.getTransportZoneName(), null);
426             } catch (TepException e) {
427                 LOG.error(e.getMessage());
428             }
429
430             freeIps.add(ipAddress);
431         }
432         LOG.debug( "Delete OnCommit in NewlyAddedDpns");
433         tepCommandHelper.deleteOnCommit();
434         deAllocateIpAddresses(freeIps, subnetCidr);
435     }
436
437     /**
438      * Calculate available IPs from the subnet mask specified in the schema.
439      * Pushes the available and allocated IP address to config DS.
440      *
441      * @param schema
442      *            the schema
443      */
444     private VtepIpPool processAvailableIps(final VtepConfigSchema schema) {
445         String subnetCidr = ItmUtils.getSubnetCidrAsString(schema.getSubnet());
446         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
447
448         List<IpAddress> availableIps = calculateAvailableIps(subnetUtils, schema.getExcludeIpFilter(),
449                 schema.getGatewayIp());
450         VtepIpPool vtepIpPool = new VtepIpPoolBuilder().setSubnetCidr(subnetCidr).setAvailableIpaddress(availableIps)
451                 .setAllocatedIpaddress(new ArrayList<>()).build();
452
453         MDSALUtil.syncWrite(this.dataBroker, LogicalDatastoreType.CONFIGURATION,
454                 ItmUtils.getVtepIpPoolIdentifier(subnetCidr), vtepIpPool);
455         LOG.info("Vtep IP Pool with key:{} added to config DS", subnetCidr);
456         return vtepIpPool;
457     }
458
459     /**
460      * Gets the vtep ip pool.
461      *
462      * @param subnetCidr
463      *            the subnet cidr
464      * @return the vtep ip pool
465      */
466     private VtepIpPool getVtepIpPool(final String subnetCidr) {
467         return ItmUtils.read(LogicalDatastoreType.CONFIGURATION, ItmUtils.getVtepIpPoolIdentifier(subnetCidr),
468                 this.dataBroker).orNull();
469     }
470
471     /**
472      * Delete vtep ip pool.
473      *
474      * @param subnetCidr
475      *            the subnet cidr
476      */
477     private void deleteVtepIpPool(final String subnetCidr) {
478         if (StringUtils.isNotBlank(subnetCidr)) {
479             MDSALUtil.syncDelete(this.dataBroker, LogicalDatastoreType.CONFIGURATION,
480                     ItmUtils.getVtepIpPoolIdentifier(subnetCidr));
481             LOG.debug("Deleted Vtep IP Pool with key:{}", subnetCidr);
482         }
483     }
484
485     /**
486      * Gets the an available ip.
487      *
488      * @param availableIps
489      *
490      * @return the an available ip
491      */
492     private IpAddress getAnAvailableIP(List<IpAddress> availableIps) {
493         // TODO: Sort IP Addresses, get the least value
494         IpAddress ipAddress = null;
495         if (availableIps != null && !availableIps.isEmpty()) {
496             ipAddress = availableIps.remove(0);
497         }
498         return ipAddress;
499     }
500
501     /**
502      * Allocate ip addresses.
503      *
504      * @param allocatedIps
505      *            the allocated ips
506      * @param vtepIpPool
507      *            the vtep ip pool
508      * @param subnetCidr
509      *            the subnet cidr
510      */
511     private void allocateIpAddresses(List<IpAddress> allocatedIps, VtepIpPool vtepIpPool, String subnetCidr) {
512         if (allocatedIps != null && !allocatedIps.isEmpty() && vtepIpPool != null) {
513             // Remove from the available IP address list and add to allocated IP
514             // address list.
515             VtepIpPoolBuilder builder = new VtepIpPoolBuilder(vtepIpPool);
516             if (builder.getAvailableIpaddress() != null) {
517                 builder.getAvailableIpaddress().removeAll(allocatedIps);
518             }
519             if (builder.getAllocatedIpaddress() == null) {
520                 builder.setAllocatedIpaddress(allocatedIps);
521             } else {
522                 builder.getAllocatedIpaddress().addAll(allocatedIps);
523             }
524
525             MDSALUtil.syncWrite(this.dataBroker, LogicalDatastoreType.CONFIGURATION,
526                     ItmUtils.getVtepIpPoolIdentifier(subnetCidr), builder.build());
527         }
528     }
529
530     /**
531      * De-allocate ip addresses.
532      *
533      * @param freeIps
534      *            the free ips
535      * @param subnetCidr
536      *            the subnet cidr
537      */
538     private void deAllocateIpAddresses(List<IpAddress> freeIps, String subnetCidr) {
539         VtepIpPool vtepIpPool = getVtepIpPool(subnetCidr);
540         if (freeIps != null && !freeIps.isEmpty() && vtepIpPool != null) {
541             // Remove from the allocated IP address list and add to available IP
542             // address list.
543             VtepIpPoolBuilder builder = new VtepIpPoolBuilder(vtepIpPool);
544             if (builder.getAllocatedIpaddress() != null) {
545                 builder.getAllocatedIpaddress().removeAll(freeIps);
546             }
547             if (builder.getAvailableIpaddress() == null) {
548                 builder.setAvailableIpaddress(freeIps);
549             } else {
550                 builder.getAvailableIpaddress().addAll(freeIps);
551             }
552
553             MDSALUtil.syncWrite(this.dataBroker, LogicalDatastoreType.CONFIGURATION,
554                     ItmUtils.getVtepIpPoolIdentifier(subnetCidr), builder.build());
555             LOG.debug("Vtep IP Pool with key:{} updated to config DS", subnetCidr);
556         }
557     }
558
559     /**
560      * Calculate available ips.
561      *
562      * @param subnetCidr
563      *            the subnet cidr
564      * @param excludeIpFilter
565      *            the exclude ip filter
566      * @param gatewayIp
567      *            the gateway IP
568      * @return the list
569      */
570     private List<IpAddress> calculateAvailableIps(SubnetUtils subnetUtils, String excludeIpFilter,
571                                                   IpAddress gatewayIp) {
572         List<IpAddress> lstAvailableIps = new ArrayList<>();
573         SubnetInfo subnetInfo = subnetUtils.getInfo();
574         String[] arrIpAddresses = subnetInfo.getAllAddresses();
575
576         for (String ipAddress : arrIpAddresses) {
577             lstAvailableIps.add(new IpAddress(ipAddress.toCharArray()));
578         }
579         lstAvailableIps.remove(gatewayIp);
580         lstAvailableIps.removeAll(ItmUtils.getExcludeIpAddresses(excludeIpFilter, subnetInfo));
581
582         return lstAvailableIps;
583     }
584 }