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