ACL: Support for non-conntrack supported traffic.
[netvirt.git] / vpnservice / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / utils / AclServiceUtils.java
index 1d6a4af9e315d41f7d3f12f20d3fff4e11447c2a..06159bf5bb0547c9850eb3ec3c0e4c2ead237248 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
+ * Copyright © 2016, 2017 Red Hat, Inc. and others. All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,28 +9,49 @@
 package org.opendaylight.netvirt.aclservice.utils;
 
 import com.google.common.base.Optional;
-import com.googlecode.ipv6.IPv6Address;
-import com.googlecode.ipv6.IPv6NetworkMask;
+import com.google.common.collect.Lists;
+import com.google.common.net.InetAddresses;
 import java.math.BigInteger;
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
+import javax.inject.Inject;
+import javax.inject.Singleton;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
 import org.opendaylight.genius.mdsalutil.MDSALUtil;
-import org.opendaylight.genius.mdsalutil.MatchFieldType;
-import org.opendaylight.genius.mdsalutil.MatchInfo;
 import org.opendaylight.genius.mdsalutil.MatchInfoBase;
 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
 import org.opendaylight.genius.mdsalutil.NwConstants;
-import org.opendaylight.genius.mdsalutil.NxMatchFieldType;
 import org.opendaylight.genius.mdsalutil.NxMatchInfo;
+import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
+import org.opendaylight.genius.mdsalutil.matches.MatchArpSpa;
+import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
+import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
+import org.opendaylight.genius.mdsalutil.matches.MatchIcmpv6;
+import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
+import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
+import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source;
+import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Destination;
+import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Source;
+import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
+import org.opendaylight.genius.mdsalutil.matches.MatchUdpDestinationPort;
+import org.opendaylight.genius.mdsalutil.matches.MatchUdpSourcePort;
+import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchRegister;
 import org.opendaylight.genius.mdsalutil.packet.IPProtocols;
 import org.opendaylight.netvirt.aclservice.api.AclServiceManager.MatchCriteria;
 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
@@ -38,21 +59,36 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.cont
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntries;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
@@ -62,16 +98,22 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.ser
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.config.rev160806.AclserviceConfig;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.PortsSubnetIpPrefixes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.ports.subnet.ip.prefixes.PortSubnetIpPrefixes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.ports.subnet.ip.prefixes.PortSubnetIpPrefixesKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
@@ -79,12 +121,23 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-@SuppressWarnings("deprecation")
+@Singleton
 public final class AclServiceUtils {
 
     private static final Logger LOG = LoggerFactory.getLogger(AclServiceUtils.class);
+    public static final AclserviceConfig.DefaultBehavior DEFAULT_DENY = AclserviceConfig.DefaultBehavior.Deny;
+    public static final AclserviceConfig.DefaultBehavior DEFAULT_ALLOW = AclserviceConfig.DefaultBehavior.Allow;
 
-    private AclServiceUtils() { }
+    private final AclDataUtil aclDataUtil;
+    private final AclserviceConfig config;
+    private final IdManagerService idManager;
+
+    @Inject
+    public AclServiceUtils(AclDataUtil aclDataUtil, AclserviceConfig config, IdManagerService idManager) {
+        this.aclDataUtil = aclDataUtil;
+        this.config = config;
+        this.idManager = idManager;
+    }
 
     /**
      * Retrieves the Interface from the datastore.
@@ -115,21 +168,17 @@ public final class AclServiceUtils {
      * @param broker the data broker.
      * @param datastoreType the data store type.
      * @param path the wild card path.
+     * @param <T> type of DataObject
      * @return the required object.
      */
     public static <T extends DataObject> Optional<T> read(
             DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
-
-        Optional<T> result = Optional.absent();
-        ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
-        try {
-            result = tx.read(datastoreType, path).checkedGet();
+        try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
+            return tx.read(datastoreType, path).checkedGet();
         } catch (ReadFailedException e) {
-            LOG.warn("Failed to read InstanceIdentifier {} from {}", path, datastoreType, e);
-        } finally {
-            tx.close();
+            LOG.error("Failed to read InstanceIdentifier {} from {}", path, datastoreType, e);
+            return Optional.absent();
         }
-        return result;
     }
 
     /**
@@ -140,12 +189,7 @@ public final class AclServiceUtils {
      * @return the acl
      */
     public static Acl getAcl(DataBroker broker, String aclKey) {
-        Optional<Acl> optAcl = read(broker,
-            LogicalDatastoreType.CONFIGURATION, getAclInstanceIdentifier(aclKey));
-        if (optAcl.isPresent()) {
-            return optAcl.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.CONFIGURATION, getAclInstanceIdentifier(aclKey)).orNull();
     }
 
     /** Creates the Acl instance identifier.
@@ -196,14 +240,7 @@ public final class AclServiceUtils {
         .Interface getInterfaceStateFromOperDS(DataBroker dataBroker, String interfaceName) {
         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
             .interfaces.state.Interface> ifStateId = buildStateInterfaceId(interfaceName);
-        Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
-            .interfaces.state.Interface> ifStateOptional = MDSALUtil.read(LogicalDatastoreType
-                .OPERATIONAL, ifStateId, dataBroker);
-        if (!ifStateOptional.isPresent()) {
-            return null;
-        }
-
-        return ifStateOptional.get();
+        return MDSALUtil.read(LogicalDatastoreType.OPERATIONAL, ifStateId, dataBroker).orNull();
     }
 
     /**
@@ -273,19 +310,17 @@ public final class AclServiceUtils {
      * @param srcPort the source port.
      * @param dstPort the destination port.
      * @param lportTag the lport tag
+     * @param serviceMode ingress or egress service
      * @return list of matches.
      */
-    public static List<MatchInfoBase> buildDhcpMatches(int srcPort, int dstPort, int lportTag) {
-        List<MatchInfoBase> matches = new ArrayList<>(6);
-        matches.add(new MatchInfo(MatchFieldType.eth_type,
-                new long[] { NwConstants.ETHTYPE_IPV4 }));
-        matches.add(new MatchInfo(MatchFieldType.ip_proto,
-                new long[] { IPProtocols.UDP.intValue() }));
-        matches.add(new MatchInfo(MatchFieldType.udp_dst,
-                new long[] { dstPort }));
-        matches.add(new MatchInfo(MatchFieldType.udp_src,
-                new long[] { srcPort}));
-        matches.add(AclServiceUtils.buildLPortTagMatch(lportTag));
+    public static List<MatchInfoBase> buildDhcpMatches(int srcPort, int dstPort, int lportTag,
+            Class<? extends ServiceModeBase> serviceMode) {
+        List<MatchInfoBase> matches = new ArrayList<>(5);
+        matches.add(MatchEthernetType.IPV4);
+        matches.add(MatchIpProtocol.UDP);
+        matches.add(new MatchUdpDestinationPort(dstPort));
+        matches.add(new MatchUdpSourcePort(srcPort));
+        matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
         return matches;
     }
 
@@ -295,19 +330,17 @@ public final class AclServiceUtils {
      * @param srcPort the source port.
      * @param dstPort the destination port.
      * @param lportTag the lport tag
+     * @param serviceMode ingress or egress
      * @return list of matches.
      */
-    public static List<MatchInfoBase> buildDhcpV6Matches(int srcPort, int dstPort, int lportTag) {
+    public static List<MatchInfoBase> buildDhcpV6Matches(int srcPort, int dstPort, int lportTag,
+            Class<? extends ServiceModeBase> serviceMode) {
         List<MatchInfoBase> matches = new ArrayList<>(6);
-        matches.add(new MatchInfo(MatchFieldType.eth_type,
-                new long[] { NwConstants.ETHTYPE_IPV6 }));
-        matches.add(new MatchInfo(MatchFieldType.ip_proto,
-                new long[] { IPProtocols.UDP.intValue() }));
-        matches.add(new MatchInfo(MatchFieldType.udp_dst,
-                new long[] { dstPort }));
-        matches.add(new MatchInfo(MatchFieldType.udp_src,
-                new long[] { srcPort}));
-        matches.add(AclServiceUtils.buildLPortTagMatch(lportTag));
+        matches.add(MatchEthernetType.IPV6);
+        matches.add(MatchIpProtocol.UDP);
+        matches.add(new MatchUdpDestinationPort(dstPort));
+        matches.add(new MatchUdpSourcePort(srcPort));
+        matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
         return matches;
     }
 
@@ -317,19 +350,32 @@ public final class AclServiceUtils {
      * @param icmpType the icmpv6-type.
      * @param icmpCode the icmpv6-code.
      * @param lportTag the lport tag
+     * @param serviceMode ingress or egress
      * @return list of matches.
      */
-    public static List<MatchInfoBase> buildIcmpV6Matches(int icmpType, int icmpCode, int lportTag) {
+    public static List<MatchInfoBase> buildIcmpV6Matches(int icmpType, int icmpCode, int lportTag,
+            Class<? extends ServiceModeBase> serviceMode) {
         List<MatchInfoBase> matches = new ArrayList<>(6);
-        matches.add(new MatchInfo(MatchFieldType.eth_type,
-                new long[] { NwConstants.ETHTYPE_IPV6 }));
-        matches.add(new MatchInfo(MatchFieldType.ip_proto,
-                new long[] { IPProtocols.IPV6ICMP.intValue() }));
+        matches.add(MatchEthernetType.IPV6);
+        matches.add(MatchIpProtocol.ICMPV6);
         if (icmpType != 0) {
-            matches.add(new MatchInfo(MatchFieldType.icmp_v6,
-                    new long[] { icmpType, icmpCode}));
+            matches.add(new MatchIcmpv6((short) icmpType, (short) icmpCode));
         }
-        matches.add(AclServiceUtils.buildLPortTagMatch(lportTag));
+        matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
+        return matches;
+    }
+
+    public static List<MatchInfoBase> buildBroadcastIpV4Matches(String ipAddr) {
+        List<MatchInfoBase> matches = new ArrayList<>(2);
+        matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
+        matches.addAll(AclServiceUtils.buildIpMatches(new IpPrefixOrAddress(ipAddr.toCharArray()),
+                MatchCriteria.MATCH_DESTINATION));
+        return matches;
+    }
+
+    public static List<MatchInfoBase> buildL2BroadcastMatches() {
+        List<MatchInfoBase> matches = new ArrayList<>();
+        matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
         return matches;
     }
 
@@ -369,7 +415,7 @@ public final class AclServiceUtils {
 
     public static List<Uuid> getUpdatedAclList(List<Uuid> updatedAclList, List<Uuid> currentAclList) {
         if (updatedAclList == null) {
-            return null;
+            return Collections.emptyList();
         }
         List<Uuid> newAclList = new ArrayList<>(updatedAclList);
         if (currentAclList == null) {
@@ -434,6 +480,33 @@ public final class AclServiceUtils {
         return dpId;
     }
 
+    public static List<String> getIpBroadcastAddresses(List<IpPrefixOrAddress> cidrs) {
+        List<String> ipBroadcastAddresses = new ArrayList<>();
+        for (IpPrefixOrAddress cidr : cidrs) {
+            IpPrefix cidrIpPrefix = cidr.getIpPrefix();
+            if (cidrIpPrefix != null) {
+                Ipv4Prefix cidrIpv4Prefix = cidrIpPrefix.getIpv4Prefix();
+                if (cidrIpv4Prefix != null) {
+                    ipBroadcastAddresses.add(getBroadcastAddressFromCidr(cidrIpv4Prefix.getValue()));
+                }
+            }
+        }
+        return ipBroadcastAddresses;
+    }
+
+    public static String getBroadcastAddressFromCidr(String cidr) {
+        String[] ipaddressValues = cidr.split("/");
+        int address = InetAddresses.coerceToInteger(InetAddresses.forString(ipaddressValues[0]));
+        int cidrPart = Integer.parseInt(ipaddressValues[1]);
+        int netmask = 0;
+        for (int j = 0; j < cidrPart; ++j) {
+            netmask |= 1 << 31 - j;
+        }
+        int network = address & netmask;
+        int broadcast = network | ~netmask;
+        return InetAddresses.toAddrString(InetAddresses.fromInteger(broadcast));
+    }
+
     /**
      * Builds the ip matches.
      *
@@ -445,53 +518,192 @@ public final class AclServiceUtils {
                                                      MatchCriteria matchCriteria) {
         List<MatchInfoBase> flowMatches = new ArrayList<>();
         IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
-        MatchFieldType matchFieldType;
         if (ipPrefix != null) {
-            if (ipPrefix.getIpv4Prefix() != null) {
-                flowMatches.add(new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV4}));
-                String[] ipaddressValues = ipPrefix.getIpv4Prefix().getValue().split("/");
-                matchFieldType = (matchCriteria == MatchCriteria.MATCH_SOURCE)
-                        ? MatchFieldType.ipv4_source : MatchFieldType.ipv4_destination;
-                flowMatches.add(new MatchInfo(matchFieldType, new String[] {ipaddressValues[0], ipaddressValues[1]}));
+            Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
+            if (ipv4Prefix != null) {
+                flowMatches.add(MatchEthernetType.IPV4);
+                if (!ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
+                    flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(ipv4Prefix)
+                            : new MatchIpv4Destination(ipv4Prefix));
+                }
             } else {
-                matchFieldType = (matchCriteria == MatchCriteria.MATCH_SOURCE)
-                        ? MatchFieldType.ipv6_source : MatchFieldType.ipv6_destination;
-                String[] ipv6addressValues = ipPrefix.getIpv6Prefix().getValue().split("/");
-                IPv6Address ipv6Address = IPv6Address.fromString(ipv6addressValues[0]);
-                IPv6Address maskedV6Address = ipv6Address.maskWithNetworkMask(
-                        IPv6NetworkMask.fromPrefixLength(Integer.parseInt(ipv6addressValues[1])));
-                flowMatches.add(new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV6}));
-                flowMatches.add(new MatchInfo(matchFieldType,
-                        new String[] {maskedV6Address.toString() + "/" + ipv6addressValues[1]}));
+                flowMatches.add(MatchEthernetType.IPV6);
+                flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
+                        ipPrefix.getIpv6Prefix()) : new MatchIpv6Destination(ipPrefix.getIpv6Prefix()));
             }
         } else {
             IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
             if (ipAddress.getIpv4Address() != null) {
-                matchFieldType = (matchCriteria == MatchCriteria.MATCH_SOURCE)
-                        ? MatchFieldType.ipv4_source : MatchFieldType.ipv4_destination;
-                flowMatches.add(new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV4}));
-                flowMatches.add(new MatchInfo(matchFieldType,
-                        new String[] {ipAddress.getIpv4Address().getValue(), "32"}));
+                flowMatches.add(MatchEthernetType.IPV4);
+                flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(
+                        ipAddress.getIpv4Address().getValue(), "32") : new MatchIpv4Destination(
+                        ipAddress.getIpv4Address().getValue(), "32"));
             } else {
-                matchFieldType = (matchCriteria == MatchCriteria.MATCH_SOURCE)
-                        ? MatchFieldType.ipv6_source : MatchFieldType.ipv6_destination;
-                flowMatches.add(new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV6}));
-                flowMatches.add(new MatchInfo(matchFieldType,
-                        new String[] {ipAddress.getIpv6Address().getValue() + "/128" }));
+                flowMatches.add(MatchEthernetType.IPV6);
+                flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
+                        ipAddress.getIpv6Address().getValue() + "/128") : new MatchIpv6Destination(
+                        ipAddress.getIpv6Address().getValue() + "/128"));
             }
         }
         return flowMatches;
     }
 
+    /**
+     * Builds the arp ip matches.
+     * @param ipPrefixOrAddress the ip prefix or address
+     * @return the MatchInfoBase list
+     */
+    public static List<MatchInfoBase> buildArpIpMatches(IpPrefixOrAddress ipPrefixOrAddress) {
+        List<MatchInfoBase> flowMatches = new ArrayList<>();
+        IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
+        if (ipPrefix != null) {
+            Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
+            if (ipv4Prefix != null && !ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
+                flowMatches.add(new MatchArpSpa(ipv4Prefix));
+            }
+        } else {
+            IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
+            if (ipAddress != null && ipAddress.getIpv4Address() != null) {
+                flowMatches.add(new MatchArpSpa(ipAddress.getIpv4Address().getValue(), "32"));
+            }
+        }
+        return flowMatches;
+    }
+
+    private List<MatchInfoBase> buildAclIdMetadataMatches(Uuid remoteAclId) {
+        List<MatchInfoBase> flowMatches = new ArrayList<>();
+        BigInteger aclId = buildAclId(remoteAclId);
+        if (aclId.intValue() != AclConstants.INVALID_ACL_TAG) {
+            MatchMetadata metadataMatch = new MatchMetadata(getAclTagMetadata(aclId),
+                    MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
+            flowMatches.add(metadataMatch);
+        } else {
+            LOG.error("Failed building metadata match for Acl id match. Failed to allocate id");
+        }
+        return flowMatches;
+    }
+
+    public static MatchInfoBase buildAclTagMetadataMatch(Integer aclTag) {
+        return new MatchMetadata(getAclTagMetadata(BigInteger.valueOf(aclTag)),
+                MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
+    }
+
+    public BigInteger buildAclId(Uuid remoteAclId) {
+        Integer aclId = allocateAclTag(remoteAclId.getValue());
+        return BigInteger.valueOf(aclId);
+    }
+
+    public static BigInteger getAclTagMetadata(BigInteger aclTag) {
+        return aclTag.shiftLeft(4);
+    }
+
+    /**
+     * Does IPv4 address exists in the list of allowed address pair.
+     *
+     * @param aaps the allowed address pairs
+     * @return true, if successful
+     */
+    public static boolean doesIpv4AddressExists(List<AllowedAddressPairs> aaps) {
+        if (aaps == null) {
+            return false;
+        }
+        for (AllowedAddressPairs aap : aaps) {
+            IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
+            IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
+            if (ipPrefix != null) {
+                if (ipPrefix.getIpv4Prefix() != null) {
+                    return true;
+                }
+            } else {
+                IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
+                if (ipAddress != null && ipAddress.getIpv4Address() != null) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Does IPv6 address exists in the list of allowed address pair.
+     *
+     * @param aaps the allowed address pairs
+     * @return true, if successful
+     */
+    public static boolean doesIpv6AddressExists(List<AllowedAddressPairs> aaps) {
+        if (aaps == null) {
+            return false;
+        }
+        for (AllowedAddressPairs aap : aaps) {
+            IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
+            IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
+            if (ipPrefix != null) {
+                if (ipPrefix.getIpv6Prefix() != null) {
+                    return true;
+                }
+            } else {
+                IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
+                if (ipAddress != null && ipAddress.getIpv6Address() != null) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
     /**
      * Gets the lport tag match.
+     * Ingress match is based on metadata and egress match is based on masked reg6
      *
      * @param lportTag the lport tag
+     * @param serviceMode ingress or egress service mode
      * @return the lport tag match
      */
-    public static MatchInfo buildLPortTagMatch(int lportTag) {
-        return new MatchInfo(MatchFieldType.metadata,
-                new BigInteger[] {MetaDataUtil.getLportTagMetaData(lportTag), MetaDataUtil.METADATA_MASK_LPORT_TAG});
+    public static MatchInfoBase buildLPortTagMatch(int lportTag, Class<? extends ServiceModeBase> serviceMode) {
+        if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
+            return new NxMatchRegister(NxmNxReg6.class, MetaDataUtil.getLportTagForReg6(lportTag).longValue(),
+                    MetaDataUtil.getLportTagMaskForReg6());
+        } else {
+            return new MatchMetadata(MetaDataUtil.getLportTagMetaData(lportTag), MetaDataUtil.METADATA_MASK_LPORT_TAG);
+        }
+    }
+
+    public static List<MatchInfoBase> buildMatchesForLPortTagAndRemoteAclTag(Integer lportTag, Integer aclTag,
+            Class<? extends ServiceModeBase> serviceMode) {
+        List<MatchInfoBase> matches = new ArrayList<>();
+        if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
+            matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
+            matches.add(AclServiceUtils.buildAclTagMetadataMatch(aclTag));
+        } else {
+            // In case of ingress service mode, only metadata is used for
+            // matching both lportTag and aclTag. Hence performing "or"
+            // operation on both lportTag and aclTag metadata.
+            BigInteger metaData =
+                    MetaDataUtil.getLportTagMetaData(lportTag).or(getAclTagMetadata(BigInteger.valueOf(aclTag)));
+            BigInteger metaDataMask = MetaDataUtil.METADATA_MASK_LPORT_TAG
+                    .or(MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
+            matches.add(new MatchMetadata(metaData, metaDataMask));
+        }
+        return matches;
+    }
+
+    public static InstructionWriteMetadata getWriteMetadataForAclClassifierType(
+            AclConntrackClassifierType conntrackClassifierType) {
+        return new InstructionWriteMetadata(
+                MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(conntrackClassifierType.getValue()),
+                MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
+    }
+
+    public static InstructionWriteMetadata getWriteMetadataForRemoteAclTag(Integer remoteAclTag) {
+        return new InstructionWriteMetadata(getAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
+                MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
+    }
+
+    public static MatchInfoBase buildAclConntrackClassifierTypeMatch(
+            AclConntrackClassifierType conntrackSupportedType) {
+        return new MatchMetadata(
+                MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(conntrackSupportedType.getValue()),
+                MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
     }
 
     public static List<Ace> getAceWithRemoteAclId(DataBroker dataBroker, AclInterface port, Uuid remoteAcl) {
@@ -510,47 +722,64 @@ public final class AclServiceUtils {
         return remoteAclRuleList;
     }
 
-    public static Map<String, List<MatchInfoBase>> getFlowForRemoteAcl(Uuid remoteAclId, String ignoreInterfaceId,
-                                                                       Map<String, List<MatchInfoBase>>
-                                                                               flowMatchesMap, boolean
-                                                                               isSourceIpMacMatch) {
-        List<AclInterface> interfaceList = AclDataUtil.getInterfaceList(remoteAclId);
-        if (flowMatchesMap == null || interfaceList == null || interfaceList.isEmpty()) {
-            return null;
+    public Map<String, List<MatchInfoBase>> getFlowForRemoteAcl(AclInterface aclInterface, Uuid remoteAclId,
+            String ignoreInterfaceId, Map<String, List<MatchInfoBase>> flowMatchesMap, boolean isSourceIpMacMatch) {
+        boolean singleAcl = false;
+        Collection<AclInterface> interfaceList = null;
+        if (aclInterface.getSecurityGroups() != null && aclInterface.getSecurityGroups().size() == 1) {
+            singleAcl = true;
+        } else {
+            interfaceList = aclDataUtil.getInterfaceList(remoteAclId);
+            if (flowMatchesMap == null || interfaceList == null || interfaceList.isEmpty()) {
+                return null;
+            }
         }
         Map<String, List<MatchInfoBase>> updatedFlowMatchesMap = new HashMap<>();
-        MatchInfoBase ipv4Match = new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV4});
-        MatchInfoBase ipv6Match = new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV6});
-        for (String flowName : flowMatchesMap.keySet()) {
-            List<MatchInfoBase> flows = flowMatchesMap.get(flowName);
+        MatchInfoBase ipv4Match = MatchEthernetType.IPV4;
+        MatchInfoBase ipv6Match = MatchEthernetType.IPV6;
+        for (Entry<String, List<MatchInfoBase>> entry : flowMatchesMap.entrySet()) {
+            String flowName = entry.getKey();
+            List<MatchInfoBase> flows = entry.getValue();
+            if (singleAcl) {
+                LOG.debug("port {} is in only one SG. "
+                        + "Doesn't adding it's IPs {} to matches (handled in acl id match)",
+                        aclInterface.getLPortTag(), aclInterface.getAllowedAddressPairs());
+                List<MatchInfoBase> matchInfoBaseList = addFlowMatchForAclId(remoteAclId, flows);
+                String flowId = flowName + "_remoteACL_id_" + remoteAclId.getValue();
+                updatedFlowMatchesMap.put(flowId, matchInfoBaseList);
+                continue;
+            }
             for (AclInterface port : interfaceList) {
                 if (port.getInterfaceId().equals(ignoreInterfaceId)) {
                     continue;
                 }
-                //get allow address pair
+
+                // get allow address pair
                 List<AllowedAddressPairs> allowedAddressPair = port.getAllowedAddressPairs();
                 // iterate over allow address pair and update match type
                 for (AllowedAddressPairs aap : allowedAddressPair) {
                     List<MatchInfoBase> matchInfoBaseList;
                     String flowId;
-                    if (flows.contains(ipv4Match) && isIPv4Address(aap)) {
+                    if (flows.contains(ipv4Match) && isIPv4Address(aap) && isNotIpv4AllNetwork(aap)) {
                         matchInfoBaseList = updateAAPMatches(isSourceIpMacMatch, flows, aap);
-                        flowId = flowName + "_ipv4_remoteACL_interface_aap_" + aap.getKey();
+                        flowId = flowName + "_ipv4_remoteACL_interface_aap_" + getAapFlowId(aap);
                         updatedFlowMatchesMap.put(flowId, matchInfoBaseList);
-                    } else if (flows.contains(ipv6Match) && !isIPv4Address(aap)) {
+                    } else if (flows.contains(ipv6Match) && !isIPv4Address(aap) && isNotIpv6AllNetwork(aap)) {
                         matchInfoBaseList = updateAAPMatches(isSourceIpMacMatch, flows, aap);
-                        flowId = flowName + "_ipv6_remoteACL_interface_aap_" +  aap.getKey();
+                        flowId = flowName + "_ipv6_remoteACL_interface_aap_" + getAapFlowId(aap);
                         updatedFlowMatchesMap.put(flowId, matchInfoBaseList);
                     }
                 }
-
             }
-
         }
         return updatedFlowMatchesMap;
     }
 
-    private static boolean isIPv4Address(AllowedAddressPairs aap) {
+    public AclserviceConfig getConfig() {
+        return config;
+    }
+
+    public static boolean isIPv4Address(AllowedAddressPairs aap) {
         IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
         IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
         if (ipPrefix != null) {
@@ -559,45 +788,65 @@ public final class AclServiceUtils {
             }
         } else {
             IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
-            if (ipAddress.getIpv4Address() != null) {
+            if (ipAddress != null && ipAddress.getIpv4Address() != null) {
                 return true;
             }
         }
         return false;
     }
 
-    public static Map<String, List<MatchInfoBase>> getFlowForAllowedAddresses(List<AllowedAddressPairs>
-                                                                                      syncAllowedAddresses,
-                                                                              Map<String, List<MatchInfoBase>>
-                                                                                      flowMatchesMap, boolean
-                                                                                      isSourceIpMacMatch) {
+    public static Map<String, List<MatchInfoBase>> getFlowForAllowedAddresses(
+            List<AllowedAddressPairs> syncAllowedAddresses, Map<String, List<MatchInfoBase>> flowMatchesMap,
+            boolean isSourceIpMacMatch) {
         if (flowMatchesMap == null) {
             return null;
         }
         Map<String, List<MatchInfoBase>> updatedFlowMatchesMap = new HashMap<>();
-        MatchInfoBase ipv4Match = new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV4});
-        MatchInfoBase ipv6Match = new MatchInfo(MatchFieldType.eth_type, new long[] {NwConstants.ETHTYPE_IPV6});
-        for (String flowName : flowMatchesMap.keySet()) {
-            List<MatchInfoBase> flows = flowMatchesMap.get(flowName);
+        MatchInfoBase ipv4Match = MatchEthernetType.IPV4;
+        MatchInfoBase ipv6Match = MatchEthernetType.IPV6;
+        for (Entry<String, List<MatchInfoBase>> entry : flowMatchesMap.entrySet()) {
+            String flowName = entry.getKey();
+            List<MatchInfoBase> flows = entry.getValue();
             // iterate over allow address pair and update match type
             for (AllowedAddressPairs aap : syncAllowedAddresses) {
                 List<MatchInfoBase> matchInfoBaseList;
                 String flowId;
-                if (flows.contains(ipv4Match) && isIPv4Address(aap)) {
+                if (flows.contains(ipv4Match) && isIPv4Address(aap) && isNotIpv4AllNetwork(aap)) {
                     matchInfoBaseList = updateAAPMatches(isSourceIpMacMatch, flows, aap);
-                    flowId = flowName + "_ipv4_remoteACL_interface_aap_" + aap.getKey();
+                    flowId = flowName + "_ipv4_remoteACL_interface_aap_" + getAapFlowId(aap);
                     updatedFlowMatchesMap.put(flowId, matchInfoBaseList);
-                } else if (flows.contains(ipv6Match) && !isIPv4Address(aap)) {
+                } else if (flows.contains(ipv6Match) && !isIPv4Address(aap) && isNotIpv6AllNetwork(aap)) {
                     matchInfoBaseList = updateAAPMatches(isSourceIpMacMatch, flows, aap);
-                    flowId = flowName + "_ipv6_remoteACL_interface_aap_" + aap.getKey();
+                    flowId = flowName + "_ipv6_remoteACL_interface_aap_" + getAapFlowId(aap);
                     updatedFlowMatchesMap.put(flowId, matchInfoBaseList);
                 }
             }
-
         }
         return updatedFlowMatchesMap;
     }
 
+    public static boolean isNotIpv4AllNetwork(AllowedAddressPairs aap) {
+        IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
+        if (ipPrefix != null && ipPrefix.getIpv4Prefix() != null
+                && ipPrefix.getIpv4Prefix().getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
+            return false;
+        }
+        return true;
+    }
+
+    protected static boolean isNotIpv6AllNetwork(AllowedAddressPairs aap) {
+        IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
+        if (ipPrefix != null && ipPrefix.getIpv6Prefix() != null
+                && ipPrefix.getIpv6Prefix().getValue().equals(AclConstants.IPV6_ALL_NETWORK)) {
+            return false;
+        }
+        return true;
+    }
+
+    private static String getAapFlowId(AllowedAddressPairs aap) {
+        return aap.getMacAddress().getValue() + "_" + String.valueOf(aap.getIpAddress().getValue());
+    }
+
     public static Long getElanIdFromInterface(String elanInterfaceName,DataBroker broker) {
         ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(elanInterfaceName, broker);
         if (null != elanInterface) {
@@ -609,12 +858,7 @@ public final class AclServiceUtils {
 
     public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName,DataBroker broker) {
         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
-        Optional<ElanInterface> existingElanInterface = read(broker,
-                LogicalDatastoreType.CONFIGURATION, elanInterfaceId);
-        if (existingElanInterface.isPresent()) {
-            return existingElanInterface.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
     }
 
     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
@@ -625,12 +869,7 @@ public final class AclServiceUtils {
     // elan-instances config container
     public static ElanInstance getElanInstanceByName(String elanInstanceName, DataBroker broker) {
         InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
-        Optional<ElanInstance> elanInstance = read(broker, LogicalDatastoreType.CONFIGURATION,
-                elanIdentifierId);
-        if (elanInstance.isPresent()) {
-            return elanInstance.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
     }
 
     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
@@ -638,6 +877,22 @@ public final class AclServiceUtils {
                 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
     }
 
+    public static List<IpPrefixOrAddress> getSubnetIpPrefixes(DataBroker broker, String portId) {
+        InstanceIdentifier<PortSubnetIpPrefixes> id = InstanceIdentifier.builder(PortsSubnetIpPrefixes.class)
+                .child(PortSubnetIpPrefixes.class, new PortSubnetIpPrefixesKey(portId)).build();
+        Optional<PortSubnetIpPrefixes> portSubnetIpPrefixes = read(broker, LogicalDatastoreType.OPERATIONAL, id);
+        if (portSubnetIpPrefixes.isPresent()) {
+            return portSubnetIpPrefixes.get().getSubnetIpPrefixes();
+        }
+        return null;
+    }
+
+    public static void deleteSubnetIpPrefixes(DataBroker broker, String portId) {
+        InstanceIdentifier<PortSubnetIpPrefixes> id = InstanceIdentifier.builder(PortsSubnetIpPrefixes.class)
+                    .child(PortSubnetIpPrefixes.class, new PortSubnetIpPrefixesKey(portId)).build();
+        MDSALUtil.syncDelete(broker, LogicalDatastoreType.OPERATIONAL, id);
+    }
+
     private static List<MatchInfoBase> updateAAPMatches(boolean isSourceIpMacMatch, List<MatchInfoBase> flows,
                                                         AllowedAddressPairs aap) {
         List<MatchInfoBase> matchInfoBaseList;
@@ -650,49 +905,323 @@ public final class AclServiceUtils {
         return matchInfoBaseList;
     }
 
-    public static MatchInfoBase popMatchInfoByType(List<MatchInfoBase> flows, MatchFieldType type) {
-        MatchInfoBase mib = getMatchInfoByType(flows, type);
-        if (mib != null) {
-            flows.remove(mib);
-        }
-        return mib;
+    public List<MatchInfoBase> addFlowMatchForAclId(Uuid remoteAclId, List<MatchInfoBase> flows) {
+        List<MatchInfoBase> matchInfoBaseList;
+        matchInfoBaseList = buildAclIdMetadataMatches(remoteAclId);
+        matchInfoBaseList.addAll(flows);
+        return matchInfoBaseList;
     }
 
-    public static MatchInfoBase getMatchInfoByType(List<MatchInfoBase> flows, MatchFieldType type) {
+    public static MatchInfoBase getMatchInfoByType(List<MatchInfoBase> flows, Class<? extends NxMatchInfo> type) {
         for (MatchInfoBase mib : flows) {
-            if (mib instanceof MatchInfo) {
-                if (((MatchInfo)mib).getMatchField() == type) {
-                    return mib;
-                }
+            if (type.isAssignableFrom(mib.getClass())) {
+                return mib;
             }
         }
         return null;
     }
 
-    public static MatchInfoBase getMatchInfoByType(List<MatchInfoBase> flows, NxMatchFieldType type) {
-        for (MatchInfoBase mib : flows) {
-            if (mib instanceof NxMatchInfo) {
-                if (((NxMatchInfo)mib).getMatchField() == type) {
-                    return mib;
-                }
+    public static boolean containsMatchFieldType(List<MatchInfoBase> flows, Class<? extends NxMatchInfo> type) {
+        return getMatchInfoByType(flows, type) != null;
+    }
+
+    public static boolean containsTcpMatchField(List<MatchInfoBase> flows) {
+        return flows.contains(MatchIpProtocol.TCP);
+    }
+
+    public static boolean containsUdpMatchField(List<MatchInfoBase> flows) {
+        return flows.contains(MatchIpProtocol.UDP);
+    }
+
+    public static Integer allocateId(IdManagerService idManager, String poolName, String idKey, Integer defaultId) {
+        AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
+        try {
+            Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
+            RpcResult<AllocateIdOutput> rpcResult = result.get();
+            if (rpcResult.isSuccessful()) {
+                Integer allocatedId = rpcResult.getResult().getIdValue().intValue();
+                LOG.debug("Allocated ACL ID: {} with key: {} into pool: {}", allocatedId, idKey, poolName);
+                return allocatedId;
+            } else {
+                LOG.error("RPC Call to Get Unique Id for key {} from pool {} returned with Errors {}",
+                        idKey, poolName, rpcResult.getErrors());
             }
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.error("Exception when getting Unique Id for key {} from pool {} ", idKey, poolName, e);
         }
-        return null;
+        return defaultId;
     }
 
-    public static boolean containsMatchFieldType(List<MatchInfoBase> flows, MatchFieldType type) {
-        MatchInfoBase mib = getMatchInfoByType(flows, type);
-        if (mib != null) {
-            return true;
+    public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
+        ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
+        try {
+            Future<RpcResult<Void>> result = idManager.releaseId(idInput);
+            RpcResult<Void> rpcResult = result.get();
+            if (!rpcResult.isSuccessful()) {
+                LOG.error("RPC Call to release Id with Key {} from pool {} returned with Errors {}",
+                        idKey, poolName, rpcResult.getErrors());
+            } else {
+                LOG.debug("Released ACL ID with key: {} from pool: {}", idKey, poolName);
+            }
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.error("Exception when releasing Id for key {} from pool {} ", idKey, poolName, e);
         }
-        return false;
     }
 
-    public static boolean containsMatchFieldType(List<MatchInfoBase> flows, NxMatchFieldType type) {
-        MatchInfoBase mib = getMatchInfoByType(flows, type);
-        if (mib != null) {
-            return true;
+    /**
+     * Gets the ACL tag from cache. If not found in cache, tries to allocate and
+     * return the value.
+     *
+     * @param aclId the acl id
+     * @return the acl tag
+     */
+    public Integer getAclTag(final Uuid aclId) {
+        String aclName = aclId.getValue();
+        Integer aclTag = this.aclDataUtil.getAclTag(aclName);
+        if (aclTag == null) {
+            LOG.debug("ACL tag not found in cache for ACL={}, trying to allocate again.", aclName);
+            aclTag = allocateAclTag(aclName);
+            if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
+                this.aclDataUtil.addAclTag(aclName, aclTag);
+            }
+        }
+        return aclTag;
+    }
+
+    /**
+     * Allocate ACL tag.
+     *
+     * @param aclName the ACL name
+     * @return the integer
+     */
+    public Integer allocateAclTag(String aclName) {
+        Integer aclTag = AclServiceUtils.allocateId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName,
+                AclConstants.INVALID_ACL_TAG);
+        return aclTag;
+    }
+
+    /**
+     * Release ACL tag.
+     *
+     * @param aclName the ACL name
+     */
+    public void releaseAclTag(String aclName) {
+        AclServiceUtils.releaseId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName);
+    }
+
+    /**
+     * Indicates whether the interface has port security enabled.
+     *
+     * @param aclInterface the interface.
+     * @return true if port is security enabled.
+     */
+    public static boolean isOfInterest(AclInterface aclInterface) {
+        return aclInterface != null && aclInterface.isPortSecurityEnabled();
+    }
+
+    /**
+     * Creates the id pool for ACL tag.
+     *
+     * @param poolName the pool name
+     */
+    private void createIdPoolForAclTag(String poolName) {
+        CreateIdPoolInput createPool = new CreateIdPoolInputBuilder()
+                .setPoolName(poolName).setLow(AclConstants.ACL_TAG_POOL_START)
+                .setHigh(AclConstants.ACL_TAG_POOL_END).build();
+        try {
+            Future<RpcResult<Void>> result = this.idManager.createIdPool(createPool);
+            if (result != null && result.get().isSuccessful()) {
+                LOG.debug("Created IdPool for {}", poolName);
+            }
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.error("Failed to create ID pool [{}] for remote ACL ids", poolName, e);
+            throw new RuntimeException("Failed to create ID pool [{}] for remote ACL ids", e);
+        }
+    }
+
+    /**
+     * Delete id pool.
+     *
+     * @param poolName the pool name
+     */
+    public void deleteIdPool(String poolName) {
+        DeleteIdPoolInput deletePool = new DeleteIdPoolInputBuilder().setPoolName(poolName).build();
+        try {
+            Future<RpcResult<Void>> result = this.idManager.deleteIdPool(deletePool);
+            if (result != null && result.get().isSuccessful()) {
+                LOG.debug("Deleted IdPool for {}", poolName);
+            }
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.error("Failed to delete ID pool [{}]", poolName, e);
+            throw new RuntimeException("Failed to delete ID pool [" + poolName + "]", e);
+        }
+    }
+
+    /**
+     * Creates remote the acl id pools.
+     */
+    public void createRemoteAclIdPool() {
+        createIdPoolForAclTag(AclConstants.ACL_TAG_POOL_NAME);
+    }
+
+    /**
+     * Delete remote the acl id pools.
+     */
+    public void deleteRemoteAclIdPool() {
+        deleteIdPool(AclConstants.ACL_TAG_POOL_NAME);
+    }
+
+    public static List<? extends MatchInfoBase> buildIpAndSrcServiceMatch(Integer aclTag, AllowedAddressPairs ip,
+            DataBroker dataBroker) {
+        List<MatchInfoBase> flowMatches = new ArrayList<>();
+        flowMatches.add(buildAclTagMetadataMatch(aclTag));
+        if (ip.getIpAddress().getIpAddress() != null) {
+            if (ip.getIpAddress().getIpAddress().getIpv4Address() != null) {
+                MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
+                flowMatches.add(ipv4EthMatch);
+                MatchIpv4Source srcMatch = new MatchIpv4Source(
+                        new Ipv4Prefix(ip.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
+                flowMatches.add(srcMatch);
+            } else if (ip.getIpAddress().getIpAddress().getIpv6Address() != null) {
+                MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
+                flowMatches.add(ipv6EthMatch);
+                MatchIpv6Source srcMatch = new MatchIpv6Source(
+                        new Ipv6Prefix(ip.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
+                flowMatches.add(srcMatch);
+            }
+        } else if (ip.getIpAddress().getIpPrefix() != null) {
+            if (ip.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
+                MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
+                flowMatches.add(ipv4EthMatch);
+                MatchIpv4Source srcMatch = new MatchIpv4Source(ip.getIpAddress().getIpPrefix().getIpv4Prefix());
+                flowMatches.add(srcMatch);
+            } else if (ip.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
+                MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
+                flowMatches.add(ipv6EthMatch);
+                MatchIpv6Source srcMatch = new MatchIpv6Source(ip.getIpAddress().getIpPrefix().getIpv6Prefix());
+                flowMatches.add(srcMatch);
+            }
+        }
+        return flowMatches;
+    }
+
+    public static List<? extends MatchInfoBase> buildIpAndDstServiceMatch(Integer aclTag, AllowedAddressPairs ip,
+            DataBroker dataBroker) {
+        List<MatchInfoBase> flowMatches = new ArrayList<>();
+        flowMatches.add(buildAclTagMetadataMatch(aclTag));
+
+        if (ip.getIpAddress().getIpAddress() != null) {
+            if (ip.getIpAddress().getIpAddress().getIpv4Address() != null) {
+                MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
+                flowMatches.add(ipv4EthMatch);
+                MatchIpv4Destination dstMatch = new MatchIpv4Destination(
+                        new Ipv4Prefix(ip.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
+                flowMatches.add(dstMatch);
+            } else if (ip.getIpAddress().getIpAddress().getIpv6Address() != null) {
+                MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
+                flowMatches.add(ipv6EthMatch);
+                MatchIpv6Destination dstMatch = new MatchIpv6Destination(
+                        new Ipv6Prefix(ip.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
+                flowMatches.add(dstMatch);
+            }
+        } else if (ip.getIpAddress().getIpPrefix() != null) {
+            if (ip.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
+                MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
+                flowMatches.add(ipv4EthMatch);
+                MatchIpv4Destination dstMatch =
+                        new MatchIpv4Destination(ip.getIpAddress().getIpPrefix().getIpv4Prefix());
+                flowMatches.add(dstMatch);
+            } else if (ip.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
+                MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
+                flowMatches.add(ipv6EthMatch);
+                MatchIpv6Destination dstMatch =
+                        new MatchIpv6Destination(ip.getIpAddress().getIpPrefix().getIpv6Prefix());
+                flowMatches.add(dstMatch);
+            }
+        }
+        return flowMatches;
+    }
+
+    public static boolean isOfAclInterest(Acl acl) {
+        List<Ace> aceList = acl.getAccessListEntries().getAce();
+        if (aceList != null && !aceList.isEmpty()) {
+            return aceList.get(0).getAugmentation(SecurityRuleAttr.class) != null;
         }
         return false;
     }
+
+    public static void addLportTagMetadataMatch(int lportTag, List<MatchInfoBase> flowMatches,
+            Class<? extends ServiceModeBase> serviceMode) {
+        MatchInfoBase lportMatch = buildLPortTagMatch(lportTag, serviceMode);
+        InterfaceServiceUtil.mergeMetadataMatchsOrAdd(flowMatches, lportMatch);
+    }
+
+    /**
+     * Returns ACL specific key for synchronization.
+     *
+     * @param key the generic key
+     * @return ACL key that can be used with synchronization
+     */
+    public static String getAclKeyForSynchronization(String key) {
+        return key + AclConstants.ACL_SYNC_KEY_EXT;
+    }
+
+    /**
+     * Builds the ip protocol matches.
+     *
+     * @param etherType the ether type
+     * @param protocol the protocol
+     * @return the list of matches.
+     */
+    public static List<MatchInfoBase> buildIpProtocolMatches(MatchEthernetType etherType, IPProtocols protocol) {
+        return Lists.newArrayList(etherType, new MatchIpProtocol(protocol.shortValue()));
+    }
+
+    /**
+     * Does ACE have remote group id.
+     *
+     * @param aceAttr the ace attr
+     * @return true, if successful
+     */
+    public static boolean doesAceHaveRemoteGroupId(final SecurityRuleAttr aceAttr) {
+        return aceAttr.getRemoteGroupId() != null;
+    }
+
+    public SortedSet<Integer> getRemoteAclTags(List<Uuid> aclIds, Class<? extends DirectionBase> direction,
+            DataBroker dataBroker) {
+        SortedSet<Integer> remoteAclTags = new TreeSet<>();
+        Set<Uuid> remoteAclIds = AclServiceUtils.getRemoteAclIdsByDirection(aclIds, direction, dataBroker);
+        for (Uuid remoteAclId : remoteAclIds) {
+            Integer remoteAclTag = getAclTag(remoteAclId);
+            if (remoteAclTag != null && remoteAclTag != AclConstants.INVALID_ACL_TAG) {
+                remoteAclTags.add(remoteAclTag);
+            }
+        }
+        return remoteAclTags;
+    }
+
+    public static Set<Uuid> getRemoteAclIdsByDirection(List<Uuid> aclIds, Class<? extends DirectionBase> direction,
+            DataBroker broker) {
+        Set<Uuid> remoteAclIds = new HashSet<>();
+        if (aclIds == null || aclIds.isEmpty()) {
+            return remoteAclIds;
+        }
+
+        for (Uuid aclId : aclIds) {
+            Acl acl = AclServiceUtils.getAcl(broker, aclId.getValue());
+            if (null == acl) {
+                LOG.warn("ACL {} not found in config DS.", aclId.getValue());
+                continue;
+            }
+            AccessListEntries accessListEntries = acl.getAccessListEntries();
+            List<Ace> aceList = accessListEntries.getAce();
+            for (Ace ace : aceList) {
+                SecurityRuleAttr aceAttr = AclServiceUtils.getAccesssListAttributes(ace);
+                if (aceAttr.getDirection().equals(direction) && doesAceHaveRemoteGroupId(aceAttr)) {
+                    remoteAclIds.add(aceAttr.getRemoteGroupId());
+                }
+            }
+        }
+        return remoteAclIds;
+    }
 }