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