Send garp on floating ip
[netvirt.git] / vpnservice / vpnmanager / vpnmanager-impl / src / main / java / org / opendaylight / netvirt / vpnmanager / VpnUtil.java
1 /*
2  * Copyright (c) 2015 - 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.vpnmanager;
10
11 import java.math.BigInteger;
12 import java.net.InetAddress;
13 import java.util.*;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.Future;
16
17
18 import com.google.common.base.Optional;
19 import com.google.common.base.Preconditions;
20 import com.google.common.primitives.Ints;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
24
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
27 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
30 import org.opendaylight.genius.mdsalutil.MDSALUtil;
31 import org.opendaylight.genius.mdsalutil.NwConstants;
32 import org.opendaylight.netvirt.bgpmanager.api.IBgpManager;
33 import org.opendaylight.netvirt.fibmanager.api.RouteOrigin;
34 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronConstants;
35 import org.opendaylight.netvirt.vpnmanager.utilities.InterfaceUtils;
36 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.bgp.rev130715.bgp.neighbors.bgp.neighbor.peer.address.type.IpAddress;
37 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnAfConfig;
38 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces;
39 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
40 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
41 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey;
42 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
43 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceKey;
44 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceBuilder;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntryBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntryKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.*;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.adjacency.list.Adjacency;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.Adjacencies;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.AdjacenciesBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.VpnIds;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.VpnIdsBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.VpnIdsKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.PrefixesBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.PrefixesKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.router.interfaces.RouterInterfaceBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.router.interfaces.RouterInterface;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.router.interfaces.RouterInterfaceKey;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnList;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnListKey;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstanceBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.Vpn;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.VpnBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.VpnKey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.vpn.Extraroute;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.vpn.ExtrarouteBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroute.vpn.ExtrarouteKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExtRouters;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.RoutersKey;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.FibEntries;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTables;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesKey;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdPools;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPool;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.L3nexthop;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.VpnNexthops;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.VpnNexthopsKey;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NeutronVpnPortipPortData;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPort;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortBuilder;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortKey;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.InterVpnLinkStates;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.InterVpnLinks;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.link.states.InterVpnLinkState;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.link.states.InterVpnLinkStateKey;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.links.InterVpnLink;
118 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
119 import org.opendaylight.yangtools.yang.common.RpcResult;
120 import org.opendaylight.yangtools.yang.binding.DataObject;
121 import org.opendaylight.yangtools.yang.data.impl.schema.tree.SchemaValidationFailedException;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
124
125 public class VpnUtil {
126     private static final Logger LOG = LoggerFactory.getLogger(VpnUtil.class);
127     private static final int DEFAULT_PREFIX_LENGTH = 32;
128     private static final String PREFIX_SEPARATOR = "/";
129
130     static InstanceIdentifier<VpnInterface> getVpnInterfaceIdentifier(String vpnInterfaceName) {
131         return InstanceIdentifier.builder(VpnInterfaces.class)
132                 .child(VpnInterface.class, new VpnInterfaceKey(vpnInterfaceName)).build();
133     }
134
135     static InstanceIdentifier<VpnInstance> getVpnInstanceIdentifier(String vpnName) {
136         return InstanceIdentifier.builder(VpnInstances.class)
137                 .child(VpnInstance.class, new VpnInstanceKey(vpnName)).build();
138     }
139
140     static VpnInterface getVpnInterface(String intfName, String vpnName, Adjacencies aug, BigInteger dpnId, Boolean isSheduledForRemove) {
141         return new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(intfName)).setVpnInstanceName(vpnName).setDpnId(dpnId)
142                 .setScheduledForRemove(isSheduledForRemove).addAugmentation(Adjacencies.class, aug)
143                 .build();
144     }
145
146     static InstanceIdentifier<Prefixes> getPrefixToInterfaceIdentifier(long vpnId, String ipPrefix) {
147         return InstanceIdentifier.builder(PrefixToInterface.class)
148                 .child(VpnIds.class, new VpnIdsKey(vpnId)).child(Prefixes.class,
149                         new PrefixesKey(ipPrefix)).build();
150     }
151
152     static InstanceIdentifier<VpnIds> getPrefixToInterfaceIdentifier(long vpnId) {
153         return InstanceIdentifier.builder(PrefixToInterface.class)
154                 .child(VpnIds.class, new VpnIdsKey(vpnId)).build();
155     }
156
157     static VpnIds getPrefixToInterface(long vpnId) {
158         return new VpnIdsBuilder().setKey(new VpnIdsKey(vpnId)).setVpnId(vpnId).build();
159     }
160
161     static Prefixes getPrefixToInterface(BigInteger dpId, String vpnInterfaceName, String ipPrefix) {
162         return new PrefixesBuilder().setDpnId(dpId).setVpnInterfaceName(
163                 vpnInterfaceName).setIpAddress(ipPrefix).build();
164     }
165
166     static InstanceIdentifier<Extraroute> getVpnToExtrarouteIdentifier(String vrfId, String ipPrefix) {
167         return InstanceIdentifier.builder(VpnToExtraroute.class)
168                 .child(Vpn.class, new VpnKey(vrfId)).child(Extraroute.class,
169                         new ExtrarouteKey(ipPrefix)).build();
170     }
171
172     static InstanceIdentifier<Vpn> getVpnToExtrarouteIdentifier(String vrfId) {
173         return InstanceIdentifier.builder(VpnToExtraroute.class)
174                 .child(Vpn.class, new VpnKey(vrfId)).build();
175     }
176
177     static Vpn getVpnToExtraRoute(String vrfId) {
178         return new VpnBuilder().setKey(new VpnKey(vrfId)).setVrfId(vrfId).build();
179     }
180
181     /**
182      * Retrieves the Instance Identifier that points to an InterVpnLink object
183      * in MDSL
184      *
185      * @param vpnLinkName The name of the InterVpnLink
186      * @return The requested InstanceIdentifier
187      */
188     public static InstanceIdentifier<InterVpnLinkState> getInterVpnLinkStateIid(String vpnLinkName) {
189         return InstanceIdentifier.builder(InterVpnLinkStates.class).child(InterVpnLinkState.class, new InterVpnLinkStateKey(vpnLinkName)).build();
190     }
191
192     /**
193      * Get inter-VPN link state
194      *
195      * @param broker dataBroker service reference
196      * @param vpnLinkName The name of the InterVpnLink
197      * @return the object that contains the State of the specified InterVpnLink
198      */
199     public static InterVpnLinkState getInterVpnLinkState(DataBroker broker, String vpnLinkName) {
200         InstanceIdentifier<InterVpnLinkState> vpnLinkStateIid = VpnUtil.getInterVpnLinkStateIid(vpnLinkName);
201         Optional<InterVpnLinkState> vpnLinkState = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION,
202                 vpnLinkStateIid);
203         if (vpnLinkState.isPresent()) {
204             return vpnLinkState.get();
205         }
206         return null;
207     }
208
209     /**
210      * Get VRF table given a Route Distinguisher
211      *
212      * @param broker dataBroker service reference
213      * @param rd Route-Distinguisher
214      * @return VrfTables that holds the list of VrfEntries of the specified rd
215      */
216     public static VrfTables getVrfTable(DataBroker broker, String rd) {
217         InstanceIdentifier<VrfTables> id =
218                 InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build();
219         Optional<VrfTables> vrfTable = read(broker, LogicalDatastoreType.CONFIGURATION, id);
220         return vrfTable.isPresent() ? vrfTable.get() : null;
221     }
222
223     /**
224      * Retrieves the VrfEntries that belong to a given VPN filtered out by
225      * Origin, searching by its Route-Distinguisher
226      *
227      * @param broker dataBroker service reference
228      * @param rd     Route-distinguisher of the VPN
229      * @param originsToConsider Only entries whose origin is included in this
230      *     list will be considered
231      * @return the list of VrfEntries
232      */
233     public static List<VrfEntry> getVrfEntriesByOrigin(DataBroker broker, String rd,
234                                                        List<RouteOrigin> originsToConsider) {
235         List<VrfEntry> result = new ArrayList<VrfEntry>();
236         List<VrfEntry> allVpnVrfEntries = getAllVrfEntries(broker, rd);
237         for (VrfEntry vrfEntry : allVpnVrfEntries) {
238             if (originsToConsider.contains(RouteOrigin.value(vrfEntry.getOrigin()))) {
239                 result.add(vrfEntry);
240             }
241         }
242         return result;
243     }
244
245     static List<Prefixes> getAllPrefixesToInterface(DataBroker broker, long vpnId) {
246         Optional<VpnIds> vpnIds = read(broker, LogicalDatastoreType.OPERATIONAL, getPrefixToInterfaceIdentifier(vpnId));
247         if (vpnIds.isPresent()) {
248             return vpnIds.get().getPrefixes();
249         }
250         return new ArrayList<Prefixes>();
251     }
252
253     static List<Extraroute> getAllExtraRoutes(DataBroker broker, String vrfId) {
254         Optional<Vpn> extraRoutes = read(broker, LogicalDatastoreType.OPERATIONAL, getVpnToExtrarouteIdentifier(vrfId));
255         if (extraRoutes.isPresent()) {
256             return extraRoutes.get().getExtraroute();
257         }
258         return new ArrayList<Extraroute>();
259     }
260
261     /**
262      * Retrieves all the VrfEntries that belong to a given VPN searching by its
263      * Route-Distinguisher
264      *
265      * @param broker dataBroker service reference
266      * @param rd     Route-distinguisher of the VPN
267      * @return the list of VrfEntries
268      */
269     public static List<VrfEntry> getAllVrfEntries(DataBroker broker, String rd) {
270         VrfTables vrfTables = VpnUtil.getVrfTable(broker, rd);
271         return (vrfTables != null) ? vrfTables.getVrfEntry() : new ArrayList<VrfEntry>();
272     }
273
274     //FIXME: Implement caches for DS reads
275     static VpnInstance getVpnInstance(DataBroker broker, String vpnInstanceName) {
276         InstanceIdentifier<VpnInstance> id = InstanceIdentifier.builder(VpnInstances.class).child(VpnInstance.class,
277                 new VpnInstanceKey(vpnInstanceName)).build();
278         Optional<VpnInstance> vpnInstance = read(broker, LogicalDatastoreType.CONFIGURATION, id);
279         return (vpnInstance.isPresent()) ? vpnInstance.get() : null;
280     }
281
282     static List<VpnInstance> getAllVpnInstance(DataBroker broker) {
283         InstanceIdentifier<VpnInstances> id = InstanceIdentifier.builder(VpnInstances.class).build();
284         Optional<VpnInstances> optVpnInstances = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, id);
285         if (optVpnInstances.isPresent()) {
286             return optVpnInstances.get().getVpnInstance();
287         } else {
288             return new ArrayList<VpnInstance>();
289         }
290     }
291
292     static VrfEntry getVrfEntry(DataBroker broker, String rd, String ipPrefix) {
293
294         VrfTables vrfTable = getVrfTable(broker, rd);
295         // TODO: why check VrfTables if we later go for the specific VrfEntry?
296         if (vrfTable != null) {
297             InstanceIdentifier<VrfEntry> vrfEntryId =
298                     InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).
299                             child(VrfEntry.class, new VrfEntryKey(ipPrefix)).build();
300             Optional<VrfEntry> vrfEntry = read(broker, LogicalDatastoreType.CONFIGURATION, vrfEntryId);
301             if (vrfEntry.isPresent()) {
302                 return (vrfEntry.get());
303             }
304         }
305         return null;
306     }
307
308     static List<Adjacency> getAdjacenciesForVpnInterfaceFromConfig(DataBroker broker, String intfName) {
309         final InstanceIdentifier<VpnInterface> identifier = getVpnInterfaceIdentifier(intfName);
310         InstanceIdentifier<Adjacencies> path = identifier.augmentation(Adjacencies.class);
311         Optional<Adjacencies> adjacencies = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, path);
312
313         if (adjacencies.isPresent()) {
314             List<Adjacency> nextHops = adjacencies.get().getAdjacency();
315             return nextHops;
316         }
317         return null;
318     }
319
320     static Extraroute getVpnToExtraroute(String ipPrefix, List<String> nextHopList) {
321         return new ExtrarouteBuilder().setPrefix(ipPrefix).setNexthopIpList(nextHopList).build();
322     }
323
324     public static List<Extraroute> getVpnExtraroutes(DataBroker broker, String vpnRd) {
325         InstanceIdentifier<Vpn> vpnExtraRoutesId =
326                 InstanceIdentifier.builder(VpnToExtraroute.class).child(Vpn.class, new VpnKey(vpnRd)).build();
327         Optional<Vpn> vpnOpc = read(broker, LogicalDatastoreType.OPERATIONAL, vpnExtraRoutesId);
328         return vpnOpc.isPresent() ? vpnOpc.get().getExtraroute() : new ArrayList<Extraroute>();
329     }
330
331     static Adjacencies getVpnInterfaceAugmentation(List<Adjacency> nextHopList) {
332         return new AdjacenciesBuilder().setAdjacency(nextHopList).build();
333     }
334
335     public static InstanceIdentifier<IdPool> getPoolId(String poolName) {
336         InstanceIdentifier.InstanceIdentifierBuilder<IdPool> idBuilder =
337                 InstanceIdentifier.builder(IdPools.class).child(IdPool.class, new IdPoolKey(poolName));
338         InstanceIdentifier<IdPool> id = idBuilder.build();
339         return id;
340     }
341
342     static InstanceIdentifier<VpnInterfaces> getVpnInterfacesIdentifier() {
343         return InstanceIdentifier.builder(VpnInterfaces.class).build();
344     }
345
346     static InstanceIdentifier<Interface> getInterfaceIdentifier(String interfaceName) {
347         return InstanceIdentifier.builder(Interfaces.class)
348                 .child(Interface.class, new InterfaceKey(interfaceName)).build();
349     }
350
351     static InstanceIdentifier<VpnToDpnList> getVpnToDpnListIdentifier(String rd, BigInteger dpnId) {
352         return InstanceIdentifier.builder(VpnInstanceOpData.class)
353                 .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd))
354                 .child(VpnToDpnList.class, new VpnToDpnListKey(dpnId)).build();
355     }
356
357     public static BigInteger getCookieArpFlow(int interfaceTag) {
358         return VpnConstants.COOKIE_L3_BASE.add(new BigInteger("0110000", 16)).add(
359                 BigInteger.valueOf(interfaceTag));
360     }
361
362     public static BigInteger getCookieL3(int vpnId) {
363         return VpnConstants.COOKIE_L3_BASE.add(new BigInteger("0610000", 16)).add(BigInteger.valueOf(vpnId));
364     }
365
366     public static String getFlowRef(BigInteger dpnId, short tableId, int ethType, int lPortTag, int arpType) {
367         return new StringBuffer().append(VpnConstants.FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
368                 .append(tableId).append(NwConstants.FLOWID_SEPARATOR).append(ethType).append(lPortTag)
369                 .append(NwConstants.FLOWID_SEPARATOR).append(arpType).toString();
370     }
371
372     public static int getUniqueId(IdManagerService idManager, String poolName, String idKey) {
373         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
374
375         try {
376             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
377             RpcResult<AllocateIdOutput> rpcResult = result.get();
378             if (rpcResult.isSuccessful()) {
379                 return rpcResult.getResult().getIdValue().intValue();
380             } else {
381                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
382             }
383         } catch (InterruptedException | ExecutionException e) {
384             LOG.warn("Exception when getting Unique Id", e);
385         }
386         return 0;
387     }
388
389     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
390         ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
391         try {
392             Future<RpcResult<Void>> result = idManager.releaseId(idInput);
393             RpcResult<Void> rpcResult = result.get();
394             if (!rpcResult.isSuccessful()) {
395                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
396             }
397         } catch (InterruptedException | ExecutionException e) {
398             LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
399         }
400     }
401
402     public static String getNextHopLabelKey(String rd, String prefix) {
403         return rd + VpnConstants.SEPARATOR + prefix;
404     }
405
406     /**
407      * Retrieves the VpnInstance name (typically the VPN Uuid) out from the
408      * route-distinguisher
409      *
410      * @param broker dataBroker service reference
411      * @param rd Route-Distinguisher
412      * @return the VpnInstance name
413      */
414     public static String getVpnNameFromRd(DataBroker broker, String rd) {
415         VpnInstanceOpDataEntry vpnInstanceOpData = getVpnInstanceOpData(broker, rd);
416         return (vpnInstanceOpData != null) ? vpnInstanceOpData.getVpnInstanceName() : null;
417     }
418
419     /**
420      * Retrieves the dataplane identifier of a specific VPN, searching by its
421      * VpnInstance name.
422      *
423      * @param broker dataBroker service reference
424      * @param vpnName Name of the VPN
425      * @return the dataplane identifier of the VPN, the VrfTag.
426      */
427     public static long getVpnId(DataBroker broker, String vpnName) {
428
429         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> id
430                 = getVpnInstanceToVpnIdIdentifier(vpnName);
431         Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> vpnInstance
432                 = read(broker, LogicalDatastoreType.CONFIGURATION, id);
433
434         long vpnId = VpnConstants.INVALID_ID;
435         if (vpnInstance.isPresent()) {
436             vpnId = vpnInstance.get().getVpnId();
437         }
438         return vpnId;
439     }
440
441     /**
442      * Retrieves the VPN Route Distinguisher searching by its Vpn instance name
443      *
444      * @param broker dataBroker service reference
445      * @param vpnName Name of the VPN
446      * @return the route-distinguisher of the VPN
447      */
448     public static String getVpnRd(DataBroker broker, String vpnName) {
449         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> id
450                 = getVpnInstanceToVpnIdIdentifier(vpnName);
451         Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance> vpnInstance
452                 = read(broker, LogicalDatastoreType.CONFIGURATION, id);
453
454         String rd = null;
455         if (vpnInstance.isPresent()) {
456             rd = vpnInstance.get().getVrfId();
457         }
458         return rd;
459     }
460
461     /**
462      * Get VPN Route Distinguisher from VPN Instance Configuration
463      *
464      * @param broker dataBroker service reference
465      * @param vpnName Name of the VPN
466      * @return the route-distinguisher of the VPN
467      */
468     public static String getVpnRdFromVpnInstanceConfig(DataBroker broker, String vpnName) {
469         InstanceIdentifier<VpnInstance> id = InstanceIdentifier.builder(VpnInstances.class)
470                 .child(VpnInstance.class, new VpnInstanceKey(vpnName)).build();
471         Optional<VpnInstance> vpnInstance = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, id);
472         String rd = null;
473         if (vpnInstance.isPresent()) {
474             VpnInstance instance = vpnInstance.get();
475             VpnAfConfig config = instance.getIpv4Family();
476             rd = config.getRouteDistinguisher();
477         }
478         return rd;
479     }
480
481     /**
482      * Remove from MDSAL all those VrfEntries in a VPN that have an specific RouteOrigin
483      *
484      * @param broker dataBroker service reference
485      * @param rd     Route Distinguisher
486      * @param origin Origin of the Routes to be removed (see {@link RouteOrigin})
487      */
488     public static void removeVrfEntriesByOrigin(DataBroker broker, String rd, RouteOrigin origin) {
489         InstanceIdentifier<VrfTables> vpnVrfTableIid =
490                 InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build();
491         Optional<VrfTables> vrfTablesOpc = read(broker, LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid);
492         if (vrfTablesOpc.isPresent()) {
493             VrfTables vrfTables = vrfTablesOpc.get();
494             List<VrfEntry> newVrfEntries = new ArrayList<VrfEntry>();
495             for (VrfEntry vrfEntry : vrfTables.getVrfEntry()) {
496                 if (origin == RouteOrigin.value(vrfEntry.getOrigin())) {
497                     delete(broker, LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid.child(VrfEntry.class,
498                             vrfEntry.getKey()));
499                 }
500             }
501         }
502     }
503
504     public static void removeVrfEntriesByNexthop(DataBroker broker, String rd, String nexthop) {
505         InstanceIdentifier<VrfTables> vpnVrfTableIid =
506                 InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd)).build();
507         Optional<VrfTables> vrfTablesOpc = read(broker, LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid);
508         if (vrfTablesOpc.isPresent()) {
509             VrfTables vrfTables = vrfTablesOpc.get();
510             for (VrfEntry vrfEntry : vrfTables.getVrfEntry()) {
511                 if (vrfEntry.getNextHopAddressList() != null && vrfEntry.getNextHopAddressList().contains(nexthop)) {
512                     // TODO: Removes all the VrfEntry if one of the nexthops is the specified nexthop
513                     //                should we only remove the specific nexthop, or all the VrfEnry?
514                     delete(broker, LogicalDatastoreType.CONFIGURATION, vpnVrfTableIid.child(VrfEntry.class,
515                             vrfEntry.getKey()));
516                 }
517             }
518         }
519     }
520
521     static org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance
522                 getVpnInstanceToVpnId(String vpnName, long vpnId, String rd) {
523
524         return new VpnInstanceBuilder().setVpnId(vpnId).setVpnInstanceName(vpnName).setVrfId(rd).build();
525
526     }
527
528     static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance>
529                 getVpnInstanceToVpnIdIdentifier(String vpnName) {
530         return InstanceIdentifier.builder(VpnInstanceToVpnId.class)
531                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance.class,
532                         new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstanceKey(vpnName)).build();
533     }
534
535     static RouterInterface getConfiguredRouterInterface(DataBroker broker, String interfaceName) {
536         Optional<RouterInterface> optRouterInterface = read(broker, LogicalDatastoreType.CONFIGURATION, VpnUtil.getRouterInterfaceId(interfaceName));
537         if(optRouterInterface.isPresent()) {
538             return optRouterInterface.get();
539         }
540         return null;
541     }
542
543     static org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds
544                 getVpnIdToVpnInstance(long vpnId, String vpnName, String rd, boolean isExternalVpn) {
545         return new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIdsBuilder()
546                 .setVpnId(vpnId).setVpnInstanceName(vpnName).setVrfId(rd).setExternalVpn(isExternalVpn).build();
547
548     }
549
550     static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds>
551         getVpnIdToVpnInstanceIdentifier(long vpnId) {
552         return InstanceIdentifier.builder(VpnIdToVpnInstance.class)
553                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds.class,
554                         new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIdsKey(Long.valueOf(vpnId))).build();
555     }
556
557     /**
558      * Retrieves the Vpn Name searching by its VPN Tag.
559      *
560      * @param broker dataBroker service reference
561      * @param vpnId Dataplane identifier of the VPN
562      * @return the Vpn instance name
563      */
564     public static String getVpnName(DataBroker broker, long vpnId) {
565
566         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> id
567                 = getVpnIdToVpnInstanceIdentifier(vpnId);
568         Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.id.to.vpn.instance.VpnIds> vpnInstance
569                 = read(broker, LogicalDatastoreType.CONFIGURATION, id);
570
571         String vpnName = null;
572         if (vpnInstance.isPresent()) {
573             vpnName = vpnInstance.get().getVpnInstanceName();
574         }
575         return vpnName;
576     }
577
578     public static InstanceIdentifier<VpnInstanceOpDataEntry> getVpnInstanceOpDataIdentifier(String rd) {
579         return InstanceIdentifier.builder(VpnInstanceOpData.class)
580                 .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd)).build();
581     }
582
583     static VpnInstanceOpDataEntry getVpnInstanceOpDataBuilder(String rd, long vpnId, String vpnName) {
584         return new VpnInstanceOpDataEntryBuilder().setVrfId(rd).setVpnId(vpnId).setVpnInstanceName(vpnName).build();
585     }
586
587     static VpnInstanceOpDataEntry updateIntfCntInVpnInstOpData(Long newCount, String vrfId) {
588         return new VpnInstanceOpDataEntryBuilder().setVpnInterfaceCount(newCount).setVrfId(vrfId).build();
589     }
590
591     static InstanceIdentifier<RouterInterface> getRouterInterfaceId(String interfaceName) {
592         return InstanceIdentifier.builder(RouterInterfaces.class)
593                 .child(RouterInterface.class, new RouterInterfaceKey(interfaceName)).build();
594     }
595
596     static RouterInterface getRouterInterface(String interfaceName, String routerName) {
597         return new RouterInterfaceBuilder().setKey(new RouterInterfaceKey(interfaceName))
598                 .setInterfaceName(interfaceName).setRouterName(routerName).build();
599     }
600
601     static VpnInstanceOpDataEntry getVpnInstanceOpData(DataBroker broker, String rd) {
602         InstanceIdentifier<VpnInstanceOpDataEntry> id = VpnUtil.getVpnInstanceOpDataIdentifier(rd);
603         Optional<VpnInstanceOpDataEntry> vpnInstanceOpData = read(broker, LogicalDatastoreType.OPERATIONAL, id);
604         if (vpnInstanceOpData.isPresent()) {
605             return vpnInstanceOpData.get();
606         }
607         return null;
608     }
609
610     static VpnInterface getConfiguredVpnInterface(DataBroker broker, String interfaceName) {
611         InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName);
612         Optional<VpnInterface> configuredVpnInterface = read(broker, LogicalDatastoreType.CONFIGURATION, interfaceId);
613
614         if (configuredVpnInterface.isPresent()) {
615             return configuredVpnInterface.get();
616         }
617         return null;
618     }
619
620     static VpnInterface getOperationalVpnInterface(DataBroker broker, String interfaceName) {
621         InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName);
622         Optional<VpnInterface> operationalVpnInterface = read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
623
624         if (operationalVpnInterface.isPresent()) {
625             return operationalVpnInterface.get();
626         }
627         return null;
628     }
629
630     static boolean isVpnInterfaceConfigured(DataBroker broker, String interfaceName) {
631         InstanceIdentifier<VpnInterface> interfaceId = getVpnInterfaceIdentifier(interfaceName);
632         Optional<VpnInterface> configuredVpnInterface = read(broker, LogicalDatastoreType.CONFIGURATION, interfaceId);
633
634         if (configuredVpnInterface.isPresent()) {
635             return true;
636         }
637         return false;
638     }
639
640     static String getIpPrefix(String prefix) {
641         String prefixValues[] = prefix.split("/");
642         if (prefixValues.length == 1) {
643             prefix = prefix + PREFIX_SEPARATOR + DEFAULT_PREFIX_LENGTH;
644         }
645         return prefix;
646     }
647
648     static final FutureCallback<Void> DEFAULT_CALLBACK =
649             new FutureCallback<Void>() {
650                 @Override
651                 public void onSuccess(Void result) {
652                     LOG.debug("Success in Datastore operation");
653                 }
654
655                 @Override
656                 public void onFailure(Throwable error) {
657                     LOG.error("Error in Datastore operation", error);
658                 }
659
660                 ;
661             };
662
663     public static <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
664                                                           InstanceIdentifier<T> path) {
665
666         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
667
668         Optional<T> result = Optional.absent();
669         try {
670             result = tx.read(datastoreType, path).get();
671         } catch (Exception e) {
672             throw new RuntimeException(e);
673         } finally {
674             tx.close();
675         }
676
677         return result;
678     }
679
680     public static <T extends DataObject> void asyncUpdate(DataBroker broker, LogicalDatastoreType datastoreType,
681                                                           InstanceIdentifier<T> path, T data) {
682         asyncUpdate(broker, datastoreType, path, data, DEFAULT_CALLBACK);
683     }
684
685     public static <T extends DataObject> void asyncUpdate(DataBroker broker, LogicalDatastoreType datastoreType,
686                                                           InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
687         WriteTransaction tx = broker.newWriteOnlyTransaction();
688         tx.merge(datastoreType, path, data, true);
689         Futures.addCallback(tx.submit(), callback);
690     }
691
692     public static <T extends DataObject> void asyncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
693                                                          InstanceIdentifier<T> path, T data) {
694         asyncWrite(broker, datastoreType, path, data, DEFAULT_CALLBACK);
695     }
696
697     public static <T extends DataObject> void asyncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
698                                                          InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
699         WriteTransaction tx = broker.newWriteOnlyTransaction();
700         tx.put(datastoreType, path, data, true);
701         Futures.addCallback(tx.submit(), callback);
702     }
703
704     public static <T extends DataObject> void tryDelete(DataBroker broker, LogicalDatastoreType datastoreType,
705                                                      InstanceIdentifier<T> path) {
706         try {
707             delete(broker, datastoreType, path, DEFAULT_CALLBACK);
708         } catch ( SchemaValidationFailedException sve ) {
709             LOG.info("Could not delete {}. SchemaValidationFailedException: {}", path, sve.getMessage());
710         } catch ( Exception e) {
711             LOG.info("Could not delete {}. Unhandled error: {}", path, e.getMessage());
712         }
713     }
714
715     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
716                                                      InstanceIdentifier<T> path) {
717         delete(broker, datastoreType, path, DEFAULT_CALLBACK);
718     }
719
720
721     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
722                                                      InstanceIdentifier<T> path, FutureCallback<Void> callback) {
723         WriteTransaction tx = broker.newWriteOnlyTransaction();
724         tx.delete(datastoreType, path);
725         Futures.addCallback(tx.submit(), callback);
726     }
727
728     public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
729                                                         InstanceIdentifier<T> path, T data) {
730         WriteTransaction tx = broker.newWriteOnlyTransaction();
731         tx.put(datastoreType, path, data, true);
732         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
733         try {
734             futures.get();
735         } catch (InterruptedException | ExecutionException e) {
736             LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data);
737             throw new RuntimeException(e.getMessage());
738         }
739     }
740
741     public static <T extends DataObject> void syncUpdate(DataBroker broker, LogicalDatastoreType datastoreType,
742                                                          InstanceIdentifier<T> path, T data) {
743         WriteTransaction tx = broker.newWriteOnlyTransaction();
744         tx.merge(datastoreType, path, data, true);
745         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
746         try {
747             futures.get();
748         } catch (InterruptedException | ExecutionException e) {
749             LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data);
750             throw new RuntimeException(e.getMessage());
751         }
752     }
753
754     public static long getRemoteBCGroup(long elanTag) {
755         return VpnConstants.ELAN_GID_MIN + ((elanTag % VpnConstants.ELAN_GID_MIN) * 2);
756     }
757
758     // interface-index-tag operational container
759     public static IfIndexInterface getInterfaceInfoByInterfaceTag(DataBroker broker, long interfaceTag) {
760         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
761         Optional<IfIndexInterface> existingInterfaceInfo = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
762         if (existingInterfaceInfo.isPresent()) {
763             return existingInterfaceInfo.get();
764         }
765         return null;
766     }
767
768     private static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
769         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class).child(IfIndexInterface.class,
770                 new IfIndexInterfaceKey((int) interfaceTag)).build();
771     }
772
773     public static ElanTagName getElanInfoByElanTag(DataBroker broker, long elanTag) {
774         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
775         Optional<ElanTagName> existingElanInfo = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanId);
776         if (existingElanInfo.isPresent()) {
777             return existingElanInfo.get();
778         }
779         return null;
780     }
781
782     private static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
783         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class,
784                 new ElanTagNameKey(elanTag)).build();
785     }
786
787
788     // TODO: Move this to NwUtil
789     public static boolean isIpInSubnet(int ipAddress, String subnetCidr) {
790         String[] subSplit = subnetCidr.split("/");
791         if (subSplit.length < 2) {
792             return false;
793         }
794
795         String subnetStr = subSplit[0];
796         int subnet = 0;
797         try {
798             InetAddress subnetAddress = InetAddress.getByName(subnetStr);
799             subnet = Ints.fromByteArray(subnetAddress.getAddress());
800         } catch (Exception ex) {
801             LOG.error("Passed in Subnet IP string not convertible to InetAdddress " + subnetStr);
802             return false;
803         }
804         int prefixLength = Integer.valueOf(subSplit[1]);
805         int mask = -1 << (32 - prefixLength);
806         if ((subnet & mask) == (ipAddress & mask)) {
807             return true;
808         }
809         return false;
810     }
811
812     /**
813      * Returns the Path identifier to reach a specific interface in a specific DPN in a given VpnInstance
814      *
815      * @param vpnRd     Route-Distinguisher of the VpnInstance
816      * @param dpnId     Id of the DPN where the interface is
817      * @param ifaceName Interface name
818      * @return the Instance Identifier
819      */
820     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
821             .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces>
822     getVpnToDpnInterfacePath(String vpnRd, BigInteger dpnId, String ifaceName) {
823
824         return
825                 InstanceIdentifier.builder(VpnInstanceOpData.class)
826                         .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(vpnRd))
827                         .child(VpnToDpnList.class, new VpnToDpnListKey(dpnId))
828                         .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
829                                 .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces.class,
830                                 new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
831                                         .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfacesKey(ifaceName))
832                         .build();
833     }
834
835     /**
836      * Includes a DPN with the corresponding interface names in the VpnToDpn operational data.
837      * This method is preferably over mergeDpnInVpnToDpnMap(DataBroker, String, String, BigInteger, List)
838      * when there are several DPNs to be merged since it saves some readings from MDSAL.
839      *
840      * @param broker     dataBroker service reference
841      * @param vpnOpData  Reference to the object that holds the Operational data of the VpnInstance
842      * @param dpnId      Id of the DPN where the interfaces to be added to Operational data are located
843      * @param ifaceNames List of interface names
844      */
845     public static void mergeDpnInVpnToDpnMap(DataBroker broker, VpnInstanceOpDataEntry vpnOpData, BigInteger dpnId,
846                                              List<String> ifaceNames) {
847         Preconditions.checkNotNull(vpnOpData);
848         Preconditions.checkNotNull(ifaceNames);
849
850         for (String ifaceName : ifaceNames) {
851             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
852                     .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces> vpnDpnIfaceIid =
853                     getVpnToDpnInterfacePath(vpnOpData.getKey().getVrfId(), dpnId, ifaceName);
854
855             org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
856                     .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfaces vpnDpnIface =
857                     new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
858                             .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list
859                             .VpnInterfacesBuilder().setKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
860                             .instance.op.data.vpn.instance.op.data.entry.vpn.to.dpn.list.VpnInterfacesKey(ifaceName))
861                             .setInterfaceName(ifaceName)
862                             .build();
863
864             syncUpdate(broker, LogicalDatastoreType.OPERATIONAL, vpnDpnIfaceIid, vpnDpnIface);
865         }
866     }
867
868     /**
869      * Includes a DPN with the corresponding interface names in the VpnToDpn operational data.
870      *
871      * @param broker dataBroker service reference
872      * @param vpnName Name of the VPN
873      * @param rd Route-Distinguisher
874      * @param dpnId Id of the DPN that includes the list of Ifaces to be
875      *           included in the Map
876      * @param ifaceNames List of interfaces to be included in the Map
877      */
878     public static void mergeDpnInVpnToDpnMap(DataBroker broker, String vpnName, String rd, BigInteger dpnId,
879                                              List<String> ifaceNames) {
880         InstanceIdentifier<VpnInstanceOpDataEntry> id = InstanceIdentifier.builder(VpnInstanceOpData.class)
881                 .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(vpnName))
882                 .build();
883
884         Optional<VpnInstanceOpDataEntry> vpnInstanceOpData =
885             MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, id);
886         if (vpnInstanceOpData.isPresent()) {
887             mergeDpnInVpnToDpnMap(broker, vpnInstanceOpData.get(), dpnId, ifaceNames);
888         }
889     }
890
891     /**
892      * Removes a specific interface from the VpnToDpn operative map.
893      *
894      * @param broker    dataBroker service reference
895      * @param rd        Route-distinguisher of the VPN
896      * @param dpnId     Id of the DPN where the interface is
897      * @param ifaceName interface name.
898      */
899     public static void removeIfaceFromVpnToDpnMap(DataBroker broker, String rd, BigInteger dpnId, String ifaceName) {
900         tryDelete(broker, LogicalDatastoreType.CONFIGURATION, getVpnToDpnInterfacePath(rd, dpnId, ifaceName));
901         // Note: tryDelete is a best-effort. Sometimes we want to update the VpnToDpnMap ifaces when the
902         // DPN has gone down (and the VpnToDpnMap has been removed in a different Thread)
903     }
904
905     public static void removePrefixToInterfaceForVpnId(DataBroker broker, long vpnId, WriteTransaction writeTxn) {
906         try {
907             // Clean up PrefixToInterface Operational DS
908             if (writeTxn != null) {
909                 writeTxn.delete(LogicalDatastoreType.OPERATIONAL,
910                         InstanceIdentifier.builder(PrefixToInterface.class).child(
911                                 VpnIds.class, new VpnIdsKey(vpnId)).build());
912             } else {
913                 delete(broker, LogicalDatastoreType.OPERATIONAL,
914                         InstanceIdentifier.builder(PrefixToInterface.class).child(VpnIds.class, new VpnIdsKey(vpnId)).build(),
915                         DEFAULT_CALLBACK);
916             }
917         } catch (Exception e) {
918             LOG.error("Exception during cleanup of PrefixToInterface for VPN ID {}", vpnId, e);
919         }
920     }
921
922     public static void removeVpnExtraRouteForVpn(DataBroker broker, String vpnName, WriteTransaction writeTxn) {
923         try {
924             // Clean up VPNExtraRoutes Operational DS
925             if (writeTxn != null) {
926                 writeTxn.delete(LogicalDatastoreType.OPERATIONAL,
927                         InstanceIdentifier.builder(VpnToExtraroute.class).child(Vpn.class, new VpnKey(vpnName)).build());
928             } else {
929                 delete(broker, LogicalDatastoreType.OPERATIONAL,
930                         InstanceIdentifier.builder(VpnToExtraroute.class).child(Vpn.class, new VpnKey(vpnName)).build(),
931                         DEFAULT_CALLBACK);
932             }
933         } catch (Exception e) {
934             LOG.error("Exception during cleanup of VPNToExtraRoute for VPN {}", vpnName, e);
935         }
936     }
937
938     public static void removeVpnOpInstance(DataBroker broker, String vpnName, WriteTransaction writeTxn) {
939         try {
940             // Clean up VPNInstanceOpDataEntry
941             if (writeTxn != null) {
942                 writeTxn.delete(LogicalDatastoreType.OPERATIONAL, getVpnInstanceOpDataIdentifier(vpnName));
943             } else {
944                 delete(broker, LogicalDatastoreType.OPERATIONAL, getVpnInstanceOpDataIdentifier(vpnName),
945                         DEFAULT_CALLBACK);
946             }
947         } catch (Exception e) {
948             LOG.error("Exception during cleanup of VPNInstanceOpDataEntry for VPN {}", vpnName, e);
949         }
950     }
951
952     public static void removeVpnInstanceToVpnId(DataBroker broker, String vpnName, WriteTransaction writeTxn) {
953         try {
954             if (writeTxn != null) {
955                 writeTxn.delete(LogicalDatastoreType.CONFIGURATION, getVpnInstanceToVpnIdIdentifier(vpnName));
956             } else {
957                 delete(broker, LogicalDatastoreType.CONFIGURATION, getVpnInstanceToVpnIdIdentifier(vpnName),
958                         DEFAULT_CALLBACK);
959             }
960         } catch (Exception e) {
961             LOG.error("Exception during clean up of VpnInstanceToVpnId for VPN {}", vpnName, e);
962         }
963     }
964
965     public static void removeVpnIdToVpnInstance(DataBroker broker, long vpnId, WriteTransaction writeTxn) {
966         try {
967             if (writeTxn != null) {
968                 writeTxn.delete(LogicalDatastoreType.CONFIGURATION, getVpnIdToVpnInstanceIdentifier(vpnId));
969             } else {
970                 delete(broker, LogicalDatastoreType.CONFIGURATION, getVpnIdToVpnInstanceIdentifier(vpnId),
971                         DEFAULT_CALLBACK);
972             }
973         } catch (Exception e) {
974             LOG.error("Exception during clean up of VpnIdToVpnInstance for VPNID {}", vpnId, e);
975         }
976     }
977
978     public static void removeVrfTableForVpn(DataBroker broker, String vpnName, WriteTransaction writeTxn) {
979         // Clean up FIB Entries Config DS
980         try {
981             if (writeTxn != null) {
982                 writeTxn.delete(LogicalDatastoreType.CONFIGURATION,
983                         InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(vpnName)).build());
984             } else {
985                 delete(broker, LogicalDatastoreType.CONFIGURATION,
986                         InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(vpnName)).build(),
987                         DEFAULT_CALLBACK);
988             }
989         } catch (Exception e) {
990             LOG.error("Exception during clean up of VrfTable from FIB for VPN {}", vpnName, e);
991         }
992     }
993
994     public static void removeL3nexthopForVpnId(DataBroker broker, long vpnId, WriteTransaction writeTxn) {
995         try {
996             // Clean up L3NextHop Operational DS
997             if (writeTxn != null) {
998                 writeTxn.delete(LogicalDatastoreType.OPERATIONAL,
999                         InstanceIdentifier.builder(L3nexthop.class).child(VpnNexthops.class, new VpnNexthopsKey(vpnId)).build());
1000             } else {
1001                 delete(broker, LogicalDatastoreType.OPERATIONAL,
1002                         InstanceIdentifier.builder(L3nexthop.class).child(VpnNexthops.class, new VpnNexthopsKey(vpnId)).build(),
1003                         DEFAULT_CALLBACK);
1004             }
1005         } catch (Exception e) {
1006             LOG.error("Exception during cleanup of L3NextHop for VPN ID {}", vpnId, e);
1007         }
1008     }
1009
1010     /**
1011      * Retrieves all configured InterVpnLinks
1012      *
1013      * @param broker dataBroker service reference
1014      * @return the list of InterVpnLinks
1015      */
1016     public static List<InterVpnLink> getAllInterVpnLinks(DataBroker broker) {
1017         InstanceIdentifier<InterVpnLinks> interVpnLinksIid = InstanceIdentifier.builder(InterVpnLinks.class).build();
1018
1019         Optional<InterVpnLinks> interVpnLinksOpData = MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION,
1020                 interVpnLinksIid);
1021
1022         return (interVpnLinksOpData.isPresent()) ? interVpnLinksOpData.get().getInterVpnLink()
1023                 : new ArrayList<InterVpnLink>();
1024     }
1025
1026     /**
1027      * Retrieves the list of DPNs where the endpoint of a VPN in an InterVPNLink was instantiated
1028      *
1029      * @param broker dataBroker service reference
1030      * @param vpnLinkName the name of the InterVpnLink
1031      * @param vpnUuid UUID of the VPN whose endpoint to be checked
1032      * @return the list of DPN Ids
1033      */
1034     public static List<BigInteger> getVpnLinkEndpointDPNs(DataBroker broker, String vpnLinkName, String vpnUuid) {
1035         InterVpnLinkState interVpnLinkState = getInterVpnLinkState(broker, vpnLinkName);
1036         if (interVpnLinkState.getFirstEndpointState().getVpnUuid().getValue().equals(vpnUuid)) {
1037             return interVpnLinkState.getFirstEndpointState().getDpId();
1038         } else {
1039             return interVpnLinkState.getSecondEndpointState().getDpId();
1040         }
1041     }
1042
1043     /**
1044      * Retrieves an InterVpnLink by searching by one of its endpoint's IP.
1045      *
1046      * @param broker dataBroker service reference
1047      * @param endpointIp IP to serch for.
1048      * @return the InterVpnLink or null if no InterVpnLink can be found
1049      */
1050     public static InterVpnLink getInterVpnLinkByEndpointIp(DataBroker broker, String endpointIp) {
1051         List<InterVpnLink> allInterVpnLinks = getAllInterVpnLinks(broker);
1052         for (InterVpnLink interVpnLink : allInterVpnLinks) {
1053             if (interVpnLink.getFirstEndpoint().getIpAddress().getValue().equals(endpointIp)
1054                     || interVpnLink.getSecondEndpoint().getIpAddress().getValue().equals(endpointIp)) {
1055                 return interVpnLink;
1056             }
1057         }
1058         return null;
1059     }
1060
1061     /**
1062      * Retrieves the InterVpnLink that has one of its 2 endpoints installed in
1063      * the specified DpnId
1064      *
1065      * @param broker dataBroker service reference
1066      * @param dpnId Id of the DPN
1067      * @return The InterVpnLink object if found, Optional.absent() otherwise
1068      */
1069     public static Optional<InterVpnLink> getInterVpnLinkByDpnId(DataBroker broker, BigInteger dpnId) {
1070         List<InterVpnLink> allInterVpnLinks = getAllInterVpnLinks(broker);
1071         for (InterVpnLink interVpnLink : allInterVpnLinks) {
1072             InterVpnLinkState interVpnLinkState = getInterVpnLinkState(broker, interVpnLink.getName());
1073             if ( ( interVpnLinkState != null )
1074                  && ( interVpnLinkState.getFirstEndpointState().getDpId().contains(dpnId)
1075                       || interVpnLinkState.getSecondEndpointState().getDpId().contains(dpnId) ) ) {
1076                 return Optional.fromNullable(interVpnLink);
1077             }
1078         }
1079         return Optional.absent();
1080     }
1081
1082     /**
1083      * Leaks a route from one VPN to another. By default, the origin for this leaked route is INTERVPN
1084      *
1085      * @param broker           dataBroker service reference
1086      * @param bgpManager       Used to advertise routes to the BGP Router
1087      * @param interVpnLink     Reference to the object that holds the info about the link between the 2 VPNs
1088      * @param srcVpnUuid       UUID of the VPN that has the route that is going to be leaked to the other VPN
1089      * @param dstVpnUuid       UUID of the VPN that is going to receive the route
1090      * @param prefix           Prefix of the route
1091      * @param label            Label of the route in the original VPN
1092      */
1093     public static void leakRoute(DataBroker broker, IBgpManager bgpManager, InterVpnLink interVpnLink,
1094                                  String srcVpnUuid, String dstVpnUuid, String prefix, Long label) {
1095         leakRoute(broker, bgpManager, interVpnLink, srcVpnUuid, dstVpnUuid, prefix, label, RouteOrigin.INTERVPN);
1096     }
1097
1098     /**
1099      * Leaks a route from one VPN to another.
1100      *
1101      * @param broker           dataBroker service reference
1102      * @param bgpManager       Used to advertise routes to the BGP Router
1103      * @param interVpnLink     Reference to the object that holds the info about the link between the 2 VPNs
1104      * @param srcVpnUuid       UUID of the VPN that has the route that is going to be leaked to the other VPN
1105      * @param dstVpnUuid       UUID of the VPN that is going to receive the route
1106      * @param prefix           Prefix of the route
1107      * @param label            Label of the route in the original VPN
1108      * @param forcedOrigin     By default, origin for leaked routes should be INTERVPN, however it is possible to
1109      *                         provide a different origin if desired.
1110      */
1111     public static void leakRoute(DataBroker broker, IBgpManager bgpManager, InterVpnLink interVpnLink,
1112                                  String srcVpnUuid, String dstVpnUuid, String prefix, Long label,
1113                                  RouteOrigin forcedOrigin) {
1114         Preconditions.checkNotNull(interVpnLink);
1115
1116         // The source VPN must participate in the InterVpnLink
1117         Preconditions.checkArgument(interVpnLink.getFirstEndpoint().getVpnUuid().getValue().equals(srcVpnUuid)
1118                         || interVpnLink.getSecondEndpoint().getVpnUuid().getValue().equals(srcVpnUuid),
1119                 "The source VPN {} does not participate in the interVpnLink {}",
1120                 srcVpnUuid, interVpnLink.getName());
1121         // The destination VPN must participate in the InterVpnLink
1122         Preconditions.checkArgument(interVpnLink.getFirstEndpoint().getVpnUuid().getValue().equals(dstVpnUuid)
1123                         || interVpnLink.getSecondEndpoint().getVpnUuid().getValue().equals(dstVpnUuid),
1124                 "The destination VPN {} does not participate in the interVpnLink {}",
1125                 dstVpnUuid, interVpnLink.getName());
1126
1127         boolean destinationIs1stEndpoint = interVpnLink.getFirstEndpoint().getVpnUuid().getValue().equals(dstVpnUuid);
1128
1129         String endpointIp = (destinationIs1stEndpoint) ? interVpnLink.getSecondEndpoint().getIpAddress().getValue()
1130                 : interVpnLink.getFirstEndpoint().getIpAddress().getValue();
1131
1132         VrfEntry newVrfEntry = new VrfEntryBuilder().setKey(new VrfEntryKey(prefix)).setDestPrefix(prefix)
1133                 .setLabel(label).setNextHopAddressList(Arrays.asList(endpointIp))
1134                 .setOrigin(RouteOrigin.INTERVPN.getValue())
1135                 .build();
1136
1137         String dstVpnRd = getVpnRd(broker, dstVpnUuid);
1138         InstanceIdentifier<VrfEntry> newVrfEntryIid =
1139                 InstanceIdentifier.builder(FibEntries.class)
1140                         .child(VrfTables.class, new VrfTablesKey(dstVpnRd))
1141                         .child(VrfEntry.class, new VrfEntryKey(newVrfEntry.getDestPrefix()))
1142                         .build();
1143         asyncWrite(broker, LogicalDatastoreType.CONFIGURATION, newVrfEntryIid, newVrfEntry);
1144
1145         // Finally, route is advertised it to the DC-GW. But while in the FibEntries the nexthop is the other
1146         // endpoint's IP, in the DC-GW the nexthop for those prefixes are the IPs of those DPNs where the target
1147         // VPN has been instantiated
1148         List<String> ecmpNexthops = new ArrayList<String>();
1149         InterVpnLinkState vpnLinkState = getInterVpnLinkState(broker, interVpnLink.getName());
1150         List<BigInteger> dpnIdList = (destinationIs1stEndpoint) ? vpnLinkState.getFirstEndpointState().getDpId()
1151                 : vpnLinkState.getSecondEndpointState().getDpId();
1152         List<String> nexthops = new ArrayList<String>();
1153         for (BigInteger dpnId : dpnIdList) {
1154             nexthops.add(InterfaceUtils.getEndpointIpAddressForDPN(broker, dpnId));
1155         }
1156         try {
1157             bgpManager.advertisePrefix(dstVpnRd, newVrfEntry.getDestPrefix(), nexthops, label.intValue());
1158         } catch (Exception exc) {
1159             LOG.error("Could not advertise prefix {} with label {} to VPN rd={}",
1160                     newVrfEntry.getDestPrefix(), label.intValue(), dstVpnRd);
1161         }
1162     }
1163
1164
1165     /**
1166      * Retrieves the ids of the currently operative DPNs
1167      *
1168      * @param dataBroker dataBroker service reference
1169      * @return the list of DPNs currently operative
1170      */
1171     public static List<BigInteger> getOperativeDPNs(DataBroker dataBroker) {
1172         List<BigInteger> result = new LinkedList<BigInteger>();
1173         InstanceIdentifier<Nodes> nodesInstanceIdentifier = InstanceIdentifier.builder(Nodes.class).build();
1174         Optional<Nodes> nodesOptional = MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL,
1175                 nodesInstanceIdentifier);
1176         if (!nodesOptional.isPresent()) {
1177             return result;
1178         }
1179         Nodes nodes = nodesOptional.get();
1180         List<Node> nodeList = nodes.getNode();
1181         for (Node node : nodeList) {
1182             NodeId nodeId = node.getId();
1183             if (nodeId != null) {
1184                 BigInteger dpnId = MDSALUtil.getDpnIdFromNodeName(nodeId);
1185                 result.add(dpnId);
1186             }
1187         }
1188         return result;
1189     }
1190
1191     /**
1192      * Retrieves a list of randomly selected DPNs, as many as specified.
1193      *
1194      * @param dataBroker dataBroker service reference
1195      * @param numberOfDPNs Specifies how many Operative DPNs must be found
1196      * @param excludingDPNs Specifies a blacklist of DPNs
1197      * @return the list of DPN Ids
1198      */
1199     public static List<BigInteger> pickRandomDPNs(DataBroker dataBroker, int numberOfDPNs,
1200                                                   List<BigInteger> excludingDPNs) {
1201         List<BigInteger> dpnIdPool = getOperativeDPNs(dataBroker);
1202         int poolSize = dpnIdPool.size();
1203         if (poolSize <= numberOfDPNs) {
1204             // You requested more than there is, I give you all I have.
1205             return dpnIdPool;
1206         }
1207
1208         // Random reorder
1209         Collections.shuffle(dpnIdPool);
1210         List<BigInteger> result = new ArrayList<BigInteger>();
1211
1212         for (BigInteger dpId : dpnIdPool) {
1213             if (excludingDPNs == null || !excludingDPNs.contains(dpId)) {
1214                 result.add(dpId);
1215                 if (result.size() == numberOfDPNs)
1216                     break;
1217             }
1218         }
1219
1220         if (result.size() < numberOfDPNs) {
1221             // We still don't have all we need, so we have to pick up among the "prohibited" ones
1222             dpnIdPool.removeAll(result);
1223
1224             int nbrOfProhibitedDpnsToPick = numberOfDPNs - result.size();
1225             for (int i = 0; i < nbrOfProhibitedDpnsToPick; i++) {
1226                 result.add(dpnIdPool.get(i));
1227             }
1228         }
1229         return result;
1230     }
1231
1232     public static void scheduleVpnInterfaceForRemoval(DataBroker broker,String interfaceName, BigInteger dpnId,
1233                                                       String vpnInstanceName, Boolean isScheduledToRemove,
1234                                                       WriteTransaction writeOperTxn){
1235         InstanceIdentifier<VpnInterface> interfaceId = VpnUtil.getVpnInterfaceIdentifier(interfaceName);
1236         VpnInterface interfaceToUpdate = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(interfaceName)).setName(interfaceName)
1237                 .setDpnId(dpnId).setVpnInstanceName(vpnInstanceName).setScheduledForRemove(isScheduledToRemove).build();
1238         if (writeOperTxn != null) {
1239             writeOperTxn.merge(LogicalDatastoreType.OPERATIONAL, interfaceId, interfaceToUpdate, true);
1240         } else {
1241             VpnUtil.syncUpdate(broker, LogicalDatastoreType.OPERATIONAL, interfaceId, interfaceToUpdate);
1242         }
1243     }
1244
1245     public static Port getNeutronPortForFloatingIp(DataBroker broker,
1246             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress targetIP) {
1247         InstanceIdentifier<Ports> portsIdentifier = InstanceIdentifier.create(Neutron.class).child(Ports.class);
1248         Optional<Ports> portsOptional = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, portsIdentifier);
1249         if (!portsOptional.isPresent() || portsOptional.get().getPort() == null) {
1250             LOG.trace("No neutron ports found");
1251             return null;
1252         }
1253
1254         for (Port port : portsOptional.get().getPort()) {
1255             if (NeutronConstants.DEVICE_OWNER_FLOATING_IP.equals(port.getDeviceOwner()) && port.getFixedIps() != null) {
1256                 for (FixedIps ip : port.getFixedIps()) {
1257                     if (Objects.equals(ip.getIpAddress(), targetIP)) {
1258                         return port;
1259                     }
1260                 }
1261             }
1262         }
1263
1264         return null;
1265     }
1266
1267     protected static void createVpnPortFixedIpToPort(DataBroker broker, String vpnName, String fixedIp,
1268                                                      String portName, String macAddress, boolean isSubnetIp, boolean isConfig,
1269                                                      boolean isLearnt) {
1270         InstanceIdentifier<VpnPortipToPort> id = buildVpnPortipToPortIdentifier(vpnName, fixedIp);
1271         VpnPortipToPortBuilder builder = new VpnPortipToPortBuilder().setKey(
1272                 new VpnPortipToPortKey(fixedIp, vpnName)).setVpnName(vpnName).setPortFixedip(fixedIp).setPortName(portName)
1273                 .setMacAddress(macAddress).setSubnetIp(isSubnetIp).setConfig(isConfig).setLearnt(isLearnt);
1274         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, builder.build());
1275         LOG.debug("ARP learned for fixedIp: {}, vpn {}, interface {}, mac {}, isSubnetIp {} added to VpnPortipToPort DS",
1276                 fixedIp, vpnName, portName, macAddress, isLearnt);
1277     }
1278
1279     protected static void updateVpnPortFixedIpToPort(DataBroker broker, String vpnName, String fixedIp,
1280                                                      String portName, String macAddress, boolean isSubnetIp,boolean isConfig,
1281                                                      boolean isLearnt) {
1282         InstanceIdentifier<VpnPortipToPort> id = buildVpnPortipToPortIdentifier(vpnName, fixedIp);
1283         VpnPortipToPortBuilder builder = new VpnPortipToPortBuilder().setKey(
1284                 new VpnPortipToPortKey(fixedIp, vpnName)).setVpnName(vpnName).setPortFixedip(fixedIp).setPortName(portName)
1285                 .setMacAddress(macAddress).setSubnetIp(isSubnetIp).setConfig(isConfig).setLearnt(isLearnt);;
1286         MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, id, builder.build());
1287         LOG.debug("Updated Arp learnt fixedIp: {}, vpn {}, interface {}, mac {}, isLearnt {} Updated to VpnPortipToPort DS",
1288                 fixedIp, vpnName, portName, macAddress, isLearnt);
1289     }
1290
1291     protected static void removeVpnPortFixedIpToPort(DataBroker broker, String vpnName, String fixedIp) {
1292         InstanceIdentifier<VpnPortipToPort> id = buildVpnPortipToPortIdentifier(vpnName, fixedIp);
1293         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, id);
1294         LOG.debug("Delete learned ARP for fixedIp: {}, vpn {} removed from VpnPortipToPort DS",
1295                 fixedIp, vpnName);
1296     }
1297
1298     static InstanceIdentifier<VpnPortipToPort> buildVpnPortipToPortIdentifier(String vpnName, String fixedIp) {
1299         InstanceIdentifier<VpnPortipToPort> id = InstanceIdentifier.builder(NeutronVpnPortipPortData.class).child
1300                 (VpnPortipToPort.class, new VpnPortipToPortKey(fixedIp, vpnName)).build();
1301         return id;
1302     }
1303
1304     static VpnPortipToPort getNeutronPortFromVpnPortFixedIp(DataBroker broker, String vpnName, String fixedIp) {
1305         InstanceIdentifier id = buildVpnPortipToPortIdentifier(vpnName, fixedIp);
1306         Optional<VpnPortipToPort> vpnPortipToPortData = read(broker, LogicalDatastoreType.CONFIGURATION, id);
1307         if (vpnPortipToPortData.isPresent()) {
1308             return (vpnPortipToPortData.get());
1309         }
1310         return null;
1311     }
1312     
1313     static String getAssociatedExternalNetwork(DataBroker dataBroker, String routerId) {
1314         InstanceIdentifier<Routers> id = buildRouterIdentifier(routerId);
1315         Optional<Routers> routerData = read(dataBroker, LogicalDatastoreType.CONFIGURATION, id);
1316         if (routerData.isPresent()) {
1317             Uuid networkId = routerData.get().getNetworkId();
1318             if(networkId != null) {
1319                 return networkId.getValue();
1320             }
1321         }
1322         return null;
1323     }
1324     
1325     static InstanceIdentifier<Routers> buildRouterIdentifier(String routerId) {
1326         InstanceIdentifier<Routers> routerInstanceIndentifier = InstanceIdentifier.builder(ExtRouters.class).child
1327                 (Routers.class, new RoutersKey(routerId)).build();
1328         return routerInstanceIndentifier;
1329     }
1330 }