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