Optimize the method in AclServiceUtils.java
[netvirt.git] / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / utils / AclServiceUtils.java
1 /*
2  * Copyright (c) 2016, 2018 Red Hat, Inc. 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.aclservice.utils;
10
11 import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
12 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
13 import static org.opendaylight.genius.infra.Datastore.OPERATIONAL;
14
15 import com.google.common.base.Optional;
16 import com.google.common.collect.Lists;
17 import com.google.common.net.InetAddresses;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import java.math.BigInteger;
20 import java.net.InetAddress;
21 import java.net.UnknownHostException;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Objects;
29 import java.util.Set;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.Future;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
38 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
41 import org.opendaylight.genius.infra.Datastore.Operational;
42 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
43 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
44 import org.opendaylight.genius.infra.TypedWriteTransaction;
45 import org.opendaylight.genius.mdsalutil.ActionInfo;
46 import org.opendaylight.genius.mdsalutil.InstructionInfo;
47 import org.opendaylight.genius.mdsalutil.MDSALUtil;
48 import org.opendaylight.genius.mdsalutil.MatchInfoBase;
49 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
50 import org.opendaylight.genius.mdsalutil.NwConstants;
51 import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack;
52 import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack.NxCtAction;
53 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
54 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
55 import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
56 import org.opendaylight.genius.mdsalutil.matches.MatchArpSpa;
57 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
58 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
59 import org.opendaylight.genius.mdsalutil.matches.MatchIcmpv6;
60 import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
61 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
62 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source;
63 import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Destination;
64 import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Source;
65 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
66 import org.opendaylight.genius.mdsalutil.matches.MatchUdpDestinationPort;
67 import org.opendaylight.genius.mdsalutil.matches.MatchUdpSourcePort;
68 import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchRegister;
69 import org.opendaylight.genius.mdsalutil.packet.IPProtocols;
70 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
71 import org.opendaylight.netvirt.aclservice.api.AclServiceManager.MatchCriteria;
72 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntries;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolOutput;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInput;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInputBuilder;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolOutput;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdOutput;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.config.rev160806.AclserviceConfig;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.AclPortsLookup;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddress;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddressBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpVersionV6;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.AclPortsByIp;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.AclPortsByIpKey;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.AclIpPrefixes;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.AclIpPrefixesKey;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIds;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIdsBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIdsKey;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.SubnetInfo;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.serviceutils.srm.types.rev180626.NetvirtAcl;
141 import org.opendaylight.yangtools.yang.binding.DataObject;
142 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
143 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
144 import org.opendaylight.yangtools.yang.common.RpcResult;
145 import org.opendaylight.yangtools.yang.common.Uint64;
146 import org.slf4j.Logger;
147 import org.slf4j.LoggerFactory;
148
149 @Singleton
150 public final class AclServiceUtils {
151
152     private static final Logger LOG = LoggerFactory.getLogger(AclServiceUtils.class);
153
154     private final DataBroker dataBroker;
155     private final ManagedNewTransactionRunner txRunner;
156     private final AclDataUtil aclDataUtil;
157     private final AclserviceConfig config;
158     private final IdManagerService idManager;
159     private final JobCoordinator jobCoordinator;
160
161     @Inject
162     public AclServiceUtils(DataBroker dataBroker, AclDataUtil aclDataUtil, AclserviceConfig config,
163             IdManagerService idManager, JobCoordinator jobCoordinator) {
164         this.dataBroker = dataBroker;
165         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
166         this.aclDataUtil = aclDataUtil;
167         this.config = config;
168         this.idManager = idManager;
169         this.jobCoordinator = jobCoordinator;
170     }
171
172     /**
173      * Retrieves the Interface from the datastore.
174      * @param broker the data broker
175      * @param interfaceName the interface name
176      * @return the interface.
177      */
178     public static Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
179         .Interface> getInterface(DataBroker broker, String interfaceName) {
180         return read(broker, LogicalDatastoreType.CONFIGURATION, getInterfaceIdentifier(interfaceName));
181     }
182
183     /**
184      * Builds the interface identifier.
185      * @param interfaceName the interface name.
186      * @return the interface identifier.
187      */
188     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
189         .interfaces.Interface> getInterfaceIdentifier(String interfaceName) {
190         return InstanceIdentifier.builder(Interfaces.class)
191                 .child(
192                     org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
193                     .Interface.class, new InterfaceKey(interfaceName)).build();
194     }
195
196     /**
197      * Retrieves the object from the datastore.
198      * @param broker the data broker.
199      * @param datastoreType the data store type.
200      * @param path the wild card path.
201      * @param <T> type of DataObject
202      * @return the required object.
203      */
204     public static <T extends DataObject> Optional<T> read(
205             DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
206         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
207             return tx.read(datastoreType, path).checkedGet();
208         } catch (ReadFailedException e) {
209             LOG.error("Failed to read InstanceIdentifier {} from {}", path, datastoreType, e);
210             return Optional.absent();
211         }
212     }
213
214     /**
215      * Retrieves the interface state.
216      * @param dataBroker the data broker.
217      * @param interfaceName the interface name.
218      * @return the interface state.
219      */
220     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
221         .@Nullable Interface getInterfaceStateFromOperDS(DataBroker dataBroker, String interfaceName) {
222         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
223             .interfaces.state.Interface> ifStateId = buildStateInterfaceId(interfaceName);
224         return MDSALUtil.read(LogicalDatastoreType.OPERATIONAL, ifStateId, dataBroker).orNull();
225     }
226
227     /**
228      * Build the interface state.
229      * @param interfaceName the interface name.
230      * @return the interface state.
231      */
232     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
233         .interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
234         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
235             .interfaces.state.Interface> idBuilder = InstanceIdentifier.builder(InterfacesState.class)
236             .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
237             .state.Interface.class, new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
238             .rev140508.interfaces.state.InterfaceKey(interfaceName));
239         return idBuilder.build();
240     }
241
242     /**
243      * Retrieves the security rule attribute augmentation from the access list.
244      * @param ace the access list entry
245      * @return the security rule attributes
246      */
247     @Nullable
248     public static SecurityRuleAttr getAccessListAttributes(Ace ace) {
249         if (ace == null) {
250             return null;
251         }
252         SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
253         if (aceAttributes == null) {
254             return null;
255         }
256         return aceAttributes;
257     }
258
259     /**
260      * Returns the DHCP match.
261      *
262      * @param srcPort the source port.
263      * @param dstPort the destination port.
264      * @param lportTag the lport tag
265      * @param serviceMode ingress or egress service
266      * @return list of matches.
267      */
268     public static List<MatchInfoBase> buildDhcpMatches(int srcPort, int dstPort, int lportTag,
269             Class<? extends ServiceModeBase> serviceMode) {
270         List<MatchInfoBase> matches = new ArrayList<>(5);
271         matches.add(MatchEthernetType.IPV4);
272         matches.add(MatchIpProtocol.UDP);
273         matches.add(new MatchUdpDestinationPort(dstPort));
274         matches.add(new MatchUdpSourcePort(srcPort));
275         matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
276         return matches;
277     }
278
279     /**
280      * Returns the DHCPv6 match.
281      *
282      * @param srcPort the source port.
283      * @param dstPort the destination port.
284      * @param lportTag the lport tag
285      * @param serviceMode ingress or egress
286      * @return list of matches.
287      */
288     public static List<MatchInfoBase> buildDhcpV6Matches(int srcPort, int dstPort, int lportTag,
289             Class<? extends ServiceModeBase> serviceMode) {
290         List<MatchInfoBase> matches = new ArrayList<>(6);
291         matches.add(MatchEthernetType.IPV6);
292         matches.add(MatchIpProtocol.UDP);
293         matches.add(new MatchUdpDestinationPort(dstPort));
294         matches.add(new MatchUdpSourcePort(srcPort));
295         matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
296         return matches;
297     }
298
299     /**
300      * Returns the ICMPv6 match.
301      *
302      * @param icmpType the icmpv6-type.
303      * @param icmpCode the icmpv6-code.
304      * @param lportTag the lport tag
305      * @param serviceMode ingress or egress
306      * @return list of matches.
307      */
308     public static List<MatchInfoBase> buildIcmpV6Matches(int icmpType, int icmpCode, int lportTag,
309             Class<? extends ServiceModeBase> serviceMode) {
310         List<MatchInfoBase> matches = new ArrayList<>();
311         matches.add(MatchEthernetType.IPV6);
312         matches.add(MatchIpProtocol.ICMPV6);
313         if (icmpType != 0) {
314             matches.add(new MatchIcmpv6((short) icmpType, (short) icmpCode));
315         }
316         matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
317         return matches;
318     }
319
320     public static List<MatchInfoBase> buildBroadcastIpV4Matches(String ipAddr) {
321         List<MatchInfoBase> matches = new ArrayList<>(2);
322         matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
323         matches.addAll(AclServiceUtils.buildIpMatches(IpPrefixOrAddressBuilder.getDefaultInstance(ipAddr),
324                 MatchCriteria.MATCH_DESTINATION));
325         return matches;
326     }
327
328     public static List<MatchInfoBase> buildL2BroadcastMatches() {
329         List<MatchInfoBase> matches = new ArrayList<>();
330         matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
331         return matches;
332     }
333
334     /**
335      * Builds the service id.
336      *
337      * @param interfaceName the interface name
338      * @param serviceIndex the service index
339      * @param serviceMode the service mode
340      * @return the instance identifier
341      */
342     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex,
343             Class<? extends ServiceModeBase> serviceMode) {
344         return InstanceIdentifier.builder(ServiceBindings.class)
345                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, serviceMode))
346                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
347     }
348
349     /**
350      * Gets the bound services.
351      *
352      * @param serviceName the service name
353      * @param servicePriority the service priority
354      * @param flowPriority the flow priority
355      * @param cookie the cookie
356      * @param instructions the instructions
357      * @return the bound services
358      */
359     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
360             Uint64 cookie, List<Instruction> instructions) {
361         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
362                 .setInstruction(instructions);
363         return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
364                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
365                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
366     }
367
368     public static List<Uuid> getUpdatedAclList(List<Uuid> updatedAclList, List<Uuid> currentAclList) {
369         if (updatedAclList == null) {
370             return Collections.emptyList();
371         }
372         List<Uuid> newAclList = new ArrayList<>(updatedAclList);
373         if (currentAclList == null) {
374             return newAclList;
375         }
376         List<Uuid> origAclList = new ArrayList<>(currentAclList);
377         newAclList.removeAll(origAclList);
378         return newAclList;
379     }
380
381     public static List<AllowedAddressPairs> getUpdatedAllowedAddressPairs(
382             @Nullable List<AllowedAddressPairs> updatedAllowedAddressPairs,
383             @Nullable List<AllowedAddressPairs> currentAllowedAddressPairs) {
384         if (updatedAllowedAddressPairs == null) {
385             return Collections.emptyList();
386         }
387         List<AllowedAddressPairs> newAllowedAddressPairs = new ArrayList<>(updatedAllowedAddressPairs);
388         if (currentAllowedAddressPairs == null) {
389             return newAllowedAddressPairs;
390         }
391         List<AllowedAddressPairs> origAllowedAddressPairs = new ArrayList<>(currentAllowedAddressPairs);
392         for (Iterator<AllowedAddressPairs> iterator = newAllowedAddressPairs.iterator(); iterator.hasNext();) {
393             AllowedAddressPairs updatedAllowedAddressPair = iterator.next();
394             for (AllowedAddressPairs currentAllowedAddressPair : origAllowedAddressPairs) {
395                 if (updatedAllowedAddressPair.key().equals(currentAllowedAddressPair.key())) {
396                     iterator.remove();
397                     break;
398                 }
399             }
400         }
401         return newAllowedAddressPairs;
402     }
403
404     @Nullable
405     public static BigInteger getDpIdFromIterfaceState(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
406             .interfaces.rev140508.interfaces.state.Interface interfaceState) {
407         BigInteger dpId = null;
408         List<String> ofportIds = interfaceState.getLowerLayerIf();
409         if (ofportIds != null && !ofportIds.isEmpty()) {
410             NodeConnectorId nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
411             dpId = BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
412         }
413         return dpId;
414     }
415
416     public static List<String> getIpBroadcastAddresses(List<SubnetInfo> subnetInfoList) {
417         List<String> ipBroadcastAddresses = new ArrayList<>();
418         for (SubnetInfo subnetInfo : subnetInfoList) {
419             IpPrefix cidrIpPrefix = subnetInfo.getIpPrefix().getIpPrefix();
420             if (cidrIpPrefix != null) {
421                 Ipv4Prefix cidrIpv4Prefix = cidrIpPrefix.getIpv4Prefix();
422                 if (cidrIpv4Prefix != null) {
423                     ipBroadcastAddresses.add(getBroadcastAddressFromCidr(cidrIpv4Prefix.getValue()));
424                 }
425             }
426         }
427         return ipBroadcastAddresses;
428     }
429
430     public static String getBroadcastAddressFromCidr(String cidr) {
431         String[] ipaddressValues = cidr.split("/");
432         int address = InetAddresses.coerceToInteger(InetAddresses.forString(ipaddressValues[0]));
433         int cidrPart = Integer.parseInt(ipaddressValues[1]);
434         int netmask = 0;
435         for (int j = 0; j < cidrPart; ++j) {
436             netmask |= 1 << 31 - j;
437         }
438         int network = address & netmask;
439         int broadcast = network | ~netmask;
440         return InetAddresses.toAddrString(InetAddresses.fromInteger(broadcast));
441     }
442
443     /**
444      * Builds the ip matches.
445      *
446      * @param ipPrefixOrAddress the ip prefix or address
447      * @param matchCriteria the source_ip or destination_ip used for the match
448      * @return the list
449      */
450     public static List<MatchInfoBase> buildIpMatches(IpPrefixOrAddress ipPrefixOrAddress,
451                                                      MatchCriteria matchCriteria) {
452         List<MatchInfoBase> flowMatches = new ArrayList<>();
453         IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
454         if (ipPrefix != null) {
455             Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
456             if (ipv4Prefix != null) {
457                 flowMatches.add(MatchEthernetType.IPV4);
458                 if (!ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
459                     flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(ipv4Prefix)
460                             : new MatchIpv4Destination(ipv4Prefix));
461                 }
462             } else {
463                 flowMatches.add(MatchEthernetType.IPV6);
464                 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
465                         ipPrefix.getIpv6Prefix()) : new MatchIpv6Destination(ipPrefix.getIpv6Prefix()));
466             }
467         } else {
468             IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
469             if (ipAddress.getIpv4Address() != null) {
470                 flowMatches.add(MatchEthernetType.IPV4);
471                 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(
472                         ipAddress.getIpv4Address().getValue(), "32") : new MatchIpv4Destination(
473                         ipAddress.getIpv4Address().getValue(), "32"));
474             } else {
475                 flowMatches.add(MatchEthernetType.IPV6);
476                 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
477                         ipAddress.getIpv6Address().getValue() + "/128") : new MatchIpv6Destination(
478                         ipAddress.getIpv6Address().getValue() + "/128"));
479             }
480         }
481         return flowMatches;
482     }
483
484     /**
485      * Builds the arp ip matches.
486      * @param ipPrefixOrAddress the ip prefix or address
487      * @return the MatchInfoBase list
488      */
489     public static List<MatchInfoBase> buildArpIpMatches(IpPrefixOrAddress ipPrefixOrAddress) {
490         List<MatchInfoBase> flowMatches = new ArrayList<>();
491         IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
492         if (ipPrefix != null) {
493             Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
494             if (ipv4Prefix != null && !ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
495                 flowMatches.add(new MatchArpSpa(ipv4Prefix));
496             }
497         } else {
498             IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
499             if (ipAddress != null && ipAddress.getIpv4Address() != null) {
500                 flowMatches.add(new MatchArpSpa(ipAddress.getIpv4Address().getValue(), "32"));
501             }
502         }
503         return flowMatches;
504     }
505
506     public static MatchInfoBase buildRemoteAclTagMetadataMatch(Integer remoteAclTag) {
507         return new MatchMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
508                 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
509     }
510
511     public static Uint64 getRemoteAclTagMetadata(BigInteger remoteAclTag) {
512         return Uint64.valueOf(remoteAclTag.shiftLeft(4));
513     }
514
515     public static Uint64 getDropFlowCookie(int lport) {
516         return Uint64.fromLongBits(MetaDataUtil.getLportTagMetaData(lport).longValue()
517                    | AclConstants.COOKIE_ACL_DROP_FLOW.longValue());
518     }
519
520     /**
521      * Does IPv4 address exists in the list of allowed address pair.
522      *
523      * @param aaps the allowed address pairs
524      * @return true, if successful
525      */
526     public static boolean doesIpv4AddressExists(List<AllowedAddressPairs> aaps) {
527         if (aaps == null) {
528             return false;
529         }
530         for (AllowedAddressPairs aap : aaps) {
531             IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
532             IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
533             if (ipPrefix != null) {
534                 if (ipPrefix.getIpv4Prefix() != null) {
535                     return true;
536                 }
537             } else {
538                 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
539                 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
540                     return true;
541                 }
542             }
543         }
544         return false;
545     }
546
547     /**
548      * Does IPv6 address exists in the list of allowed address pair.
549      *
550      * @param aaps the allowed address pairs
551      * @return true, if successful
552      */
553     public static boolean doesIpv6AddressExists(List<AllowedAddressPairs> aaps) {
554         if (aaps == null) {
555             return false;
556         }
557         for (AllowedAddressPairs aap : aaps) {
558             IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
559             IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
560             if (ipPrefix != null) {
561                 if (ipPrefix.getIpv6Prefix() != null) {
562                     return true;
563                 }
564             } else {
565                 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
566                 if (ipAddress != null && ipAddress.getIpv6Address() != null) {
567                     return true;
568                 }
569             }
570         }
571         return false;
572     }
573
574     /**
575      * Gets the lport tag match.
576      * Ingress match is based on metadata and egress match is based on masked reg6
577      *
578      * @param lportTag the lport tag
579      * @param serviceMode ingress or egress service mode
580      * @return the lport tag match
581      */
582     public static MatchInfoBase buildLPortTagMatch(int lportTag, Class<? extends ServiceModeBase> serviceMode) {
583         if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
584             return new NxMatchRegister(NxmNxReg6.class, MetaDataUtil.getLportTagForReg6(lportTag).longValue(),
585                     MetaDataUtil.getLportTagMaskForReg6());
586         } else {
587             return new MatchMetadata(MetaDataUtil.getLportTagMetaData(lportTag), MetaDataUtil.METADATA_MASK_LPORT_TAG);
588         }
589     }
590
591     public static List<MatchInfoBase> buildMatchesForLPortTagAndRemoteAclTag(Integer lportTag, Integer remoteAclTag,
592             Class<? extends ServiceModeBase> serviceMode) {
593         List<MatchInfoBase> matches = new ArrayList<>();
594         if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
595             matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
596             matches.add(AclServiceUtils.buildRemoteAclTagMetadataMatch(remoteAclTag));
597         } else {
598             // In case of ingress service mode, only metadata is used for
599             // matching both lportTag and aclTag. Hence performing "or"
600             // operation on both lportTag and aclTag metadata.
601             Uint64 metaData = Uint64.fromLongBits(MetaDataUtil.getLportTagMetaData(lportTag).longValue()
602                     | (getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)).longValue()));
603             Uint64 metaDataMask = Uint64.fromLongBits(MetaDataUtil.METADATA_MASK_LPORT_TAG.longValue()
604                     | MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG.longValue());
605             matches.add(new MatchMetadata(metaData, metaDataMask));
606         }
607         return matches;
608     }
609
610     public static Collection<? extends MatchInfoBase> buildMatchesForLPortTagAndConntrackClassifierType(int lportTag,
611             AclConntrackClassifierType conntrackClassifierType, Class<? extends ServiceModeBase> serviceMode) {
612         List<MatchInfoBase> matches = new ArrayList<>();
613         if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
614             matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
615             matches.add(AclServiceUtils.buildAclConntrackClassifierTypeMatch(conntrackClassifierType));
616         } else {
617             // In case of ingress service mode, only metadata is used for
618             // matching both lportTag and conntrackClassifierType. Hence performing "or"
619             // operation on both lportTag and conntrackClassifierType metadata.
620             Uint64 metaData = Uint64.fromLongBits(MetaDataUtil.getLportTagMetaData(lportTag).longValue()
621                     | (MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(
622                        Uint64.valueOf(conntrackClassifierType.getValue()))).longValue());
623             Uint64 metaDataMask = Uint64.fromLongBits(MetaDataUtil.METADATA_MASK_LPORT_TAG.longValue()
624                    | MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE.longValue());
625             matches.add(new MatchMetadata(metaData, metaDataMask));
626         }
627         return matches;
628     }
629
630     public static InstructionWriteMetadata getWriteMetadataForAclClassifierType(
631             AclConntrackClassifierType conntrackClassifierType) {
632         return new InstructionWriteMetadata(MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(
633                 Uint64.valueOf(conntrackClassifierType.getValue())),
634                 MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
635     }
636
637     public static InstructionWriteMetadata getWriteMetadataForDropFlag() {
638         return new InstructionWriteMetadata(MetaDataUtil.getAclDropMetaData(AclConstants.METADATA_DROP_FLAG),
639                 MetaDataUtil.METADATA_MASK_ACL_DROP);
640     }
641
642     public static InstructionWriteMetadata getWriteMetadataForRemoteAclTag(Integer remoteAclTag) {
643         return new InstructionWriteMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
644                 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
645     }
646
647     public static MatchInfoBase buildAclConntrackClassifierTypeMatch(
648             AclConntrackClassifierType conntrackSupportedType) {
649         return new MatchMetadata(
650                 MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(
651                     Uint64.valueOf(conntrackSupportedType.getValue())),
652                     MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
653     }
654
655     public AclserviceConfig getConfig() {
656         return config;
657     }
658
659     public static boolean isIPv4Address(AllowedAddressPairs aap) {
660         IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
661         IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
662         if (ipPrefix != null) {
663             if (ipPrefix.getIpv4Prefix() != null) {
664                 return true;
665             }
666         } else {
667             IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
668             if (ipAddress != null && ipAddress.getIpv4Address() != null) {
669                 return true;
670             }
671         }
672         return false;
673     }
674
675     public static boolean isNotIpv4AllNetwork(AllowedAddressPairs aap) {
676         IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
677         if (ipPrefix != null && ipPrefix.getIpv4Prefix() != null
678                 && ipPrefix.getIpv4Prefix().getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
679             return false;
680         }
681         return true;
682     }
683
684     protected static boolean isNotIpv6AllNetwork(AllowedAddressPairs aap) {
685         IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
686         if (ipPrefix != null && ipPrefix.getIpv6Prefix() != null
687                 && ipPrefix.getIpv6Prefix().getValue().equals(AclConstants.IPV6_ALL_NETWORK)) {
688             return false;
689         }
690         return true;
691     }
692
693     public static boolean isNotIpAllNetwork(AllowedAddressPairs aap) {
694         return isNotIpv4AllNetwork(aap) && isNotIpv6AllNetwork(aap);
695     }
696
697     @Nullable
698     public static Long getElanIdFromInterface(String elanInterfaceName, DataBroker broker) {
699         ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(elanInterfaceName, broker);
700         if (null != elanInterface) {
701             ElanInstance elanInfo = getElanInstanceByName(elanInterface.getElanInstanceName(), broker);
702             return elanInfo != null ? elanInfo.getElanTag().toJava() : null;
703         }
704         return null;
705     }
706
707     @Nullable
708     public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName,DataBroker broker) {
709         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
710         return read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
711     }
712
713     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
714         return InstanceIdentifier.builder(ElanInterfaces.class)
715                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
716     }
717
718     // elan-instances config container
719     @Nullable
720     public static ElanInstance getElanInstanceByName(String elanInstanceName, DataBroker broker) {
721         InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
722         return read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
723     }
724
725     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
726         return InstanceIdentifier.builder(ElanInstances.class)
727                 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
728     }
729
730     public void deleteAcesFromConfigDS(String aclName, List<Ace> deletedAceRules) {
731         List<List<Ace>> acesParts = Lists.partition(deletedAceRules, AclConstants.ACES_PER_TRANSACTION);
732         for (List<Ace> acePart : acesParts) {
733             jobCoordinator.enqueueJob(aclName,
734                 () -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
735                     tx -> {
736                         for (Ace ace: acePart) {
737                             InstanceIdentifier<Ace> id = InstanceIdentifier.builder(AccessLists.class)
738                                     .child(Acl.class, new AclKey(aclName, Ipv4Acl.class)).child(AccessListEntries.class)
739                                     .child(Ace.class, ace.key()).build();
740                             tx.delete(id);
741                         }
742                     })), AclConstants.ACEDELETE_MAX_RETRIES);
743         }
744     }
745
746     public static Integer allocateId(IdManagerService idManager, String poolName, String idKey, Integer defaultId) {
747         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
748         try {
749             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
750             RpcResult<AllocateIdOutput> rpcResult = result.get();
751             if (rpcResult.isSuccessful()) {
752                 Integer allocatedId = rpcResult.getResult().getIdValue().intValue();
753                 LOG.debug("Allocated ACL ID: {} with key: {} into pool: {}", allocatedId, idKey, poolName);
754                 return allocatedId;
755             } else {
756                 LOG.error("RPC Call to Get Unique Id for key {} from pool {} returned with Errors {}",
757                         idKey, poolName, rpcResult.getErrors());
758             }
759         } catch (InterruptedException | ExecutionException e) {
760             LOG.error("Exception when getting Unique Id for key {} from pool {} ", idKey, poolName, e);
761         }
762         return defaultId;
763     }
764
765     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
766         ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
767         try {
768             RpcResult<ReleaseIdOutput> rpcResult = idManager.releaseId(idInput).get();
769             if (!rpcResult.isSuccessful()) {
770                 LOG.error("RPC Call to release Id with Key {} from pool {} returned with Errors {}",
771                         idKey, poolName, rpcResult.getErrors());
772             } else {
773                 LOG.debug("Released ACL ID with key: {} from pool: {}", idKey, poolName);
774             }
775         } catch (InterruptedException | ExecutionException e) {
776             LOG.error("Exception when releasing Id for key {} from pool {} ", idKey, poolName, e);
777         }
778     }
779
780     /**
781      * Gets the ACL tag from cache. If not found in cache, tries to allocate and
782      * return the value.
783      *
784      * @param aclId the acl id
785      * @return the acl tag
786      */
787     @Nullable
788     public Integer getAclTag(final Uuid aclId) {
789         String aclName = aclId.getValue();
790         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
791         if (aclTag == null) {
792             LOG.debug("ACL tag not found in cache for ACL={}, trying to allocate again.", aclName);
793             aclTag = allocateAclTag(aclName);
794             if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
795                 this.aclDataUtil.addAclTag(aclName, aclTag);
796             }
797         }
798         return aclTag;
799     }
800
801     /**
802      * Allocate ACL tag.
803      *
804      * @param aclName the ACL name
805      * @return the integer
806      */
807     public Integer allocateAclTag(String aclName) {
808         return AclServiceUtils.allocateId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName,
809                                           AclConstants.INVALID_ACL_TAG);
810     }
811
812     /**
813      * Release ACL tag.
814      *
815      * @param aclName the ACL name
816      */
817     public void releaseAclTag(String aclName) {
818         AclServiceUtils.releaseId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName);
819     }
820
821     /**
822      * Indicates whether the interface has port security enabled or interface is DHCP service port.
823      *
824      * @param aclInterface the interface.
825      * @return true if port is security enabled or is a DHCP service port.
826      */
827     public static boolean isOfInterest(AclInterface aclInterface) {
828         return aclInterface != null && (aclInterface.isPortSecurityEnabled()
829                 || aclInterface.getInterfaceType() == InterfaceAcl.InterfaceType.DhcpService);
830     }
831
832     /**
833      * Indicates whether the interface has port security enabled or interface is DHCP service port.
834      *
835      * @param aclInterface the interface.
836      * @return true if port is security enabled or is a DHCP service port.
837      */
838     public static boolean isOfInterest(InterfaceAcl aclInterface) {
839         return aclInterface != null && (aclInterface.isPortSecurityEnabled()
840                 || aclInterface.getInterfaceType() == InterfaceAcl.InterfaceType.DhcpService);
841     }
842
843     /**
844      * Creates the id pool for ACL tag.
845      *
846      * @param poolName the pool name
847      */
848     private void createIdPoolForAclTag(String poolName) {
849         CreateIdPoolInput createPool = new CreateIdPoolInputBuilder()
850                 .setPoolName(poolName).setLow(AclConstants.ACL_TAG_POOL_START)
851                 .setHigh(AclConstants.ACL_TAG_POOL_END).build();
852         try {
853             Future<RpcResult<CreateIdPoolOutput>> result = this.idManager.createIdPool(createPool);
854             if (result != null && result.get().isSuccessful()) {
855                 LOG.debug("Created IdPool for {}", poolName);
856             }
857         } catch (InterruptedException | ExecutionException e) {
858             LOG.error("Failed to create ID pool [{}] for remote ACL ids", poolName, e);
859             throw new RuntimeException("Failed to create ID pool [{}] for remote ACL ids", e);
860         }
861     }
862
863     /**
864      * Delete id pool.
865      *
866      * @param poolName the pool name
867      */
868     public void deleteIdPool(String poolName) {
869         DeleteIdPoolInput deletePool = new DeleteIdPoolInputBuilder().setPoolName(poolName).build();
870         try {
871             Future<RpcResult<DeleteIdPoolOutput>> result = this.idManager.deleteIdPool(deletePool);
872             if (result != null && result.get().isSuccessful()) {
873                 LOG.debug("Deleted IdPool for {}", poolName);
874             }
875         } catch (InterruptedException | ExecutionException e) {
876             LOG.error("Failed to delete ID pool [{}]", poolName, e);
877             throw new RuntimeException("Failed to delete ID pool [" + poolName + "]", e);
878         }
879     }
880
881     /**
882      * Creates remote the acl id pools.
883      */
884     public void createRemoteAclIdPool() {
885         createIdPoolForAclTag(AclConstants.ACL_TAG_POOL_NAME);
886     }
887
888     /**
889      * Delete remote the acl id pools.
890      */
891     public void deleteRemoteAclIdPool() {
892         deleteIdPool(AclConstants.ACL_TAG_POOL_NAME);
893     }
894
895     public static List<? extends MatchInfoBase> buildIpAndSrcServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
896         List<MatchInfoBase> flowMatches = new ArrayList<>();
897         flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
898         if (aap.getIpAddress().getIpAddress() != null) {
899             if (aap.getIpAddress().getIpAddress().getIpv4Address() != null) {
900                 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
901                 flowMatches.add(ipv4EthMatch);
902                 MatchIpv4Source srcMatch = new MatchIpv4Source(
903                         new Ipv4Prefix(aap.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
904                 flowMatches.add(srcMatch);
905             } else if (aap.getIpAddress().getIpAddress().getIpv6Address() != null) {
906                 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
907                 flowMatches.add(ipv6EthMatch);
908                 MatchIpv6Source srcMatch = new MatchIpv6Source(
909                         new Ipv6Prefix(aap.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
910                 flowMatches.add(srcMatch);
911             }
912         } else if (aap.getIpAddress().getIpPrefix() != null) {
913             if (aap.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
914                 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
915                 flowMatches.add(ipv4EthMatch);
916                 MatchIpv4Source srcMatch = new MatchIpv4Source(aap.getIpAddress().getIpPrefix().getIpv4Prefix());
917                 flowMatches.add(srcMatch);
918             } else if (aap.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
919                 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
920                 flowMatches.add(ipv6EthMatch);
921                 MatchIpv6Source srcMatch = new MatchIpv6Source(aap.getIpAddress().getIpPrefix().getIpv6Prefix());
922                 flowMatches.add(srcMatch);
923             }
924         }
925         return flowMatches;
926     }
927
928     public static List<? extends MatchInfoBase> buildIpAndDstServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
929         List<MatchInfoBase> flowMatches = new ArrayList<>();
930         flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
931
932         if (aap.getIpAddress().getIpAddress() != null) {
933             if (aap.getIpAddress().getIpAddress().getIpv4Address() != null) {
934                 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
935                 flowMatches.add(ipv4EthMatch);
936                 MatchIpv4Destination dstMatch = new MatchIpv4Destination(
937                         new Ipv4Prefix(aap.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
938                 flowMatches.add(dstMatch);
939             } else if (aap.getIpAddress().getIpAddress().getIpv6Address() != null) {
940                 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
941                 flowMatches.add(ipv6EthMatch);
942                 MatchIpv6Destination dstMatch = new MatchIpv6Destination(
943                         new Ipv6Prefix(aap.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
944                 flowMatches.add(dstMatch);
945             }
946         } else if (aap.getIpAddress().getIpPrefix() != null) {
947             if (aap.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
948                 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
949                 flowMatches.add(ipv4EthMatch);
950                 MatchIpv4Destination dstMatch =
951                         new MatchIpv4Destination(aap.getIpAddress().getIpPrefix().getIpv4Prefix());
952                 flowMatches.add(dstMatch);
953             } else if (aap.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
954                 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
955                 flowMatches.add(ipv6EthMatch);
956                 MatchIpv6Destination dstMatch =
957                         new MatchIpv6Destination(aap.getIpAddress().getIpPrefix().getIpv6Prefix());
958                 flowMatches.add(dstMatch);
959             }
960         }
961         return flowMatches;
962     }
963
964     public static List<Ace> getAceListFromAcl(Acl acl) {
965         if (acl.getAccessListEntries() != null) {
966             List<Ace> aceList = acl.getAccessListEntries().getAce();
967             if (aceList != null && !aceList.isEmpty()
968                     && aceList.get(0).augmentation(SecurityRuleAttr.class) != null) {
969                 return aceList;
970             }
971         }
972         return Collections.emptyList();
973     }
974
975     /**
976      * Builds the ip protocol matches.
977      *
978      * @param etherType the ether type
979      * @param protocol the protocol
980      * @return the list of matches.
981      */
982     public static List<MatchInfoBase> buildIpProtocolMatches(MatchEthernetType etherType, IPProtocols protocol) {
983         return Lists.newArrayList(etherType, new MatchIpProtocol(protocol.shortValue()));
984     }
985
986     /**
987      * Does ACE have remote group id.
988      *
989      * @param aceAttr the ace attr
990      * @return true, if successful
991      */
992     public static boolean doesAceHaveRemoteGroupId(final SecurityRuleAttr aceAttr) {
993         return aceAttr != null && aceAttr.getRemoteGroupId() != null;
994     }
995
996     public SortedSet<Integer> getRemoteAclTags(@Nullable List<Uuid> aclIds, Class<? extends DirectionBase> direction) {
997         SortedSet<Integer> remoteAclTags = new TreeSet<>();
998         Set<Uuid> remoteAclIds = getRemoteAclIdsByDirection(aclIds, direction);
999         for (Uuid remoteAclId : remoteAclIds) {
1000             Integer remoteAclTag = getAclTag(remoteAclId);
1001             if (remoteAclTag != null && remoteAclTag != AclConstants.INVALID_ACL_TAG) {
1002                 remoteAclTags.add(remoteAclTag);
1003             }
1004         }
1005         return remoteAclTags;
1006     }
1007
1008     public Set<Uuid> getRemoteAclIdsByDirection(@Nullable List<Uuid> aclIds, Class<? extends DirectionBase> direction) {
1009         Set<Uuid> remoteAclIds = new HashSet<>();
1010         if (aclIds == null || aclIds.isEmpty()) {
1011             return remoteAclIds;
1012         }
1013
1014         for (Uuid aclId : aclIds) {
1015             Acl acl = this.aclDataUtil.getAcl(aclId.getValue());
1016             if (null == acl) {
1017                 LOG.warn("ACL {} not found in cache.", aclId.getValue());
1018                 continue;
1019             }
1020             remoteAclIds.addAll(getRemoteAclIdsByDirection(acl, direction));
1021         }
1022         return remoteAclIds;
1023     }
1024
1025     public static Set<Uuid> getRemoteAclIdsByDirection(Acl acl, Class<? extends DirectionBase> direction) {
1026         Set<Uuid> remoteAclIds = new HashSet<>();
1027         AccessListEntries accessListEntries = acl.getAccessListEntries();
1028         if (accessListEntries != null && accessListEntries.getAce() != null) {
1029             for (Ace ace : accessListEntries.getAce()) {
1030                 SecurityRuleAttr aceAttr = AclServiceUtils.getAccessListAttributes(ace);
1031                 if (aceAttr != null && Objects.equals(aceAttr.getDirection(), direction)
1032                         && doesAceHaveRemoteGroupId(aceAttr)) {
1033                     remoteAclIds.add(aceAttr.getRemoteGroupId());
1034                 }
1035             }
1036         }
1037         return remoteAclIds;
1038     }
1039
1040     /**
1041      * Skip delete in case of overlapping IP.
1042      *
1043      * <p>
1044      * When there are multiple ports (e.g., p1, p2, p3) having same AAP (e.g.,
1045      * 224.0.0.5) configured which are part of single SG, there would be single
1046      * flow in remote ACL table. When one of these ports (say p1) is deleted,
1047      * the single flow which is configured in remote ACL table shouldn't be
1048      * deleted. It should be deleted only when there are no more references to
1049      * it.
1050      *
1051      * @param portId the port id
1052      * @param remoteAclId the remote Acl Id
1053      * @param ipPrefix the ip prefix
1054      * @param addOrRemove the add or remove
1055      * @return true, if successful
1056      */
1057     public boolean skipDeleteInCaseOfOverlappingIP(String portId, Uuid remoteAclId, IpPrefixOrAddress ipPrefix,
1058             int addOrRemove) {
1059         boolean skipDelete = false;
1060         if (addOrRemove != NwConstants.DEL_FLOW) {
1061             return skipDelete;
1062         }
1063         AclIpPrefixes aclIpPrefixes = getAclIpPrefixesFromOperDs(remoteAclId.getValue(), ipPrefix);
1064         if (aclIpPrefixes != null && aclIpPrefixes.getPortIds() != null) {
1065             List<String> ignorePorts = Lists.newArrayList(portId);
1066             List<PortIds> portIds = new ArrayList<>(aclIpPrefixes.getPortIds());
1067             // Checking if there are any other ports excluding ignorePorts
1068             long noOfRemotePorts =
1069                     portIds.stream().map(PortIds::getPortId).filter(y -> !ignorePorts.contains(y)).count();
1070             if (noOfRemotePorts > 0) {
1071                 skipDelete = true;
1072             }
1073         }
1074         return skipDelete;
1075     }
1076
1077     public static InstanceIdentifier<AclPortsByIp> aclPortsByIpPath(String aclName) {
1078         return InstanceIdentifier.builder(AclPortsLookup.class)
1079                 .child(AclPortsByIp.class, new AclPortsByIpKey(aclName)).build();
1080     }
1081
1082     public static InstanceIdentifier<AclIpPrefixes> getAclIpPrefixesPath(String aclName, IpPrefixOrAddress ipPrefix) {
1083         return InstanceIdentifier.builder(AclPortsLookup.class).child(AclPortsByIp.class, new AclPortsByIpKey(aclName))
1084                 .child(AclIpPrefixes.class, new AclIpPrefixesKey(ipPrefix)).build();
1085     }
1086
1087     public static InstanceIdentifier<PortIds> getPortIdsPathInAclPortsLookup(String ruleName,
1088             IpPrefixOrAddress ipPrefix, String portId) {
1089         return InstanceIdentifier.builder(AclPortsLookup.class).child(AclPortsByIp.class, new AclPortsByIpKey(ruleName))
1090                 .child(AclIpPrefixes.class, new AclIpPrefixesKey(ipPrefix)).child(PortIds.class, new PortIdsKey(portId))
1091                 .build();
1092     }
1093
1094     public void addAclPortsLookupForInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
1095         LOG.debug("Processing interface additions for port {}", portAfter.getInterfaceId());
1096         List<AllowedAddressPairs> addedAllowedAddressPairs = getUpdatedAllowedAddressPairs(
1097                 portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
1098         if (!addedAllowedAddressPairs.isEmpty()) {
1099             addAclPortsLookup(portAfter, portAfter.getSecurityGroups(), addedAllowedAddressPairs);
1100         }
1101
1102         List<Uuid> addedAcls = getUpdatedAclList(portAfter.getSecurityGroups(), portBefore.getSecurityGroups());
1103         if (!addedAcls.isEmpty()) {
1104             addAclPortsLookup(portAfter, addedAcls, portAfter.getAllowedAddressPairs());
1105         }
1106     }
1107
1108     public void deleteAclPortsLookupForInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
1109         LOG.debug("Processing interface removals for port {}", portAfter.getInterfaceId());
1110         List<AllowedAddressPairs> deletedAllowedAddressPairs = getUpdatedAllowedAddressPairs(
1111                 portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
1112         if (!deletedAllowedAddressPairs.isEmpty()) {
1113             deleteAclPortsLookup(portAfter, portAfter.getSecurityGroups(), deletedAllowedAddressPairs);
1114         }
1115
1116         List<Uuid> deletedAcls = getUpdatedAclList(portBefore.getSecurityGroups(), portAfter.getSecurityGroups());
1117         if (!deletedAcls.isEmpty()) {
1118             deleteAclPortsLookup(portAfter, deletedAcls, portAfter.getAllowedAddressPairs());
1119         }
1120     }
1121
1122     public void addAclPortsLookup(AclInterface port, List<Uuid> aclList,
1123             List<AllowedAddressPairs> allowedAddresses) {
1124         String portId = port.getInterfaceId();
1125         LOG.trace("Adding AclPortsLookup for port={}, acls={}, AAPs={}", portId, aclList, allowedAddresses);
1126
1127         if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1128             LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
1129                     allowedAddresses);
1130             return;
1131         }
1132
1133         for (Uuid aclId : aclList) {
1134             String aclName = aclId.getValue();
1135             jobCoordinator.enqueueJob(aclName, () -> {
1136                 List<ListenableFuture<Void>> futures = new ArrayList<>();
1137                 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1138                     for (AllowedAddressPairs aap : allowedAddresses) {
1139                         PortIds portIdObj =
1140                                 new PortIdsBuilder().withKey(new PortIdsKey(portId)).setPortId(portId).build();
1141                         InstanceIdentifier<PortIds> path =
1142                                 AclServiceUtils.getPortIdsPathInAclPortsLookup(aclName, aap.getIpAddress(), portId);
1143                         tx.put(path, portIdObj, CREATE_MISSING_PARENTS);
1144                     }
1145                 }));
1146                 return futures;
1147             });
1148         }
1149     }
1150
1151     public void deleteAclPortsLookup(AclInterface port, List<Uuid> aclList,
1152             List<AllowedAddressPairs> allowedAddresses) {
1153         String portId = port.getInterfaceId();
1154         LOG.trace("Deleting AclPortsLookup for port={}, acls={}, AAPs={}", portId, aclList, allowedAddresses);
1155
1156         if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1157             LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
1158                     allowedAddresses);
1159             return;
1160         }
1161
1162         for (Uuid aclId : aclList) {
1163             String aclName = aclId.getValue();
1164             jobCoordinator.enqueueJob(aclName, () -> {
1165                 List<ListenableFuture<Void>> futures = new ArrayList<>();
1166                 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1167                     for (AllowedAddressPairs aap : allowedAddresses) {
1168                         InstanceIdentifier<PortIds> path =
1169                                 AclServiceUtils.getPortIdsPathInAclPortsLookup(aclName, aap.getIpAddress(), portId);
1170                         tx.delete(path);
1171                     }
1172
1173                     cleanUpStaleEntriesInAclPortsLookup(aclName, tx);
1174                 }));
1175                 return futures;
1176             });
1177         }
1178     }
1179
1180     private void cleanUpStaleEntriesInAclPortsLookup(String aclName, TypedWriteTransaction<Operational> tx) {
1181         AclPortsByIp aclPortsByIp = getAclPortsByIpFromOperDs(aclName);
1182         if (aclPortsByIp == null) {
1183             return;
1184         }
1185         boolean deleteEntireAcl;
1186         List<AclIpPrefixes> ipPrefixes = aclPortsByIp.getAclIpPrefixes();
1187         if (ipPrefixes == null || ipPrefixes.isEmpty()) {
1188             deleteEntireAcl = true;
1189         } else {
1190             boolean deleteMap = true;
1191             for (AclIpPrefixes ipPrefix : ipPrefixes) {
1192                 if (ipPrefix.getPortIds() != null && !ipPrefix.getPortIds().isEmpty()) {
1193                     deleteMap = false;
1194                     break;
1195                 }
1196             }
1197             deleteEntireAcl = deleteMap;
1198         }
1199         if (deleteEntireAcl) {
1200             tx.delete(AclServiceUtils.aclPortsByIpPath(aclName));
1201         } else {
1202             for (AclIpPrefixes ipPrefix : ipPrefixes) {
1203                 if (ipPrefix.getPortIds() == null || ipPrefix.getPortIds().isEmpty()) {
1204                     InstanceIdentifier<AclIpPrefixes> delPath =
1205                             AclServiceUtils.getAclIpPrefixesPath(aclName, ipPrefix.getIpPrefix());
1206                     tx.delete(delPath);
1207                 }
1208             }
1209         }
1210     }
1211
1212     @Nullable
1213     private AclPortsByIp getAclPortsByIpFromOperDs(String aclName) {
1214         InstanceIdentifier<AclPortsByIp> path = aclPortsByIpPath(aclName);
1215         try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1216             return tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet().orNull();
1217         } catch (ReadFailedException e) {
1218             LOG.error("Failed to read ACL ports {}", path, e);
1219             return null;
1220         }
1221     }
1222
1223     @Nullable
1224     private AclIpPrefixes getAclIpPrefixesFromOperDs(String aclName, IpPrefixOrAddress ipPrefix) {
1225         InstanceIdentifier<AclIpPrefixes> path = getAclIpPrefixesPath(aclName, ipPrefix);
1226         try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1227             return tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet().orNull();
1228         } catch (ReadFailedException e) {
1229             LOG.error("Failed to read ACL IP prefixes {}", path, e);
1230             return null;
1231         }
1232     }
1233
1234     /**
1235      * Gets the ace flow priority.
1236      *
1237      * @param aclName the acl name
1238      * @return the ace flow priority
1239      */
1240     public Integer getAceFlowPriority(String aclName) {
1241         Integer priority = AclConstants.ACE_DEFAULT_PRIORITY;
1242         Integer aclTag = getAclTag(new Uuid(aclName));
1243         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
1244             // To handle overlapping rules, aclTag is added to priority
1245             priority += aclTag;
1246         } else {
1247             LOG.warn("aclTag={} is null or invalid for aclName={}", aclTag, aclName);
1248         }
1249         return priority;
1250     }
1251
1252     /**
1253      * Returns the hard timeout based on the protocol when a ACL rule removed from the instance.
1254      * It will returns the timeout configured in the {@link AclserviceConfig} class.
1255      *
1256      * @param ace the ace
1257      * @param aclServiceUtils acl service utils
1258      * @return the hard time out
1259      */
1260     public static Integer getHardTimoutForApplyStatefulChangeOnExistingTraffic(Ace ace,
1261             AclServiceUtils aclServiceUtils) {
1262         int hardTimeout = AclConstants.SECURITY_GROUP_ICMP_IDLE_TIME_OUT;
1263         Matches matches = ace.getMatches();
1264         AceIp acl = (AceIp) matches.getAceType();
1265         Short protocol = acl.getProtocol() != null ? acl.getProtocol().toJava() : null;
1266         if (protocol == null) {
1267             return hardTimeout;
1268         } else if (protocol == NwConstants.IP_PROT_TCP
1269                 && aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout() != null) {
1270             hardTimeout = aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout().toJava();
1271         } else if (protocol == NwConstants.IP_PROT_UDP
1272                 && aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout() != null) {
1273             hardTimeout = aclServiceUtils.getConfig().getSecurityGroupUdpIdleTimeout().toJava();
1274         }
1275         return hardTimeout;
1276     }
1277
1278     /**
1279      * This method creates and returns the ct_mark instruction when a ACL rule removed from the
1280      * instance. This instruction will reset the ct_mark value and stops the existing traffics.
1281      *
1282      * @param filterTable the filterTable
1283      * @param elanId the Elan id
1284      * @return list of instruction
1285      */
1286     public static List<InstructionInfo> createCtMarkInstructionForNewState(Short filterTable, Long elanId) {
1287
1288         List<InstructionInfo> instructions = new ArrayList<>();
1289         List<ActionInfo> actionsInfos = new ArrayList<>();
1290         List<NxCtAction> ctActionsList = new ArrayList<>();
1291         NxCtAction nxCtMarkClearAction = new ActionNxConntrack.NxCtMark(AclConstants.CT_MARK_NEW_STATE);
1292         ctActionsList.add(nxCtMarkClearAction);
1293
1294         ActionNxConntrack actionNxConntrack = new ActionNxConntrack(2, 1, 0, elanId.intValue(),
1295             (short) 255, ctActionsList);
1296         actionsInfos.add(actionNxConntrack);
1297         instructions.add(new InstructionApplyActions(actionsInfos));
1298         instructions.add(new InstructionGotoTable(filterTable));
1299
1300         return instructions;
1301     }
1302
1303     public static List<AllowedAddressPairs> excludeMulticastAAPs(@Nullable List<AllowedAddressPairs> allowedAddresses) {
1304         List<AllowedAddressPairs> filteredAAPs = new ArrayList<>();
1305         if (allowedAddresses != null) {
1306             for (AllowedAddressPairs allowedAddress : allowedAddresses) {
1307                 InetAddress inetAddr = getInetAddress(allowedAddress.getIpAddress());
1308                 if (inetAddr != null && !inetAddr.isMulticastAddress()) {
1309                     filteredAAPs.add(allowedAddress);
1310                 }
1311             }
1312         }
1313         return filteredAAPs;
1314     }
1315
1316     public static String getRecoverServiceRegistryKey() {
1317         return NetvirtAcl.class.toString();
1318     }
1319
1320     @Nullable
1321     private static InetAddress getInetAddress(IpPrefixOrAddress ipPrefixOrAddress) {
1322         String addr;
1323
1324         IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
1325         if (ipPrefix != null) {
1326             addr = ipPrefix.stringValue().split("/")[0];
1327         } else {
1328             IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
1329             if (ipAddress == null) {
1330                 LOG.error("Invalid address : {}", ipPrefixOrAddress);
1331                 return null;
1332             } else {
1333                 addr = ipAddress.stringValue();
1334             }
1335         }
1336         try {
1337             return InetAddress.getByName(addr);
1338         } catch (UnknownHostException e) {
1339             LOG.error("Invalid address : {}", addr, e);
1340             return null;
1341         }
1342     }
1343
1344     public static Boolean isIpv6Subnet(List<SubnetInfo> subnetInfoList) {
1345         if (subnetInfoList != null && !subnetInfoList.isEmpty()) {
1346             for (SubnetInfo subnetInfo : subnetInfoList) {
1347                 if (subnetInfo != null && IpVersionV6.class.equals(subnetInfo.getIpVersion())) {
1348                     return true;
1349                 }
1350             }
1351         }
1352         return false;
1353     }
1354
1355     /**
1356      * Gets the subnet difference by performing (subnetInfo1 - subnetInfo2).
1357      *
1358      * @param subnetInfo1 the subnet info 1
1359      * @param subnetInfo2 the subnet info 2
1360      * @return the subnet diff
1361      */
1362     public static List<SubnetInfo> getSubnetDiff(List<SubnetInfo> subnetInfo1, List<SubnetInfo> subnetInfo2) {
1363         if (subnetInfo1 == null) {
1364             return Collections.emptyList();
1365         }
1366         List<SubnetInfo> newSubnetList = new ArrayList<>(subnetInfo1);
1367         if (subnetInfo2 == null) {
1368             return newSubnetList;
1369         }
1370         newSubnetList.removeAll(subnetInfo2);
1371         return newSubnetList;
1372     }
1373 }