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