neutronvpn: drop nullToEmpty and reqNonNullOrElse
[netvirt.git] / neutronvpn / impl / src / main / java / org / opendaylight / netvirt / neutronvpn / NeutronvpnUtils.java
1 /*
2  * Copyright (c) 2016, 2018 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.neutronvpn;
10
11 import static org.opendaylight.genius.infra.Datastore.OPERATIONAL;
12
13 import com.google.common.base.Function;
14 import com.google.common.base.Optional;
15 import com.google.common.collect.ImmutableBiMap;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import com.google.common.util.concurrent.SettableFuture;
21
22 import java.math.BigInteger;
23 import java.net.Inet4Address;
24 import java.net.Inet6Address;
25 import java.net.InetAddress;
26 import java.net.UnknownHostException;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.ConcurrentMap;
38 import java.util.concurrent.ExecutionException;
39 import java.util.concurrent.Future;
40 import java.util.concurrent.locks.ReentrantLock;
41 import java.util.stream.Collectors;
42 import javax.annotation.Nonnull;
43 import javax.annotation.Nullable;
44 import javax.inject.Inject;
45 import javax.inject.Singleton;
46
47 import org.apache.commons.lang3.StringUtils;
48 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
49 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
50 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
51 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
52 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
53 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
54 import org.opendaylight.genius.infra.Datastore;
55 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
56 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
57 import org.opendaylight.genius.infra.TypedWriteTransaction;
58 import org.opendaylight.genius.mdsalutil.MDSALUtil;
59 import org.opendaylight.genius.utils.JvmGlobalLocks;
60 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
61 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
62 import org.opendaylight.netvirt.neutronvpn.api.enums.IpVersionChoice;
63 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronUtils;
64 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
65 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces;
66 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
67 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey;
68 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
69 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceKey;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdOutput;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.Dhcpv6Base;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAclBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddress;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpVersionBase;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.PortSubnets;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairsBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.PortSubnet;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.PortSubnetBuilder;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.PortSubnetKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.port.subnet.SubnetInfo;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.port.subnet.SubnetInfoBuilder;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.port.subnet.SubnetInfoKey;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeBase;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeGre;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.LearntVpnVipToPortData;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.NeutronRouterDpns;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInstanceOpData;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInstanceToVpnId;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPort;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPortKey;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.neutron.router.dpns.RouterDpnList;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.neutron.router.dpns.RouterDpnListKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.neutron.router.dpns.router.dpn.list.DpnVpninterfacesList;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExtRouters;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExternalSubnets;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.FloatingIpPortInfo;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.RoutersKey;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.subnets.SubnetsKey;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.port.info.FloatingIpIdToPortMapping;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.port.info.FloatingIpIdToPortMappingKey;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NetworkMaps;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NeutronVpnPortipPortData;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.VpnMaps;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.networkmaps.NetworkMap;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.networkmaps.NetworkMapKey;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPort;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortKey;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpn.instance.RouterIds;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpn.instance.RouterIdsBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMap;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMapKey;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.RouterKey;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.ExternalGatewayInfo;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeGre;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.NetworkKey;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortKey;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.portsecurity.rev150712.PortSecurityExtension;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.rev160613.qos.attributes.qos.policies.QosPolicy;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetKey;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.InterVpnLinkStates;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.InterVpnLinks;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.link.states.InterVpnLinkState;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.link.states.InterVpnLinkStateKey;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.links.InterVpnLink;
169 import org.opendaylight.yangtools.yang.binding.DataObject;
170 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
171 import org.opendaylight.yangtools.yang.common.RpcResult;
172 import org.slf4j.Logger;
173 import org.slf4j.LoggerFactory;
174
175 @Singleton
176 public class NeutronvpnUtils {
177
178     private static final Logger LOG = LoggerFactory.getLogger(NeutronvpnUtils.class);
179     private static final ImmutableBiMap<Class<? extends NetworkTypeBase>, Class<? extends SegmentTypeBase>>
180         NETWORK_MAP =
181         new ImmutableBiMap.Builder<Class<? extends NetworkTypeBase>, Class<? extends SegmentTypeBase>>()
182             .put(NetworkTypeFlat.class, SegmentTypeFlat.class)
183             .put(NetworkTypeGre.class, SegmentTypeGre.class)
184             .put(NetworkTypeVlan.class, SegmentTypeVlan.class)
185             .put(NetworkTypeVxlan.class, SegmentTypeVxlan.class)
186             .build();
187
188     private static final Set<Class<? extends NetworkTypeBase>> SUPPORTED_NETWORK_TYPES = new HashSet<>();
189
190     static {
191         SUPPORTED_NETWORK_TYPES.add(NetworkTypeFlat.class);
192         SUPPORTED_NETWORK_TYPES.add(NetworkTypeVlan.class);
193         SUPPORTED_NETWORK_TYPES.add(NetworkTypeVxlan.class);
194         SUPPORTED_NETWORK_TYPES.add(NetworkTypeGre.class);
195     }
196
197     private final ConcurrentMap<Uuid, Network> networkMap = new ConcurrentHashMap<>();
198     private final ConcurrentMap<Uuid, Router> routerMap = new ConcurrentHashMap<>();
199     private final ConcurrentMap<Uuid, Port> portMap = new ConcurrentHashMap<>();
200     private final ConcurrentMap<Uuid, Subnet> subnetMap = new ConcurrentHashMap<>();
201     private final Map<IpAddress, Set<Uuid>> subnetGwIpMap = new ConcurrentHashMap<>();
202     private final ConcurrentMap<Uuid, QosPolicy> qosPolicyMap = new ConcurrentHashMap<>();
203     private final ConcurrentMap<Uuid, HashMap<Uuid, Port>> qosPortsMap = new ConcurrentHashMap<>();
204     private final ConcurrentMap<Uuid, HashMap<Uuid, Network>> qosNetworksMap = new ConcurrentHashMap<>();
205
206     private final DataBroker dataBroker;
207     private final ManagedNewTransactionRunner txRunner;
208     private final IdManagerService idManager;
209     private final JobCoordinator jobCoordinator;
210     private final IPV6InternetDefaultRouteProgrammer ipV6InternetDefRt;
211     private static final int JOB_MAX_RETRIES = 3;
212
213     @Inject
214     public NeutronvpnUtils(final DataBroker dataBroker, final IdManagerService idManager,
215             final JobCoordinator jobCoordinator, final IPV6InternetDefaultRouteProgrammer ipV6InternetDefRt) {
216         this.dataBroker = dataBroker;
217         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
218         this.idManager = idManager;
219         this.jobCoordinator = jobCoordinator;
220         this.ipV6InternetDefRt = ipV6InternetDefRt;
221     }
222
223     @Nullable
224     protected Subnetmap getSubnetmap(Uuid subnetId) {
225         InstanceIdentifier<Subnetmap> id = buildSubnetMapIdentifier(subnetId);
226         Optional<Subnetmap> sn = read(LogicalDatastoreType.CONFIGURATION, id);
227
228         if (sn.isPresent()) {
229             return sn.get();
230         }
231         LOG.error("getSubnetmap failed, subnet {} is not present", subnetId.getValue());
232         return null;
233     }
234
235     @Nullable
236     public VpnMap getVpnMap(Uuid id) {
237         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap.class,
238                 new VpnMapKey(id)).build();
239         Optional<VpnMap> optionalVpnMap = read(LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
240         if (optionalVpnMap.isPresent()) {
241             return optionalVpnMap.get();
242         }
243         LOG.error("getVpnMap failed, VPN {} not present", id.getValue());
244         return null;
245     }
246
247     @Nullable
248     protected Uuid getVpnForNetwork(Uuid network) {
249         InstanceIdentifier<VpnMaps> vpnMapsIdentifier = InstanceIdentifier.builder(VpnMaps.class).build();
250         Optional<VpnMaps> optionalVpnMaps = read(LogicalDatastoreType.CONFIGURATION, vpnMapsIdentifier);
251         if (optionalVpnMaps.isPresent() && optionalVpnMaps.get().getVpnMap() != null) {
252             for (VpnMap vpnMap : optionalVpnMaps.get().nonnullVpnMap()) {
253                 List<Uuid> netIds = vpnMap.getNetworkIds();
254                 if (netIds != null && netIds.contains(network)) {
255                     return vpnMap.getVpnId();
256                 }
257             }
258         }
259         LOG.debug("getVpnForNetwork: Failed for network {} as no VPN present in VPNMaps DS", network.getValue());
260         return null;
261     }
262
263     @Nullable
264     protected Uuid getVpnForSubnet(Uuid subnetId) {
265         InstanceIdentifier<Subnetmap> subnetmapIdentifier = buildSubnetMapIdentifier(subnetId);
266         Optional<Subnetmap> optionalSubnetMap = read(LogicalDatastoreType.CONFIGURATION,
267                 subnetmapIdentifier);
268         if (optionalSubnetMap.isPresent()) {
269             return optionalSubnetMap.get().getVpnId();
270         }
271         LOG.error("getVpnForSubnet: Failed as subnetMap DS is absent for subnet {}", subnetId.getValue());
272         return null;
273     }
274
275     @Nullable
276     protected Uuid getNetworkForSubnet(Uuid subnetId) {
277         InstanceIdentifier<Subnetmap> subnetmapIdentifier = buildSubnetMapIdentifier(subnetId);
278         Optional<Subnetmap> optionalSubnetMap = read(LogicalDatastoreType.CONFIGURATION,
279                 subnetmapIdentifier);
280         if (optionalSubnetMap.isPresent()) {
281             return optionalSubnetMap.get().getNetworkId();
282         }
283         LOG.error("getNetworkForSubnet: Failed as subnetMap DS is absent for subnet {}", subnetId.getValue());
284         return null;
285     }
286
287     // @param external vpn - true if external vpn being fetched, false for internal vpn
288     @Nullable
289     protected Uuid getVpnForRouter(@Nullable Uuid routerId, boolean externalVpn) {
290         if (routerId == null) {
291             return null;
292         }
293
294         InstanceIdentifier<VpnMaps> vpnMapsIdentifier = InstanceIdentifier.builder(VpnMaps.class).build();
295         Optional<VpnMaps> optionalVpnMaps = read(LogicalDatastoreType.CONFIGURATION, vpnMapsIdentifier);
296         if (optionalVpnMaps.isPresent() && optionalVpnMaps.get().getVpnMap() != null) {
297             for (VpnMap vpnMap : optionalVpnMaps.get().nonnullVpnMap()) {
298                 List<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.vpnmap
299                     .RouterIds> routerIdsList = vpnMap.getRouterIds();
300                 if (routerIdsList == null || routerIdsList.isEmpty()) {
301                     continue;
302                 }
303                 // Skip router vpnId fetching from internet BGP-VPN
304                 if (vpnMap.getNetworkIds() != null && !vpnMap.getNetworkIds().isEmpty()) {
305                     // We only need to check the first network; if it’s not an external network there’s no
306                     // need to check the rest of the VPN’s network list
307                     if (getIsExternal(getNeutronNetwork(vpnMap.getNetworkIds().iterator().next()))) {
308                         continue;
309                     }
310                 }
311                 // FIXME: NETVIRT-1503: this check can be replaced by a ReadOnlyTransaction.exists()
312                 if (routerIdsList.stream().anyMatch(routerIds -> routerId.equals(routerIds.getRouterId()))) {
313                     if (externalVpn) {
314                         if (!routerId.equals(vpnMap.getVpnId())) {
315                             return vpnMap.getVpnId();
316                         }
317                     } else {
318                         if (routerId.equals(vpnMap.getVpnId())) {
319                             return vpnMap.getVpnId();
320                         }
321                     }
322                 }
323             }
324         }
325         LOG.debug("getVpnForRouter: Failed for router {} as no VPN present in VPNMaps DS", routerId.getValue());
326         return null;
327     }
328
329     @Nullable
330     protected List<Uuid> getRouterIdListforVpn(Uuid vpnId) {
331         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap.class,
332                 new VpnMapKey(vpnId)).build();
333         Optional<VpnMap> optionalVpnMap = read(LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
334         if (optionalVpnMap.isPresent()) {
335             VpnMap vpnMap = optionalVpnMap.get();
336             return NeutronUtils.getVpnMapRouterIdsListUuid(vpnMap.getRouterIds());
337         }
338         LOG.error("getRouterIdListforVpn: Failed as VPNMaps DS is absent for VPN {}", vpnId.getValue());
339         return null;
340     }
341
342     @Nullable
343     protected List<Uuid> getNetworksForVpn(Uuid vpnId) {
344         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap.class,
345                 new VpnMapKey(vpnId)).build();
346         Optional<VpnMap> optionalVpnMap = read(LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
347         if (optionalVpnMap.isPresent()) {
348             VpnMap vpnMap = optionalVpnMap.get();
349             return vpnMap.getNetworkIds();
350         }
351         LOG.error("getNetworksforVpn: Failed as VPNMaps DS is absent for VPN {}", vpnId.getValue());
352         return null;
353     }
354
355     protected List<Uuid> getSubnetsforVpn(Uuid vpnid) {
356         List<Uuid> subnets = new ArrayList<>();
357         // read subnetmaps
358         InstanceIdentifier<Subnetmaps> subnetmapsid = InstanceIdentifier.builder(Subnetmaps.class).build();
359         Optional<Subnetmaps> subnetmaps = read(LogicalDatastoreType.CONFIGURATION, subnetmapsid);
360         if (subnetmaps.isPresent() && subnetmaps.get().getSubnetmap() != null) {
361             List<Subnetmap> subnetMapList = subnetmaps.get().getSubnetmap();
362             for (Subnetmap candidateSubnetMap : subnetMapList) {
363                 if (candidateSubnetMap.getVpnId() != null && candidateSubnetMap.getVpnId().equals(vpnid)) {
364                     subnets.add(candidateSubnetMap.getId());
365                 }
366             }
367         }
368         return subnets;
369     }
370
371     @Nullable
372     protected String getNeutronPortNameFromVpnPortFixedIp(String vpnName, String fixedIp) {
373         InstanceIdentifier<VpnPortipToPort> id = buildVpnPortipToPortIdentifier(vpnName, fixedIp);
374         Optional<VpnPortipToPort> vpnPortipToPortData = read(LogicalDatastoreType.CONFIGURATION, id);
375         if (vpnPortipToPortData.isPresent()) {
376             return vpnPortipToPortData.get().getPortName();
377         }
378         LOG.error("getNeutronPortNameFromVpnPortFixedIp: Failed as vpnPortipToPortData DS is absent for VPN {} and"
379                 + " fixed IP {}", vpnName, fixedIp);
380         return null;
381     }
382
383     @Nullable
384     protected List<Uuid> getSubnetIdsFromNetworkId(Uuid networkId) {
385         InstanceIdentifier<NetworkMap> id = buildNetworkMapIdentifier(networkId);
386         Optional<NetworkMap> optionalNetworkMap = read(LogicalDatastoreType.CONFIGURATION, id);
387         if (optionalNetworkMap.isPresent()) {
388             return optionalNetworkMap.get().getSubnetIdList();
389         }
390         LOG.error("getSubnetIdsFromNetworkId: Failed as networkmap DS is absent for network {}", networkId.getValue());
391         return null;
392     }
393
394     @Nullable
395     protected List<Uuid> getPortIdsFromSubnetId(Uuid subnetId) {
396         InstanceIdentifier<Subnetmap> id = buildSubnetMapIdentifier(subnetId);
397         Optional<Subnetmap> optionalSubnetmap = read(LogicalDatastoreType.CONFIGURATION, id);
398         if (optionalSubnetmap.isPresent()) {
399             return optionalSubnetmap.get().getPortList();
400         }
401         return null;
402     }
403
404     protected Router getNeutronRouter(Uuid routerId) {
405         Router router = routerMap.get(routerId);
406         if (router != null) {
407             return router;
408         }
409         InstanceIdentifier<Router> inst = InstanceIdentifier.create(Neutron.class).child(Routers.class).child(Router
410                 .class, new RouterKey(routerId));
411         Optional<Router> rtr = read(LogicalDatastoreType.CONFIGURATION, inst);
412         if (rtr.isPresent()) {
413             router = rtr.get();
414         }
415         return router;
416     }
417
418     public InstanceIdentifier<Router> getNeutronRouterIid(Uuid routerId) {
419         return InstanceIdentifier.create(Neutron.class).child(Routers.class).child(Router
420                 .class, new RouterKey(routerId));
421
422     }
423
424     protected Network getNeutronNetwork(Uuid networkId) {
425         Network network = null;
426         network = networkMap.get(networkId);
427         if (network != null) {
428             return network;
429         }
430         LOG.debug("getNeutronNetwork for {}", networkId.getValue());
431         InstanceIdentifier<Network> inst = InstanceIdentifier.create(Neutron.class).child(Networks.class)
432             .child(Network.class, new NetworkKey(networkId));
433         Optional<Network> net = read(LogicalDatastoreType.CONFIGURATION, inst);
434         if (net.isPresent()) {
435             network = net.get();
436         }
437         return network;
438     }
439
440     protected Port getNeutronPort(Uuid portId) {
441         Port prt = portMap.get(portId);
442         if (prt != null) {
443             return prt;
444         }
445         LOG.debug("getNeutronPort for {}", portId.getValue());
446         InstanceIdentifier<Port> inst = InstanceIdentifier.create(Neutron.class).child(Ports.class).child(Port.class,
447                 new PortKey(portId));
448         Optional<Port> port = read(LogicalDatastoreType.CONFIGURATION, inst);
449         if (port.isPresent()) {
450             prt = port.get();
451         }
452         return prt;
453     }
454
455     /**
456      * Returns port_security_enabled status with the port.
457      *
458      * @param port the port
459      * @return port_security_enabled status
460      */
461     protected static boolean getPortSecurityEnabled(Port port) {
462         String deviceOwner = port.getDeviceOwner();
463         if (deviceOwner != null && deviceOwner.startsWith("network:")) {
464             // port with device owner of network:xxx is created by
465             // neutorn for its internal use. So security group doesn't apply.
466             // router interface, dhcp port and floating ip.
467             return false;
468         }
469         PortSecurityExtension portSecurity = port.augmentation(PortSecurityExtension.class);
470         if (portSecurity != null) {
471             return portSecurity.isPortSecurityEnabled();
472         }
473         return false;
474     }
475
476     /**
477      * Gets security group UUIDs delta   .
478      *
479      * @param port1SecurityGroups the port 1 security groups
480      * @param port2SecurityGroups the port 2 security groups
481      * @return the security groups delta
482      */
483     @Nullable
484     protected static List<Uuid> getSecurityGroupsDelta(@Nullable List<Uuid> port1SecurityGroups,
485             @Nullable List<Uuid> port2SecurityGroups) {
486         if (port1SecurityGroups == null) {
487             return null;
488         }
489
490         if (port2SecurityGroups == null) {
491             return port1SecurityGroups;
492         }
493
494         List<Uuid> list1 = new ArrayList<>(port1SecurityGroups);
495         List<Uuid> list2 = new ArrayList<>(port2SecurityGroups);
496         for (Iterator<Uuid> iterator = list1.iterator(); iterator.hasNext();) {
497             Uuid securityGroup1 = iterator.next();
498             for (Uuid securityGroup2 : list2) {
499                 if (securityGroup1.getValue().equals(securityGroup2.getValue())) {
500                     iterator.remove();
501                     break;
502                 }
503             }
504         }
505         return list1;
506     }
507
508     /**
509      * Gets the fixed ips delta.
510      *
511      * @param port1FixedIps the port 1 fixed ips
512      * @param port2FixedIps the port 2 fixed ips
513      * @return the fixed ips delta
514      */
515     protected static List<FixedIps> getFixedIpsDelta(List<FixedIps> port1FixedIps, List<FixedIps> port2FixedIps) {
516         if (port1FixedIps == null) {
517             return null;
518         }
519
520         if (port2FixedIps == null) {
521             return port1FixedIps;
522         }
523
524         List<FixedIps> list1 = new ArrayList<>(port1FixedIps);
525         List<FixedIps> list2 = new ArrayList<>(port2FixedIps);
526         for (Iterator<FixedIps> iterator = list1.iterator(); iterator.hasNext();) {
527             FixedIps fixedIps1 = iterator.next();
528             for (FixedIps fixedIps2 : list2) {
529                 if (fixedIps1.getIpAddress().equals(fixedIps2.getIpAddress())) {
530                     iterator.remove();
531                     break;
532                 }
533             }
534         }
535         return list1;
536     }
537
538     /**
539      * Gets the allowed address pairs delta.
540      *
541      * @param port1AllowedAddressPairs the port 1 allowed address pairs
542      * @param port2AllowedAddressPairs the port 2 allowed address pairs
543      * @return the allowed address pairs delta
544      */
545     @Nullable
546     protected static List<AllowedAddressPairs> getAllowedAddressPairsDelta(
547         @Nullable List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
548             .AllowedAddressPairs> port1AllowedAddressPairs,
549         @Nullable List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
550             .AllowedAddressPairs> port2AllowedAddressPairs) {
551         if (port1AllowedAddressPairs == null) {
552             return null;
553         }
554
555         if (port2AllowedAddressPairs == null) {
556             return getAllowedAddressPairsForAclService(port1AllowedAddressPairs);
557         }
558
559         List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
560             .AllowedAddressPairs> list1 =
561                 new ArrayList<>(port1AllowedAddressPairs);
562         List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
563             .AllowedAddressPairs> list2 =
564                 new ArrayList<>(port2AllowedAddressPairs);
565         for (Iterator<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
566             .AllowedAddressPairs> iterator =
567              list1.iterator(); iterator.hasNext();) {
568             org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
569                 .AllowedAddressPairs allowedAddressPair1 = iterator.next();
570             for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
571                      .AllowedAddressPairs allowedAddressPair2 : list2) {
572                 if (allowedAddressPair1.key().equals(allowedAddressPair2.key())) {
573                     iterator.remove();
574                     break;
575                 }
576             }
577         }
578         return getAllowedAddressPairsForAclService(list1);
579     }
580
581     /**
582      * Gets the acl allowed address pairs.
583      *
584      * @param macAddress the mac address
585      * @param ipAddress the ip address
586      * @return the acl allowed address pairs
587      */
588     protected static AllowedAddressPairs getAclAllowedAddressPairs(MacAddress macAddress,
589             org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.types.rev160517.IpPrefixOrAddress ipAddress) {
590         AllowedAddressPairsBuilder aclAllowedAdressPairBuilder = new AllowedAddressPairsBuilder();
591         aclAllowedAdressPairBuilder.setMacAddress(macAddress);
592         if (ipAddress != null && ipAddress.stringValue() != null) {
593             if (ipAddress.getIpPrefix() != null) {
594                 aclAllowedAdressPairBuilder.setIpAddress(new IpPrefixOrAddress(ipAddress.getIpPrefix()));
595             } else {
596                 aclAllowedAdressPairBuilder.setIpAddress(new IpPrefixOrAddress(ipAddress.getIpAddress()));
597             }
598         }
599         return aclAllowedAdressPairBuilder.build();
600     }
601
602     /**
603      * Gets the allowed address pairs for acl service.
604      *
605      * @param macAddress the mac address
606      * @param fixedIps the fixed ips
607      * @return the allowed address pairs for acl service
608      */
609     protected static List<AllowedAddressPairs> getAllowedAddressPairsForAclService(MacAddress macAddress,
610             List<FixedIps> fixedIps) {
611         List<AllowedAddressPairs> aclAllowedAddressPairs = new ArrayList<>();
612         for (FixedIps fixedIp : fixedIps) {
613             aclAllowedAddressPairs.add(getAclAllowedAddressPairs(macAddress,
614                     org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.types.rev160517.IpPrefixOrAddressBuilder
615                     .getDefaultInstance(fixedIp.getIpAddress().stringValue())));
616         }
617         return aclAllowedAddressPairs;
618     }
619
620     /**
621      * Gets the allowed address pairs for acl service.
622      *
623      * @param portAllowedAddressPairs the port allowed address pairs
624      * @return the allowed address pairs for acl service
625      */
626     protected static List<AllowedAddressPairs> getAllowedAddressPairsForAclService(
627         List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
628             .AllowedAddressPairs> portAllowedAddressPairs) {
629         List<AllowedAddressPairs> aclAllowedAddressPairs = new ArrayList<>();
630         for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs
631                  portAllowedAddressPair : portAllowedAddressPairs) {
632             aclAllowedAddressPairs.add(getAclAllowedAddressPairs(portAllowedAddressPair.getMacAddress(),
633                 portAllowedAddressPair.getIpAddress()));
634         }
635         return aclAllowedAddressPairs;
636     }
637
638     /**
639      * Gets the IPv6 Link Local Address corresponding to the MAC Address.
640      *
641      * @param macAddress the mac address
642      * @return the allowed address pairs for acl service which includes the MAC + IPv6LLA
643      */
644     protected static AllowedAddressPairs updateIPv6LinkLocalAddressForAclService(MacAddress macAddress) {
645         IpAddress ipv6LinkLocalAddress = getIpv6LinkLocalAddressFromMac(macAddress);
646         return getAclAllowedAddressPairs(macAddress,
647                 org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.types.rev160517.IpPrefixOrAddressBuilder
648                 .getDefaultInstance(
649                         ipv6LinkLocalAddress.stringValue()));
650     }
651
652     /**
653      * Gets the updated security groups.
654      *
655      * @param aclInterfaceSecurityGroups the acl interface security groups
656      * @param origSecurityGroups the orig security groups
657      * @param newSecurityGroups the new security groups
658      * @return the updated security groups
659      */
660     protected static List<Uuid> getUpdatedSecurityGroups(List<Uuid> aclInterfaceSecurityGroups,
661             List<Uuid> origSecurityGroups, List<Uuid> newSecurityGroups) {
662         List<Uuid> addedGroups = getSecurityGroupsDelta(newSecurityGroups, origSecurityGroups);
663         List<Uuid> deletedGroups = getSecurityGroupsDelta(origSecurityGroups, newSecurityGroups);
664         List<Uuid> updatedSecurityGroups =
665                 aclInterfaceSecurityGroups != null ? new ArrayList<>(aclInterfaceSecurityGroups) : new ArrayList<>();
666         if (addedGroups != null) {
667             updatedSecurityGroups.addAll(addedGroups);
668         }
669         if (deletedGroups != null) {
670             updatedSecurityGroups.removeAll(deletedGroups);
671         }
672         return updatedSecurityGroups;
673     }
674
675     /**
676      * Gets the allowed address pairs for fixed ips.
677      *
678      * @param aclInterfaceAllowedAddressPairs the acl interface allowed address pairs
679      * @param portMacAddress the port mac address
680      * @param origFixedIps the orig fixed ips
681      * @param newFixedIps the new fixed ips
682      * @return the allowed address pairs for fixed ips
683      */
684     protected static List<AllowedAddressPairs> getAllowedAddressPairsForFixedIps(
685             List<AllowedAddressPairs> aclInterfaceAllowedAddressPairs, MacAddress portMacAddress,
686             List<FixedIps> origFixedIps, List<FixedIps> newFixedIps) {
687         List<FixedIps> addedFixedIps = getFixedIpsDelta(newFixedIps, origFixedIps);
688         List<FixedIps> deletedFixedIps = getFixedIpsDelta(origFixedIps, newFixedIps);
689         List<AllowedAddressPairs> updatedAllowedAddressPairs =
690             aclInterfaceAllowedAddressPairs != null
691                 ? new ArrayList<>(aclInterfaceAllowedAddressPairs) : new ArrayList<>();
692         if (deletedFixedIps != null) {
693             updatedAllowedAddressPairs.removeAll(getAllowedAddressPairsForAclService(portMacAddress, deletedFixedIps));
694         }
695         if (addedFixedIps != null) {
696             updatedAllowedAddressPairs.addAll(getAllowedAddressPairsForAclService(portMacAddress, addedFixedIps));
697         }
698         return updatedAllowedAddressPairs;
699     }
700
701     /**
702      * Gets the updated allowed address pairs.
703      *
704      * @param aclInterfaceAllowedAddressPairs the acl interface allowed address pairs
705      * @param origAllowedAddressPairs the orig allowed address pairs
706      * @param newAllowedAddressPairs the new allowed address pairs
707      * @return the updated allowed address pairs
708      */
709     protected static List<AllowedAddressPairs> getUpdatedAllowedAddressPairs(
710             List<AllowedAddressPairs> aclInterfaceAllowedAddressPairs,
711             List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
712                 .AllowedAddressPairs> origAllowedAddressPairs,
713             List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes
714                 .AllowedAddressPairs> newAllowedAddressPairs) {
715         List<AllowedAddressPairs> addedAllowedAddressPairs =
716             getAllowedAddressPairsDelta(newAllowedAddressPairs,origAllowedAddressPairs);
717         List<AllowedAddressPairs> deletedAllowedAddressPairs =
718             getAllowedAddressPairsDelta(origAllowedAddressPairs, newAllowedAddressPairs);
719         List<AllowedAddressPairs> updatedAllowedAddressPairs =
720             aclInterfaceAllowedAddressPairs != null
721                 ? new ArrayList<>(aclInterfaceAllowedAddressPairs) : new ArrayList<>();
722         if (addedAllowedAddressPairs != null) {
723             updatedAllowedAddressPairs.addAll(addedAllowedAddressPairs);
724         }
725         if (deletedAllowedAddressPairs != null) {
726             updatedAllowedAddressPairs.removeAll(deletedAllowedAddressPairs);
727         }
728         return updatedAllowedAddressPairs;
729     }
730
731     /**
732      * Populate interface acl builder.
733      *
734      * @param interfaceAclBuilder the interface acl builder
735      * @param port the port
736      */
737     protected static void populateInterfaceAclBuilder(InterfaceAclBuilder interfaceAclBuilder, Port port) {
738         // Handle security group enabled
739         List<Uuid> securityGroups = port.getSecurityGroups();
740         if (securityGroups != null) {
741             interfaceAclBuilder.setSecurityGroups(securityGroups);
742         }
743         List<AllowedAddressPairs> aclAllowedAddressPairs = NeutronvpnUtils.getAllowedAddressPairsForAclService(
744                 port.getMacAddress(), port.getFixedIps());
745         // Update the allowed address pair with the IPv6 LLA that is auto configured on the port.
746         aclAllowedAddressPairs.add(NeutronvpnUtils.updateIPv6LinkLocalAddressForAclService(port.getMacAddress()));
747         List<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs>
748             portAllowedAddressPairs = port.getAllowedAddressPairs();
749         if (portAllowedAddressPairs != null) {
750             aclAllowedAddressPairs.addAll(NeutronvpnUtils.getAllowedAddressPairsForAclService(portAllowedAddressPairs));
751         }
752         interfaceAclBuilder.setAllowedAddressPairs(aclAllowedAddressPairs);
753     }
754
755     protected void populateSubnetInfo(Port port) {
756         List<SubnetInfo> portSubnetInfo = getSubnetInfo(port);
757         if (portSubnetInfo != null) {
758             String portId = port.getUuid().getValue();
759             InstanceIdentifier<PortSubnet> portSubnetIdentifier = buildPortSubnetIdentifier(portId);
760
761             PortSubnetBuilder portSubnetBuilder = new PortSubnetBuilder().withKey(new PortSubnetKey(portId))
762                     .setPortId(portId).setSubnetInfo(portSubnetInfo);
763             try {
764                 SingleTransactionDataBroker.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL,
765                         portSubnetIdentifier, portSubnetBuilder.build());
766             } catch (TransactionCommitFailedException e) {
767                 LOG.error("Failed to populate subnet info for port={}", portId, e);
768             }
769             LOG.debug("Created Subnet info for port={}", portId);
770         }
771     }
772
773     @Nullable
774     protected List<SubnetInfo> getSubnetInfo(Port port) {
775         List<FixedIps> portFixedIps = port.getFixedIps();
776         if (portFixedIps == null) {
777             LOG.error("Failed to get Fixed IPs for the port {}", port.getName());
778             return null;
779         }
780         List<SubnetInfo> subnetInfoList = new ArrayList<>();
781         for (FixedIps portFixedIp : portFixedIps) {
782             Uuid subnetId = portFixedIp.getSubnetId();
783             Subnet subnet = getNeutronSubnet(subnetId);
784             if (subnet != null) {
785                 Class<? extends IpVersionBase> ipVersion =
786                         NeutronSecurityRuleConstants.IP_VERSION_MAP.get(subnet.getIpVersion());
787                 Class<? extends Dhcpv6Base> raMode = subnet.getIpv6RaMode() == null ? null
788                         : NeutronSecurityRuleConstants.RA_MODE_MAP.get(subnet.getIpv6RaMode());
789                 SubnetInfo subnetInfo = new SubnetInfoBuilder().withKey(new SubnetInfoKey(subnetId))
790                         .setIpVersion(ipVersion).setIpPrefix(new IpPrefixOrAddress(subnet.getCidr()))
791                         .setIpv6RaMode(raMode).setGatewayIp(subnet.getGatewayIp()).build();
792                 subnetInfoList.add(subnetInfo);
793             }
794         }
795         return subnetInfoList;
796     }
797
798     protected Subnet getNeutronSubnet(Uuid subnetId) {
799         Subnet subnet = subnetMap.get(subnetId);
800         if (subnet != null) {
801             return subnet;
802         }
803         InstanceIdentifier<Subnet> inst = InstanceIdentifier.create(Neutron.class).child(Subnets.class).child(Subnet
804                 .class, new SubnetKey(subnetId));
805         Optional<Subnet> sn = read(LogicalDatastoreType.CONFIGURATION, inst);
806
807         if (sn.isPresent()) {
808             subnet = sn.get();
809             addToSubnetCache(subnet);
810         }
811         return subnet;
812     }
813
814     protected List<Subnetmap> getNeutronRouterSubnetMapList(Uuid routerId) {
815         List<Subnetmap> subnetMapList = new ArrayList<>();
816         Optional<Subnetmaps> subnetMaps = read(LogicalDatastoreType.CONFIGURATION,
817                 InstanceIdentifier.builder(Subnetmaps.class).build());
818         if (subnetMaps.isPresent() && subnetMaps.get().getSubnetmap() != null) {
819             for (Subnetmap subnetmap : subnetMaps.get().getSubnetmap()) {
820                 if (routerId.equals(subnetmap.getRouterId())) {
821                     subnetMapList.add(subnetmap);
822                 }
823             }
824         }
825         LOG.debug("getNeutronRouterSubnetMapList returns {}", subnetMapList);
826         return subnetMapList;
827     }
828
829     @Nonnull
830     protected List<Uuid> getNeutronRouterSubnetIds(Uuid routerId) {
831         LOG.debug("getNeutronRouterSubnetIds for {}", routerId.getValue());
832         List<Uuid> subnetIdList = new ArrayList<>();
833         Optional<Subnetmaps> subnetMaps = read(LogicalDatastoreType.CONFIGURATION,
834             InstanceIdentifier.builder(Subnetmaps.class).build());
835         if (subnetMaps.isPresent() && subnetMaps.get().getSubnetmap() != null) {
836             for (Subnetmap subnetmap : subnetMaps.get().getSubnetmap()) {
837                 if (routerId.equals(subnetmap.getRouterId())) {
838                     subnetIdList.add(subnetmap.getId());
839                 }
840             }
841         }
842         LOG.debug("getNeutronRouterSubnetIds returns {}", subnetIdList);
843         return subnetIdList;
844     }
845
846     // TODO Clean up the exception handling and the console output
847     @SuppressWarnings({"checkstyle:IllegalCatch", "checkstyle:RegexpSinglelineJava"})
848     @Nullable
849     protected Short getIPPrefixFromPort(Port port) {
850         try {
851             Uuid subnetUUID = port.getFixedIps().get(0).getSubnetId();
852             SubnetKey subnetkey = new SubnetKey(subnetUUID);
853             InstanceIdentifier<Subnet> subnetidentifier = InstanceIdentifier.create(Neutron.class).child(Subnets
854                     .class).child(Subnet.class, subnetkey);
855             Optional<Subnet> subnet = read(LogicalDatastoreType.CONFIGURATION, subnetidentifier);
856             if (subnet.isPresent()) {
857                 String cidr = subnet.get().getCidr().stringValue();
858                 // Extract the prefix length from cidr
859                 String[] parts = cidr.split("/");
860                 if (parts.length == 2) {
861                     return Short.valueOf(parts[1]);
862                 } else {
863                     LOG.trace("Could not retrieve prefix from subnet CIDR");
864                 }
865             } else {
866                 LOG.trace("Unable to read on subnet datastore");
867             }
868         } catch (Exception e) {
869             LOG.error("Failed to retrieve IP prefix from port for port {}", port.getUuid().getValue(), e);
870         }
871         LOG.error("Failed for port {}", port.getUuid().getValue());
872         return null;
873     }
874
875     // TODO Clean up the exception handling
876     @SuppressWarnings("checkstyle:IllegalCatch")
877     protected void createVpnPortFixedIpToPort(String vpnName, String fixedIp, String portName, String macAddress,
878             boolean isSubnetIp, TypedWriteTransaction<Datastore.Configuration> writeConfigTxn) {
879         InstanceIdentifier<VpnPortipToPort> id = NeutronvpnUtils.buildVpnPortipToPortIdentifier(vpnName, fixedIp);
880         VpnPortipToPortBuilder builder = new VpnPortipToPortBuilder()
881             .withKey(new VpnPortipToPortKey(fixedIp, vpnName))
882             .setVpnName(vpnName).setPortFixedip(fixedIp)
883             .setPortName(portName).setMacAddress(macAddress).setSubnetIp(isSubnetIp);
884         try {
885             if (writeConfigTxn != null) {
886                 writeConfigTxn.put(id, builder.build());
887             } else {
888                 MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, id, builder.build());
889             }
890             LOG.trace("Neutron port with fixedIp: {}, vpn {}, interface {}, mac {}, isSubnetIp {} added to "
891                 + "VpnPortipToPort DS", fixedIp, vpnName, portName, macAddress, isSubnetIp);
892         } catch (Exception e) {
893             LOG.error("Failure while creating VPNPortFixedIpToPort map for vpn {} - fixedIP {}", vpnName, fixedIp,
894                     e);
895         }
896     }
897
898     // TODO Clean up the exception handling
899     @SuppressWarnings("checkstyle:IllegalCatch")
900     protected void removeVpnPortFixedIpToPort(String vpnName, String fixedIp,
901                                               TypedWriteTransaction<Datastore.Configuration> writeConfigTxn) {
902         InstanceIdentifier<VpnPortipToPort> id = NeutronvpnUtils.buildVpnPortipToPortIdentifier(vpnName, fixedIp);
903         try {
904             if (writeConfigTxn != null) {
905                 writeConfigTxn.delete(id);
906             } else {
907                 MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, id);
908             }
909             LOG.trace("Neutron router port with fixedIp: {}, vpn {} removed from VpnPortipToPort DS", fixedIp,
910                     vpnName);
911         } catch (Exception e) {
912             LOG.error("Failure while removing VPNPortFixedIpToPort map for vpn {} - fixedIP {}", vpnName, fixedIp,
913                     e);
914         }
915     }
916
917     // TODO Clean up the exception handling
918     @SuppressWarnings("checkstyle:IllegalCatch")
919     protected void removeLearntVpnVipToPort(String vpnName, String fixedIp) {
920         InstanceIdentifier<LearntVpnVipToPort> id = NeutronvpnUtils.buildLearntVpnVipToPortIdentifier(vpnName, fixedIp);
921         // FIXME: can we use 'id' as the lock name?
922         final ReentrantLock lock = JvmGlobalLocks.getLockForString(vpnName + fixedIp);
923         lock.lock();
924         try {
925             MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.OPERATIONAL, id);
926             LOG.trace("Neutron router port with fixedIp: {}, vpn {} removed from LearntVpnPortipToPort DS", fixedIp,
927                     vpnName);
928         } catch (Exception e) {
929             LOG.error("Failure while removing LearntVpnPortFixedIpToPort map for vpn {} - fixedIP {}",
930                 vpnName, fixedIp, e);
931         } finally {
932             lock.unlock();
933         }
934     }
935
936     public void addToNetworkCache(Network network) {
937         networkMap.put(network.getUuid(), network);
938     }
939
940     public void removeFromNetworkCache(Network network) {
941         networkMap.remove(network.getUuid());
942     }
943
944     public void addToRouterCache(Router router) {
945         routerMap.put(router.getUuid(), router);
946     }
947
948     public void removeFromRouterCache(Router router) {
949         routerMap.remove(router.getUuid());
950     }
951
952     public Collection<Router> getAllRouters() {
953         return routerMap.values();
954     }
955
956     public void addToPortCache(Port port) {
957         portMap.put(port.getUuid(), port);
958     }
959
960     public void removeFromPortCache(Port port) {
961         portMap.remove(port.getUuid());
962     }
963
964     public void addToSubnetCache(Subnet subnet) {
965         subnetMap.put(subnet.getUuid(), subnet);
966         IpAddress gatewayIp = subnet.getGatewayIp();
967         if (gatewayIp != null) {
968             subnetGwIpMap.computeIfAbsent(gatewayIp, k -> Sets.newConcurrentHashSet()).add(subnet.getUuid());
969         }
970     }
971
972     public void removeFromSubnetCache(Subnet subnet) {
973         subnetMap.remove(subnet.getUuid());
974         IpAddress gatewayIp = subnet.getGatewayIp();
975         if (gatewayIp != null) {
976             Set<Uuid> gwIps = subnetGwIpMap.get(gatewayIp);
977             if (gwIps != null) {
978                 gwIps.remove(subnet.getUuid());
979             }
980         }
981     }
982
983     public static String getSegmentationIdFromNeutronNetwork(Network network) {
984         String segmentationId = null;
985         NetworkProviderExtension providerExtension = network.augmentation(NetworkProviderExtension.class);
986         if (providerExtension != null) {
987             Class<? extends NetworkTypeBase> networkType = providerExtension.getNetworkType();
988             segmentationId = NeutronUtils.getSegmentationIdFromNeutronNetwork(network, networkType);
989         }
990
991         return segmentationId;
992     }
993
994     public static Class<? extends SegmentTypeBase> getSegmentTypeFromNeutronNetwork(Network network) {
995         NetworkProviderExtension providerExtension = network.augmentation(NetworkProviderExtension.class);
996         return providerExtension != null ? NETWORK_MAP.get(providerExtension.getNetworkType()) : null;
997     }
998
999     public static String getPhysicalNetworkName(Network network) {
1000         NetworkProviderExtension providerExtension = network.augmentation(NetworkProviderExtension.class);
1001         return providerExtension != null ? providerExtension.getPhysicalNetwork() : null;
1002     }
1003
1004     public Collection<Uuid> getSubnetIdsForGatewayIp(IpAddress ipAddress) {
1005         return subnetGwIpMap.getOrDefault(ipAddress, Collections.emptySet());
1006     }
1007
1008     static InstanceIdentifier<VpnPortipToPort> buildVpnPortipToPortIdentifier(String vpnName, String fixedIp) {
1009         InstanceIdentifier<VpnPortipToPort> id =
1010             InstanceIdentifier.builder(NeutronVpnPortipPortData.class)
1011                 .child(VpnPortipToPort.class, new VpnPortipToPortKey(fixedIp, vpnName)).build();
1012         return id;
1013     }
1014
1015     static InstanceIdentifier<LearntVpnVipToPort> buildLearntVpnVipToPortIdentifier(String vpnName, String fixedIp) {
1016         InstanceIdentifier<LearntVpnVipToPort> id =
1017             InstanceIdentifier.builder(LearntVpnVipToPortData.class)
1018                 .child(LearntVpnVipToPort.class, new LearntVpnVipToPortKey(fixedIp, vpnName)).build();
1019         return id;
1020     }
1021
1022     static Boolean getIsExternal(Network network) {
1023         return network.augmentation(NetworkL3Extension.class) != null
1024                 && network.augmentation(NetworkL3Extension.class).isExternal();
1025     }
1026
1027     public void addToQosPolicyCache(QosPolicy qosPolicy) {
1028         qosPolicyMap.put(qosPolicy.getUuid(),qosPolicy);
1029     }
1030
1031     public void removeFromQosPolicyCache(QosPolicy qosPolicy) {
1032         qosPolicyMap.remove(qosPolicy.getUuid());
1033     }
1034
1035     public void addToQosPortsCache(Uuid qosUuid, Port port) {
1036         if (qosPortsMap.containsKey(qosUuid)) {
1037             if (!qosPortsMap.get(qosUuid).containsKey(port.getUuid())) {
1038                 qosPortsMap.get(qosUuid).put(port.getUuid(), port);
1039             }
1040         } else {
1041             HashMap<Uuid, Port> newPortMap = new HashMap<>();
1042             newPortMap.put(port.getUuid(), port);
1043             qosPortsMap.put(qosUuid, newPortMap);
1044         }
1045     }
1046
1047     public void removeFromQosPortsCache(Uuid qosUuid, Port port) {
1048         if (qosPortsMap.containsKey(qosUuid) && qosPortsMap.get(qosUuid).containsKey(port.getUuid())) {
1049             qosPortsMap.get(qosUuid).remove(port.getUuid(), port);
1050         }
1051     }
1052
1053     public void addToQosNetworksCache(Uuid qosUuid, Network network) {
1054         if (qosNetworksMap.containsKey(qosUuid)) {
1055             if (!qosNetworksMap.get(qosUuid).containsKey(network.getUuid())) {
1056                 qosNetworksMap.get(qosUuid).put(network.getUuid(), network);
1057             }
1058         } else {
1059             HashMap<Uuid, Network> newNetworkMap = new HashMap<>();
1060             newNetworkMap.put(network.getUuid(), network);
1061             qosNetworksMap.put(qosUuid, newNetworkMap);
1062         }
1063     }
1064
1065     public void removeFromQosNetworksCache(Uuid qosUuid, Network network) {
1066         if (qosNetworksMap.containsKey(qosUuid) && qosNetworksMap.get(qosUuid).containsKey(network.getUuid())) {
1067             qosNetworksMap.get(qosUuid).remove(network.getUuid(), network);
1068         }
1069     }
1070
1071     static InstanceIdentifier<NetworkMap> buildNetworkMapIdentifier(Uuid networkId) {
1072         InstanceIdentifier<NetworkMap> id = InstanceIdentifier.builder(NetworkMaps.class).child(NetworkMap.class, new
1073                 NetworkMapKey(networkId)).build();
1074         return id;
1075     }
1076
1077     static InstanceIdentifier<VpnInterface> buildVpnInterfaceIdentifier(String ifName) {
1078         InstanceIdentifier<VpnInterface> id = InstanceIdentifier.builder(VpnInterfaces.class).child(VpnInterface
1079                 .class, new VpnInterfaceKey(ifName)).build();
1080         return id;
1081     }
1082
1083     static InstanceIdentifier<Subnetmap> buildSubnetMapIdentifier(Uuid subnetId) {
1084         InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).child(Subnetmap.class, new
1085                 SubnetmapKey(subnetId)).build();
1086         return id;
1087     }
1088
1089     static InstanceIdentifier<Interface> buildVlanInterfaceIdentifier(String interfaceName) {
1090         InstanceIdentifier<Interface> id = InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new
1091                 InterfaceKey(interfaceName)).build();
1092         return id;
1093     }
1094
1095     static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext
1096             .routers.Routers> buildExtRoutersIdentifier(Uuid routerId) {
1097         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers
1098                 .Routers> id = InstanceIdentifier.builder(ExtRouters.class).child(org.opendaylight.yang.gen.v1.urn
1099                 .opendaylight.netvirt.natservice.rev160111.ext.routers.Routers.class, new RoutersKey(routerId
1100                 .getValue())).build();
1101         return id;
1102     }
1103
1104     static InstanceIdentifier<FloatingIpIdToPortMapping> buildfloatingIpIdToPortMappingIdentifier(Uuid floatingIpId) {
1105         return InstanceIdentifier.builder(FloatingIpPortInfo.class).child(FloatingIpIdToPortMapping.class, new
1106                 FloatingIpIdToPortMappingKey(floatingIpId)).build();
1107     }
1108
1109     static InstanceIdentifier<PortSubnet> buildPortSubnetIdentifier(String portId) {
1110         InstanceIdentifier<PortSubnet> id = InstanceIdentifier.builder(PortSubnets.class)
1111                 .child(PortSubnet.class, new PortSubnetKey(portId)).build();
1112         return id;
1113     }
1114
1115     // TODO Remove this method entirely
1116     @SuppressWarnings("checkstyle:IllegalCatch")
1117     private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
1118         try {
1119             return SingleTransactionDataBroker.syncReadOptional(dataBroker, datastoreType, path);
1120         } catch (ReadFailedException e) {
1121             throw new RuntimeException(e);
1122         }
1123     }
1124
1125     public static Class<? extends NetworkTypeBase> getNetworkType(Network network) {
1126         NetworkProviderExtension providerExtension = network.augmentation(NetworkProviderExtension.class);
1127         return providerExtension != null ? providerExtension.getNetworkType() : null;
1128     }
1129
1130     @Nullable
1131     static ProviderTypes getProviderNetworkType(Network network) {
1132         if (network == null) {
1133             LOG.error("Error in getting provider network type since network is null");
1134             return null;
1135         }
1136         NetworkProviderExtension npe = network.augmentation(NetworkProviderExtension.class);
1137         if (npe != null) {
1138             Class<? extends NetworkTypeBase> networkTypeBase = npe.getNetworkType();
1139             if (networkTypeBase != null) {
1140                 if (networkTypeBase.isAssignableFrom(NetworkTypeFlat.class)) {
1141                     return ProviderTypes.FLAT;
1142                 } else if (networkTypeBase.isAssignableFrom(NetworkTypeVlan.class)) {
1143                     return ProviderTypes.VLAN;
1144                 } else if (networkTypeBase.isAssignableFrom(NetworkTypeVxlan.class)) {
1145                     return ProviderTypes.VXLAN;
1146                 } else if (networkTypeBase.isAssignableFrom(NetworkTypeGre.class)) {
1147                     return ProviderTypes.GRE;
1148                 }
1149             }
1150         }
1151         LOG.error("Error in getting provider network type since network provider extension is null for network "
1152                 + "{}", network.getUuid().getValue());
1153         return null;
1154     }
1155
1156     static boolean isNetworkTypeSupported(Network network) {
1157         NetworkProviderExtension npe = network.augmentation(NetworkProviderExtension.class);
1158         return npe != null && npe.getNetworkType() != null && SUPPORTED_NETWORK_TYPES.contains(npe.getNetworkType());
1159     }
1160
1161     static boolean isNetworkOfType(Network network, Class<? extends NetworkTypeBase> type) {
1162         NetworkProviderExtension npe = network.augmentation(NetworkProviderExtension.class);
1163         if (npe != null && npe.getNetworkType() != null) {
1164             return type.isAssignableFrom(npe.getNetworkType());
1165         }
1166         return false;
1167     }
1168
1169     static boolean isFlatOrVlanNetwork(Network network) {
1170         return network != null
1171                 && (isNetworkOfType(network, NetworkTypeVlan.class) || isNetworkOfType(network, NetworkTypeFlat.class));
1172     }
1173
1174     static boolean isVlanOrVxlanNetwork(Class<? extends NetworkTypeBase> type) {
1175         return type.isAssignableFrom(NetworkTypeVxlan.class) || type.isAssignableFrom(NetworkTypeVlan.class);
1176     }
1177
1178     /**
1179      * Get inter-VPN link state.
1180      *
1181      * @param vpnLinkName VPN link name
1182      * @return Optional of InterVpnLinkState
1183      */
1184     public Optional<InterVpnLinkState> getInterVpnLinkState(String vpnLinkName) {
1185         InstanceIdentifier<InterVpnLinkState> vpnLinkStateIid = InstanceIdentifier.builder(InterVpnLinkStates.class)
1186                 .child(InterVpnLinkState.class, new InterVpnLinkStateKey(vpnLinkName)).build();
1187         return read(LogicalDatastoreType.CONFIGURATION, vpnLinkStateIid);
1188     }
1189
1190     /**
1191      * Returns an InterVpnLink by searching by one of its endpoint's IP.
1192      *
1193      * @param endpointIp IP to search for
1194      * @return a InterVpnLink
1195      */
1196     public Optional<InterVpnLink> getInterVpnLinkByEndpointIp(String endpointIp) {
1197         InstanceIdentifier<InterVpnLinks> interVpnLinksIid = InstanceIdentifier.builder(InterVpnLinks.class).build();
1198         Optional<InterVpnLinks> interVpnLinksOpData = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
1199                 interVpnLinksIid);
1200         if (interVpnLinksOpData.isPresent()) {
1201             for (InterVpnLink interVpnLink : interVpnLinksOpData.get().nonnullInterVpnLink()) {
1202                 if (interVpnLink.getFirstEndpoint().getIpAddress().getValue().equals(endpointIp)
1203                         || interVpnLink.getSecondEndpoint().getIpAddress().getValue().equals(endpointIp)) {
1204                     return Optional.of(interVpnLink);
1205                 }
1206             }
1207         }
1208         return Optional.absent();
1209     }
1210
1211     public Set<RouterDpnList> getAllRouterDpnList(BigInteger dpid) {
1212         Set<RouterDpnList> ret = new HashSet<>();
1213         InstanceIdentifier<NeutronRouterDpns> routerDpnId =
1214                 InstanceIdentifier.create(NeutronRouterDpns.class);
1215         Optional<NeutronRouterDpns> neutronRouterDpnsOpt =
1216             MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, routerDpnId);
1217         if (neutronRouterDpnsOpt.isPresent()) {
1218             NeutronRouterDpns neutronRouterDpns = neutronRouterDpnsOpt.get();
1219             for (RouterDpnList routerDpnList : neutronRouterDpns.nonnullRouterDpnList()) {
1220                 if (routerDpnList.getDpnVpninterfacesList() != null) {
1221                     for (DpnVpninterfacesList dpnInterfaceList : routerDpnList.getDpnVpninterfacesList()) {
1222                         if (dpnInterfaceList.getDpnId().equals(dpid)) {
1223                             ret.add(routerDpnList);
1224                         }
1225                     }
1226                 }
1227             }
1228         }
1229         return ret;
1230     }
1231
1232     @Nullable
1233     protected Integer getUniqueRDId(String poolName, String idKey) {
1234         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
1235         try {
1236             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
1237             RpcResult<AllocateIdOutput> rpcResult = result.get();
1238             if (rpcResult.isSuccessful()) {
1239                 return rpcResult.getResult().getIdValue().intValue();
1240             } else {
1241                 LOG.error("RPC call to get unique ID for pool name {} with ID key {} returned with errors {}",
1242                         poolName, idKey, rpcResult.getErrors());
1243             }
1244         } catch (InterruptedException | ExecutionException e) {
1245             LOG.error("Exception when getting Unique Id for poolname {} and ID Key {}", poolName, idKey, e);
1246         }
1247         LOG.error("getUniqueRdId: Failed to return ID for poolname {} and ID Key {}", poolName, idKey);
1248         return null;
1249     }
1250
1251     protected void releaseRDId(String poolName, String idKey) {
1252         ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
1253         try {
1254             RpcResult<ReleaseIdOutput> rpcResult = idManager.releaseId(idInput).get();
1255             if (!rpcResult.isSuccessful()) {
1256                 LOG.error("RPC Call to Get Unique Id returned with errors for poolname {} and ID Key {}: {}",
1257                         poolName, idKey, rpcResult.getErrors());
1258             } else {
1259                 LOG.info("ID {} for RD released successfully", idKey);
1260             }
1261         } catch (InterruptedException | ExecutionException e) {
1262             LOG.error("Exception when trying to release ID for poolname {} and ID Key {}", poolName, idKey, e);
1263         }
1264     }
1265
1266     protected static IpAddress getIpv6LinkLocalAddressFromMac(MacAddress mac) {
1267         byte[] octets = bytesFromHexString(mac.getValue());
1268
1269         /* As per the RFC2373, steps involved to generate a LLA include
1270            1. Convert the 48 bit MAC address to 64 bit value by inserting 0xFFFE
1271               between OUI and NIC Specific part.
1272            2. Invert the Universal/Local flag in the OUI portion of the address.
1273            3. Use the prefix "FE80::/10" along with the above 64 bit Interface
1274               identifier to generate the IPv6 LLA. */
1275
1276         StringBuilder interfaceID = new StringBuilder();
1277         short u8byte = (short) (octets[0] & 0xff);
1278         u8byte ^= 1 << 1;
1279         interfaceID.append(Integer.toHexString(0xFF & u8byte));
1280         interfaceID.append(StringUtils.leftPad(Integer.toHexString(0xFF & octets[1]), 2, "0"));
1281         interfaceID.append(":");
1282         interfaceID.append(Integer.toHexString(0xFF & octets[2]));
1283         interfaceID.append("ff:fe");
1284         interfaceID.append(StringUtils.leftPad(Integer.toHexString(0xFF & octets[3]), 2, "0"));
1285         interfaceID.append(":");
1286         interfaceID.append(Integer.toHexString(0xFF & octets[4]));
1287         interfaceID.append(StringUtils.leftPad(Integer.toHexString(0xFF & octets[5]), 2, "0"));
1288
1289         Ipv6Address ipv6LLA = new Ipv6Address("fe80:0:0:0:" + interfaceID.toString());
1290         IpAddress ipAddress = new IpAddress(ipv6LLA);
1291         return ipAddress;
1292     }
1293
1294     protected static byte[] bytesFromHexString(String values) {
1295         String target = "";
1296         if (values != null) {
1297             target = values;
1298         }
1299         String[] octets = target.split(":");
1300
1301         byte[] ret = new byte[octets.length];
1302         for (int i = 0; i < octets.length; i++) {
1303             ret[i] = Integer.valueOf(octets[i], 16).byteValue();
1304         }
1305         return ret;
1306     }
1307
1308     public List<String> getExistingRDs() {
1309         List<String> existingRDs = new ArrayList<>();
1310         InstanceIdentifier<VpnInstances> path = InstanceIdentifier.builder(VpnInstances.class).build();
1311         Optional<VpnInstances> vpnInstancesOptional = read(LogicalDatastoreType.CONFIGURATION, path);
1312         if (vpnInstancesOptional.isPresent() && vpnInstancesOptional.get().getVpnInstance() != null) {
1313             for (VpnInstance vpnInstance : vpnInstancesOptional.get().getVpnInstance()) {
1314                 if (vpnInstance.getIpv4Family() == null) {
1315                     continue;
1316                 }
1317                 List<String> rds = vpnInstance.getIpv4Family().getRouteDistinguisher();
1318                 if (rds != null) {
1319                     existingRDs.addAll(rds);
1320                 }
1321             }
1322         }
1323         return existingRDs;
1324     }
1325
1326     protected boolean doesVpnExist(Uuid vpnId) {
1327         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap.class,
1328                 new VpnMapKey(vpnId)).build();
1329         return read(LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier).isPresent();
1330     }
1331
1332     protected Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external
1333         .subnets.Subnets> getOptionalExternalSubnets(Uuid subnetId) {
1334         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice
1335             .rev160111.external.subnets.Subnets> subnetsIdentifier =
1336                 InstanceIdentifier.builder(ExternalSubnets.class)
1337                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice
1338                         .rev160111.external.subnets.Subnets.class, new SubnetsKey(subnetId)).build();
1339         return read(LogicalDatastoreType.CONFIGURATION, subnetsIdentifier);
1340     }
1341
1342     public static List<StaticMacEntries> buildStaticMacEntry(Port port) {
1343         PhysAddress physAddress = new PhysAddress(port.getMacAddress().getValue());
1344         List<FixedIps> fixedIps = port.getFixedIps();
1345         IpAddress ipAddress = null;
1346         if (isNotEmpty(fixedIps)) {
1347             ipAddress = port.getFixedIps().get(0).getIpAddress();
1348         }
1349         StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1350         List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1351         if (ipAddress != null) {
1352             staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).setIpPrefix(ipAddress).build());
1353         } else {
1354             staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1355         }
1356         return staticMacEntries;
1357     }
1358
1359     public static boolean isEmpty(Collection<?> collection) {
1360         return collection == null || collection.isEmpty();
1361     }
1362
1363     public static boolean isNotEmpty(Collection<?> collection) {
1364         return !isEmpty(collection);
1365     }
1366
1367     /**
1368      * Method to get an ipVersionChosen as IPV4 and/or IPV6 or undefined from the subnetmaps of the router.
1369      * @param routerUuid the Uuid for which find out the IP version associated
1370      * @return an IpVersionChoice used by the router from its attached subnetmaps. IpVersionChoice.UNDEFINED if any
1371      */
1372     public IpVersionChoice getIpVersionChoicesFromRouterUuid(Uuid routerUuid) {
1373         IpVersionChoice rep = IpVersionChoice.UNDEFINED;
1374         if (routerUuid == null) {
1375             return rep;
1376         }
1377         List<Subnetmap> subnetmapList = getNeutronRouterSubnetMaps(routerUuid);
1378         if (subnetmapList.isEmpty()) {
1379             return rep;
1380         }
1381         for (Subnetmap sn : subnetmapList) {
1382             if (sn.getSubnetIp() != null) {
1383                 IpVersionChoice ipVers = getIpVersionFromString(sn.getSubnetIp());
1384                 if (rep.choice != ipVers.choice) {
1385                     rep = rep.addVersion(ipVers);
1386                 }
1387                 if (rep.choice == IpVersionChoice.IPV4AND6.choice) {
1388                     return rep;
1389                 }
1390             }
1391         }
1392         return rep;
1393     }
1394
1395     /**This method return the list of Subnetmap associated to the router or a empty list if any.
1396      * @param routerId the Uuid of router for which subnetmap is find out
1397      * @return a list of Subnetmap associated to the router. it could be empty if any
1398      */
1399     protected List<Subnetmap> getNeutronRouterSubnetMaps(Uuid routerId) {
1400         List<Subnetmap> subnetIdList = new ArrayList<>();
1401         Optional<Subnetmaps> subnetMaps = read(LogicalDatastoreType.CONFIGURATION,
1402             InstanceIdentifier.builder(Subnetmaps.class).build());
1403         if (subnetMaps.isPresent() && subnetMaps.get().getSubnetmap() != null) {
1404             for (Subnetmap subnetmap : subnetMaps.get().getSubnetmap()) {
1405                 if (routerId.equals(subnetmap.getRouterId())) {
1406                     subnetIdList.add(subnetmap);
1407                 }
1408             }
1409         }
1410         return subnetIdList;
1411     }
1412
1413     static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
1414         .instance.to.vpn.id.VpnInstance> getVpnInstanceToVpnIdIdentifier(String vpnName) {
1415         return InstanceIdentifier.builder(VpnInstanceToVpnId.class)
1416             .child(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
1417                     .instance.to.vpn.id.VpnInstance.class,
1418                 new org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
1419                     .instance.to.vpn.id.VpnInstanceKey(vpnName)).build();
1420     }
1421
1422     /**
1423      * Retrieves the VPN Route Distinguisher searching by its Vpn instance name.
1424      * @param vpnName Name of the VPN
1425      *
1426      * @return the route-distinguisher of the VPN
1427      */
1428     @Nullable
1429     public String getVpnRd(String vpnName) {
1430         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
1431             .instance.to.vpn.id.VpnInstance> id = getVpnInstanceToVpnIdIdentifier(vpnName);
1432         return SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
1433                 LogicalDatastoreType.CONFIGURATION, id).toJavaUtil().map(
1434                 org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id
1435                         .VpnInstance::getVrfId).orElse(null);
1436     }
1437
1438     /**Get IpVersionChoice from String IP like x.x.x.x or an representation IPv6.
1439      * @param ipAddress String of an representation IP address V4 or V6
1440      * @return the IpVersionChoice of the version or IpVersionChoice.UNDEFINED otherwise
1441      */
1442     public static IpVersionChoice getIpVersionFromString(String ipAddress) {
1443         IpVersionChoice ipchoice = IpVersionChoice.UNDEFINED;
1444         if (ipAddress.contains("/")) {
1445             ipAddress = ipAddress.substring(0, ipAddress.indexOf("/"));
1446         }
1447         try {
1448             InetAddress address = InetAddress.getByName(ipAddress);
1449             if (address instanceof Inet4Address) {
1450                 return IpVersionChoice.IPV4;
1451             } else if (address instanceof Inet6Address) {
1452                 return IpVersionChoice.IPV6;
1453             }
1454         } catch (UnknownHostException | SecurityException e) {
1455             LOG.error("getIpVersionFromString: could not  find version for {}", ipAddress);
1456         }
1457         return ipchoice;
1458     }
1459
1460     /**Get IpVersionChoice from Uuid Subnet.
1461      * @param sm Subnetmap structure
1462      * @return the IpVersionChoice of the version or IpVersionChoice.UNDEFINED otherwise
1463      */
1464     public static IpVersionChoice getIpVersionFromSubnet(Subnetmap sm) {
1465         if (sm != null && sm.getSubnetIp() != null) {
1466             return getIpVersionFromString(sm.getSubnetIp());
1467         }
1468         return IpVersionChoice.UNDEFINED;
1469     }
1470
1471     @Nullable
1472     public VpnInstanceOpDataEntry getVpnInstanceOpDataEntryFromVpnId(String vpnName) {
1473         String primaryRd = getVpnRd(vpnName);
1474         if (primaryRd == null) {
1475             LOG.error("getVpnInstanceOpDataEntryFromVpnId: Vpn Instance {} "
1476                      + "Primary RD not found", vpnName);
1477             return null;
1478         }
1479         InstanceIdentifier<VpnInstanceOpDataEntry> id = getVpnOpDataIdentifier(primaryRd);
1480         Optional<VpnInstanceOpDataEntry> vpnInstanceOpDataEntryOptional = read(LogicalDatastoreType.OPERATIONAL, id);
1481         if (!vpnInstanceOpDataEntryOptional.isPresent()) {
1482             LOG.error("getVpnInstanceOpDataEntryFromVpnId: VpnInstance {} not found", primaryRd);
1483             return null;
1484         }
1485         return vpnInstanceOpDataEntryOptional.get();
1486     }
1487
1488     protected InstanceIdentifier<VpnInstanceOpDataEntry> getVpnOpDataIdentifier(String primaryRd) {
1489         return InstanceIdentifier.builder(VpnInstanceOpData.class)
1490                 .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(primaryRd)).build();
1491     }
1492
1493     public boolean shouldVpnHandleIpVersionChoiceChange(IpVersionChoice ipVersion, Uuid routerId, boolean add) {
1494         int subnetCount = -1;
1495         if (ipVersion.isIpVersionChosen(IpVersionChoice.IPV4)) {
1496             subnetCount = getSubnetCountFromRouter(routerId, ipVersion);
1497         } else if (ipVersion.isIpVersionChosen(IpVersionChoice.IPV6)) {
1498             subnetCount = getSubnetCountFromRouter(routerId, ipVersion);
1499         } else {
1500             //Possible value of ipversion choice is either V4 or V6 only. Not accepted V4andV6 and Undefined
1501             return false;
1502         }
1503         /* ADD: Update vpnInstanceOpDataEntry with address family only on first IPv4/IPv6 subnet
1504          * for the VPN Instance.
1505          *
1506          * REMOVE: Update vpnInstanceOpDataEntry with address family only on last IPv4/IPv6 subnet
1507          * for the VPN Instance.
1508          */
1509         if (add && subnetCount == 1) {
1510             return true;
1511         } else if (!add && subnetCount == 0) {
1512             return true;
1513         } else {
1514             return false;
1515         }
1516     }
1517
1518     public boolean shouldVpnHandleIpVersionChangeToRemove(Subnetmap sm, Uuid vpnId) {
1519         if (sm == null) {
1520             return false;
1521         }
1522         InstanceIdentifier<Subnetmaps> subnetMapsId = InstanceIdentifier.builder(Subnetmaps.class).build();
1523         Optional<Subnetmaps> allSubnetMaps = read(LogicalDatastoreType.CONFIGURATION, subnetMapsId);
1524         // calculate and store in list IpVersion for each subnetMap, belonging to current VpnInstance
1525         List<IpVersionChoice> snIpVersions = new ArrayList<>();
1526         for (Subnetmap snMap : allSubnetMaps.get().nonnullSubnetmap()) {
1527             if (snMap.getId().equals(sm.getId())) {
1528                 continue;
1529             }
1530             if (snMap.getVpnId() != null && snMap.getVpnId().equals(vpnId)) {
1531                 snIpVersions.add(getIpVersionFromString(snMap.getSubnetIp()));
1532             }
1533             if (snMap.getInternetVpnId() != null && snMap.getInternetVpnId().equals(vpnId)) {
1534                 snIpVersions.add(getIpVersionFromString(snMap.getSubnetIp()));
1535             }
1536         }
1537         IpVersionChoice ipVersion = getIpVersionFromString(sm.getSubnetIp());
1538         if (!snIpVersions.contains(ipVersion)) {
1539             return true;
1540         }
1541         return false;
1542     }
1543
1544     public int getSubnetCountFromRouter(Uuid routerId, IpVersionChoice ipVer) {
1545         List<Subnetmap> subnetMapList = getNeutronRouterSubnetMapList(routerId);
1546         int subnetCount = 0;
1547         for (Subnetmap subMap : subnetMapList) {
1548             IpVersionChoice ipVersion = getIpVersionFromString(subMap.getSubnetIp());
1549             if (ipVersion.isIpVersionChosen(ipVer)) {
1550                 subnetCount++;
1551             }
1552             if (subnetCount > 1) {
1553                 break;
1554             }
1555         }
1556         return subnetCount;
1557     }
1558
1559     public void updateVpnInstanceWithIpFamily(String vpnName, IpVersionChoice ipVersion, boolean add) {
1560         jobCoordinator.enqueueJob("VPN-" + vpnName, () -> {
1561             VpnInstanceOpDataEntry vpnInstanceOpDataEntry = getVpnInstanceOpDataEntryFromVpnId(vpnName);
1562             if (vpnInstanceOpDataEntry == null) {
1563                 return Collections.emptyList();
1564             }
1565             if (vpnInstanceOpDataEntry.getType() == VpnInstanceOpDataEntry.Type.L2) {
1566                 LOG.debug("updateVpnInstanceWithIpFamily: Update VpnInstance {} with ipFamily {}."
1567                         + "VpnInstanceOpDataEntry is L2 instance. Do nothing.", vpnName, ipVersion);
1568                 return Collections.emptyList();
1569             }
1570             if (ipVersion == IpVersionChoice.UNDEFINED) {
1571                 LOG.debug("updateVpnInstanceWithIpFamily: Update VpnInstance {} with Undefined address family"
1572                         + "is not allowed. Do nothing", vpnName);
1573                 return Collections.emptyList();
1574             }
1575             VpnInstanceOpDataEntryBuilder builder = new VpnInstanceOpDataEntryBuilder(vpnInstanceOpDataEntry);
1576             boolean ipConfigured = add;
1577             if (ipVersion.isIpVersionChosen(IpVersionChoice.IPV4AND6)) {
1578                 builder.setIpv4Configured(ipConfigured);
1579                 builder.setIpv6Configured(ipConfigured);
1580             } else if (ipVersion.isIpVersionChosen(IpVersionChoice.IPV4)) {
1581                 builder.setIpv4Configured(ipConfigured);
1582             } else if (ipVersion.isIpVersionChosen(IpVersionChoice.IPV6)) {
1583                 builder.setIpv6Configured(ipConfigured);
1584             }
1585             return Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
1586                     OPERATIONAL, tx -> {
1587                     InstanceIdentifier<VpnInstanceOpDataEntry> id = InstanceIdentifier
1588                             .builder(VpnInstanceOpData.class).child(VpnInstanceOpDataEntry.class,
1589                                         new VpnInstanceOpDataEntryKey(vpnInstanceOpDataEntry.getVrfId())).build();
1590                     tx.merge(id, builder.build(), false);
1591                     LOG.info("updateVpnInstanceWithIpFamily: Successfully {} {} to Vpn {}",
1592                             add == true ? "added" : "removed", ipVersion, vpnName);
1593                 }));
1594         });
1595     }
1596
1597     /**
1598      * Get the vpnInstance from its Uuid.
1599      *
1600      * @param broker to get informations from ds
1601      * @param vpnId the Uuid of the VPN
1602      * @return the VpnInstance or null if unfindable
1603      */
1604     @Nullable
1605     public VpnInstance getVpnInstance(DataBroker broker, Uuid vpnId) {
1606         if (broker == null || vpnId == null) {
1607             return null;
1608         }
1609         InstanceIdentifier<VpnInstance> id = InstanceIdentifier.builder(VpnInstances.class).child(VpnInstance.class,
1610                 new VpnInstanceKey(vpnId.getValue())).build();
1611         Optional<VpnInstance> vpnInstance = read(LogicalDatastoreType.CONFIGURATION, id);
1612         return vpnInstance.isPresent() ? vpnInstance.get() : null;
1613     }
1614
1615     /**
1616      *Get the Uuid of external network of the router (remember you that one router have only one external network).
1617      * @param routerId the Uuid of the router which you try to reach the external network
1618      * @return Uuid of externalNetwork or null if is not exist
1619      */
1620     protected Uuid getExternalNetworkUuidAttachedFromRouterUuid(@Nonnull Uuid routerId) {
1621         LOG.debug("getExternalNetworkUuidAttachedFromRouterUuid for {}", routerId.getValue());
1622         Uuid externalNetworkUuid = null;
1623         Router router = getNeutronRouter(routerId);
1624         if (router != null && router.getExternalGatewayInfo() != null) {
1625             externalNetworkUuid = router.getExternalGatewayInfo().getExternalNetworkId();
1626         }
1627         return externalNetworkUuid;
1628     }
1629
1630     public Uuid getInternetvpnUuidBoundToRouterId(@Nonnull Uuid routerId) {
1631         Uuid netId = getExternalNetworkUuidAttachedFromRouterUuid(routerId);
1632         if (netId == null) {
1633             return netId;
1634         }
1635         return getVpnForNetwork(netId);
1636     }
1637
1638     /**
1639      * This method get Uuid of internet vpn if existing one bound to the same router of the subnetUuid arg.
1640      * Explanation: If the subnet (of arg subnetUuid) have a router bound and this router have an
1641      * externalVpn (vpn on externalProvider network) then <b>its Uuid</b> will be returned.
1642      * @param subnetUuid Uuid of subnet where you are finding a link to an external network
1643      * @return Uuid of externalVpn or null if it is not found
1644      */
1645     @Nullable
1646     public Uuid getInternetvpnUuidBoundToSubnetRouter(@Nonnull Uuid subnetUuid) {
1647         Subnetmap subnetmap = getSubnetmap(subnetUuid);
1648         Uuid routerUuid = subnetmap.getRouterId();
1649         LOG.debug("getInternetvpnUuidBoundToSubnetRouter for subnetUuid {}", subnetUuid.getValue());
1650         if (routerUuid == null) {
1651             return null;
1652         }
1653         Uuid externalNetworkUuid = getExternalNetworkUuidAttachedFromRouterUuid(routerUuid);
1654         return externalNetworkUuid != null ? getVpnForNetwork(externalNetworkUuid) : null;
1655     }
1656
1657     /**
1658      * Get a list of Private Subnetmap Ids from router to export then its prefixes in Internet VPN.
1659      * @param extNet Provider Network, which has a port attached as external network gateway to router
1660      * @return a list of Private Subnetmap Ids of the router with external network gateway
1661      */
1662     public @Nonnull List<Uuid> getPrivateSubnetsToExport(@Nonnull Network extNet, Uuid internetVpnId) {
1663         List<Uuid> subList = new ArrayList<>();
1664         List<Uuid> rtrList = new ArrayList<>();
1665         if (internetVpnId != null) {
1666             rtrList.addAll(getRouterIdListforVpn(internetVpnId));
1667         } else {
1668             Uuid extNwVpnId = getVpnForNetwork(extNet.getUuid());
1669             rtrList.addAll(getRouterIdListforVpn(extNwVpnId));
1670         }
1671         if (rtrList.isEmpty()) {
1672             return subList;
1673         }
1674         for (Uuid rtrId: rtrList) {
1675             Router router = getNeutronRouter(rtrId);
1676             ExternalGatewayInfo info = router.getExternalGatewayInfo();
1677             if (info == null) {
1678                 LOG.error("getPrivateSubnetsToExport: can not get info about external gateway for router {}",
1679                           router.getUuid().getValue());
1680                 continue;
1681             }
1682             // check that router really has given provider network as its external gateway port
1683             if (!extNet.getUuid().equals(info.getExternalNetworkId())) {
1684                 LOG.error("getPrivateSubnetsToExport: router {} is not attached to given provider network {}",
1685                           router.getUuid().getValue(), extNet.getUuid().getValue());
1686                 continue;
1687             }
1688             subList.addAll(getNeutronRouterSubnetIds(rtrId));
1689         }
1690         return subList;
1691     }
1692
1693     public void updateVpnInstanceWithFallback(Uuid routerId, Uuid vpnName, boolean add) {
1694         VpnInstanceOpDataEntry vpnInstanceOpDataEntry = getVpnInstanceOpDataEntryFromVpnId(vpnName.getValue());
1695         if (vpnInstanceOpDataEntry == null) {
1696             LOG.error("updateVpnInstanceWithFallback: vpnInstanceOpDataEntry not found for vpn {}", vpnName);
1697             return;
1698         }
1699         Long internetBgpVpnId = vpnInstanceOpDataEntry.getVpnId();
1700         List<Uuid> routerIds = new ArrayList<>();
1701         //Handle router specific V6 internet fallback flow else handle all V6 external routers
1702         if (routerId != null) {
1703             routerIds.add(routerId);
1704         } else {
1705             //This block will execute for ext-nw to Internet VPN association/disassociation event.
1706             routerIds = getRouterIdListforVpn(vpnName);
1707         }
1708         if (routerIds == null || routerIds.isEmpty()) {
1709             LOG.error("updateVpnInstanceWithFallback: router not found for vpn {}", vpnName);
1710             return;
1711         }
1712         for (Uuid rtrId: routerIds) {
1713             if (rtrId == null) {
1714                 continue;
1715             }
1716             List<BigInteger> dpnIds = getDpnsForRouter(rtrId.getValue());
1717             if (dpnIds.isEmpty()) {
1718                 continue;
1719             }
1720             VpnInstanceOpDataEntry vpnOpDataEntry = getVpnInstanceOpDataEntryFromVpnId(rtrId.getValue());
1721             Long routerIdAsLong = vpnOpDataEntry.getVpnId();
1722             long vpnId;
1723             Uuid rtrVpnId = getVpnForRouter(rtrId, true);
1724             if (rtrVpnId == null) {
1725                 //If external BGP-VPN is not associated with router then routerId is same as routerVpnId
1726                 vpnId = routerIdAsLong;
1727             } else {
1728                 vpnId = getVpnId(rtrVpnId.getValue());
1729             }
1730             for (BigInteger dpnId : dpnIds) {
1731                 if (add) {
1732                     ipV6InternetDefRt.installDefaultRoute(dpnId, rtrId.getValue(), internetBgpVpnId, vpnId);
1733                 } else {
1734                     ipV6InternetDefRt.removeDefaultRoute(dpnId, rtrId.getValue(), internetBgpVpnId, vpnId);
1735                 }
1736             }
1737         }
1738     }
1739
1740     public void updateVpnInstanceOpWithType(VpnInstanceOpDataEntry.BgpvpnType choice, @Nonnull Uuid vpn) {
1741         String primaryRd = getVpnRd(vpn.getValue());
1742         if (primaryRd == null) {
1743             LOG.debug("updateVpnInstanceOpWithType: Update BgpvpnType {} for {}."
1744                     + "Primary RD not found", choice, vpn.getValue());
1745             return;
1746         }
1747         InstanceIdentifier<VpnInstanceOpDataEntry> id = InstanceIdentifier.builder(VpnInstanceOpData.class)
1748               .child(VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(primaryRd)).build();
1749
1750         Optional<VpnInstanceOpDataEntry> vpnInstanceOpDataEntryOptional =
1751             read(LogicalDatastoreType.OPERATIONAL, id);
1752         if (!vpnInstanceOpDataEntryOptional.isPresent()) {
1753             LOG.debug("updateVpnInstanceOpWithType: Update BgpvpnType {} for {}."
1754                     + "VpnInstanceOpDataEntry not found", choice, vpn.getValue());
1755             return;
1756         }
1757         VpnInstanceOpDataEntry vpnInstanceOpDataEntry = vpnInstanceOpDataEntryOptional.get();
1758         if (vpnInstanceOpDataEntry.getBgpvpnType().equals(choice)) {
1759             LOG.debug("updateVpnInstanceOpWithType: Update BgpvpnType {} for {}."
1760                     + "VpnInstanceOpDataEntry already set", choice, vpn.getValue());
1761             return;
1762         }
1763         VpnInstanceOpDataEntryBuilder builder = new VpnInstanceOpDataEntryBuilder(vpnInstanceOpDataEntry);
1764         builder.setBgpvpnType(choice);
1765         ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1766             tx.merge(id, builder.build(), false);
1767             LOG.debug("updateVpnInstanceOpWithType: sent merge to operDS BgpvpnType {} for {}", choice, vpn.getValue());
1768         }), LOG, "Error updating VPN instance op {} with type {}", vpn, choice);
1769     }
1770
1771     public List<Uuid> getAssociateRouterInputRouterIdsListUuid(List<RouterIds> routerIds) {
1772         if (routerIds == null) {
1773             return Collections.emptyList();
1774         }
1775         return routerIds.stream().map(
1776             routerId -> routerId.getRouterId()).collect(Collectors.toList());
1777     }
1778
1779     public List<Uuid> getDisassociateRouterInputRouterIdsListUuid(List<RouterIds> routerIds) {
1780         if (routerIds == null) {
1781             return Collections.emptyList();
1782         }
1783         return routerIds.stream().map(
1784             routerId -> routerId.getRouterId()).collect(Collectors.toList());
1785     }
1786
1787     public RouterIds getvpnMapRouterIds(Uuid routerId) {
1788         return new RouterIdsBuilder().setRouterId(routerId).build();
1789     }
1790
1791     public void removeVpnMapRouterIdsFromList(Uuid routerId, List<RouterIds> vpnRouterIds) {
1792         Iterator<RouterIds> vpnRouterIdIter = vpnRouterIds.iterator();
1793         while (vpnRouterIdIter.hasNext()) {
1794             RouterIds vpnRouterId = vpnRouterIdIter.next();
1795             if (vpnRouterId.getRouterId().getValue().equals(routerId.getValue())) {
1796                 vpnRouterIdIter.remove();
1797                 return;
1798             }
1799         }
1800         return;
1801     }
1802
1803     public boolean vpnMapRouterIdsContainsRouterId(Uuid routerId, List<RouterIds> vpnRouterIds) {
1804         if (routerId == null) {
1805             return false;
1806         }
1807         return vpnRouterIds.stream().anyMatch(vpnRouterId ->
1808               vpnRouterId.getRouterId().getValue().equals(routerId.getValue()));
1809     }
1810
1811     public List<Uuid> getVpnInstanceRouterIdsListUuid(List<RouterIds> routerIds) {
1812         if (routerIds == null) {
1813             return Collections.emptyList();
1814         }
1815         return routerIds.stream().map(
1816             routerId -> routerId.getRouterId()).collect(Collectors.toList());
1817     }
1818
1819     public static RouterIds getvpnInstanceRouterIds(Uuid routerId) {
1820         return new RouterIdsBuilder().setRouterId(routerId).build();
1821     }
1822
1823     public static List<RouterIds> getVpnInstanceRouterIdsList(List<Uuid> routerIds) {
1824         List<RouterIds> listRouterIds = new ArrayList<>();
1825         for (Uuid routerId : routerIds) {
1826             final RouterIds routerIdInstance = getvpnInstanceRouterIds(routerId);
1827             listRouterIds.add(routerIdInstance);
1828         }
1829         return listRouterIds;
1830     }
1831
1832     @Nonnull
1833     public List<BigInteger> getDpnsForRouter(String routerUuid) {
1834         InstanceIdentifier id = InstanceIdentifier.builder(NeutronRouterDpns.class)
1835             .child(RouterDpnList.class, new RouterDpnListKey(routerUuid)).build();
1836         Optional<RouterDpnList> routerDpnListData =
1837                 SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
1838                         LogicalDatastoreType.OPERATIONAL, id);
1839         List<BigInteger> dpns = new ArrayList<>();
1840         if (routerDpnListData.isPresent()) {
1841             for (DpnVpninterfacesList dpnVpnInterface : routerDpnListData.get().nonnullDpnVpninterfacesList()) {
1842                 dpns.add(dpnVpnInterface.getDpnId());
1843             }
1844         }
1845         return dpns;
1846     }
1847
1848     @Nullable
1849     public List<Uuid> getRouterIdsfromVpnInstance(String vpnName) {
1850         // returns only router, attached to IPv4 networks
1851         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
1852             .child(VpnMap.class, new VpnMapKey(new Uuid(vpnName))).build();
1853         Optional<VpnMap> optionalVpnMap = SingleTransactionDataBroker
1854                 .syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
1855                         LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
1856         if (!optionalVpnMap.isPresent()) {
1857             LOG.error("getRouterIdsfromVpnInstance : Router not found for vpn : {}", vpnName);
1858             return null;
1859         }
1860         List<Uuid> rtrIds = optionalVpnMap.get().getRouterIds().stream().map(routerIds -> routerIds.getRouterId())
1861                 .collect(Collectors.toList());
1862         return rtrIds;
1863
1864     }
1865
1866     public InstanceIdentifier<Router> buildNeutronRouterIdentifier(Uuid routerUuid) {
1867         InstanceIdentifier<Router> routerInstanceIdentifier = InstanceIdentifier.create(Neutron.class)
1868              .child(Routers.class).child(Router.class, new RouterKey(routerUuid));
1869         return routerInstanceIdentifier;
1870     }
1871
1872     @Nullable
1873     List<Subnetmap> getSubnetmapListFromNetworkId(Uuid networkId) {
1874         List<Uuid> subnetIdList = getSubnetIdsFromNetworkId(networkId);
1875         if (subnetIdList != null) {
1876             List<Subnetmap> subnetmapList = new ArrayList<>();
1877             for (Uuid subnetId : subnetIdList) {
1878                 Subnetmap subnetmap = getSubnetmap(subnetId);
1879                 if (subnetmap != null) {
1880                     subnetmapList.add(subnetmap);
1881                 } else {
1882                     LOG.error("getSubnetmapListFromNetworkId: subnetmap is null for subnet {} belonging to network {}",
1883                             subnetId.getValue(), networkId.getValue());
1884                 }
1885             }
1886             return subnetmapList;
1887         }
1888         LOG.error("getSubnetmapListFromNetworkId: Failed as subnetIdList is null for network {}",
1889                 networkId.getValue());
1890         return null;
1891     }
1892
1893     @Nullable
1894     public long getVpnId(String vpnName) {
1895         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn
1896                 .instance.to.vpn.id.VpnInstance> id = getVpnInstanceToVpnIdIdentifier(vpnName);
1897         return SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
1898                 LogicalDatastoreType.CONFIGURATION, id).toJavaUtil().map(
1899                 org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id
1900                         .VpnInstance::getVpnId).orElse(null);
1901     }
1902
1903     protected boolean isV6SubnetPartOfRouter(Uuid routerId) {
1904         List<Subnetmap> subnetList = getNeutronRouterSubnetMapList(routerId);
1905         for (Subnetmap sm : subnetList) {
1906             if (sm == null) {
1907                 continue;
1908             }
1909             IpVersionChoice ipVers = getIpVersionFromString(sm.getSubnetIp());
1910             //skip further subnet processing once found first V6 subnet for the router
1911             if (ipVers.isIpVersionChosen(IpVersionChoice.IPV6)) {
1912                 return true;
1913             }
1914         }
1915         return false;
1916     }
1917
1918     @SuppressWarnings({ "unchecked", "rawtypes" })
1919     public <T extends DataObject> void asyncReadAndExecute(final LogicalDatastoreType datastoreType,
1920                                                            final InstanceIdentifier<T> iid, final String jobKey,
1921                                                            final Function<Optional<T>, Void> function) {
1922         jobCoordinator.enqueueJob(jobKey, () -> {
1923             SettableFuture<Optional<T>> settableFuture = SettableFuture.create();
1924             List futures = Collections.singletonList(settableFuture);
1925             try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1926                 Futures.addCallback(tx.read(datastoreType, iid),
1927                         new SettableFutureCallback<Optional<T>>(settableFuture) {
1928                             @Override
1929                             public void onSuccess(Optional<T> data) {
1930                                 function.apply(data);
1931                                 super.onSuccess(data);
1932                             }
1933                         }, MoreExecutors.directExecutor());
1934
1935                 return futures;
1936             }
1937         }, JOB_MAX_RETRIES);
1938     }
1939
1940     private class SettableFutureCallback<T> implements FutureCallback<T> {
1941
1942         private final SettableFuture<T> settableFuture;
1943
1944         SettableFutureCallback(SettableFuture<T> settableFuture) {
1945             this.settableFuture = settableFuture;
1946         }
1947
1948         @Override
1949         public void onSuccess(T objT) {
1950             settableFuture.set(objT);
1951         }
1952
1953         @Override
1954         public void onFailure(Throwable throwable) {
1955             settableFuture.setException(throwable);
1956         }
1957     }
1958 }
1959