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