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