15cc7eac8bce550ab744de774ffabbca49484e9f
[netvirt.git] / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / AbstractAclServiceImpl.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 package org.opendaylight.netvirt.aclservice;
9
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
11
12 import com.google.common.collect.Lists;
13 import java.math.BigInteger;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Set;
23 import java.util.SortedSet;
24 import java.util.stream.Collectors;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
28 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
29 import org.opendaylight.genius.mdsalutil.ActionInfo;
30 import org.opendaylight.genius.mdsalutil.FlowEntity;
31 import org.opendaylight.genius.mdsalutil.InstructionInfo;
32 import org.opendaylight.genius.mdsalutil.MDSALUtil;
33 import org.opendaylight.genius.mdsalutil.MatchInfoBase;
34 import org.opendaylight.genius.mdsalutil.NwConstants;
35 import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack;
36 import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack.NxCtAction;
37 import org.opendaylight.genius.mdsalutil.actions.ActionNxCtClear;
38 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
39 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
40 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
41 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
42 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
43 import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchCtState;
44 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
45 import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
46 import org.opendaylight.netvirt.aclservice.api.AclServiceListener;
47 import org.opendaylight.netvirt.aclservice.api.AclServiceManager.Action;
48 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
49 import org.opendaylight.netvirt.aclservice.utils.AclConntrackClassifierType;
50 import org.opendaylight.netvirt.aclservice.utils.AclConstants;
51 import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
52 import org.opendaylight.netvirt.aclservice.utils.AclServiceOFFlowBuilder;
53 import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
56 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;
57 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;
58 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.ace.ip.ace.ip.version.AceIpv4;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl.InterfaceType;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.SubnetInfo;
69 import org.opendaylight.yangtools.yang.common.Uint64;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 public abstract class AbstractAclServiceImpl implements AclServiceListener {
74
75     private static final Logger LOG = LoggerFactory.getLogger(AbstractAclServiceImpl.class);
76
77     protected final IMdsalApiManager mdsalManager;
78     protected final ManagedNewTransactionRunner txRunner;
79     protected final Class<? extends ServiceModeBase> serviceMode;
80     protected final AclDataUtil aclDataUtil;
81     protected final AclServiceUtils aclServiceUtils;
82     protected final JobCoordinator jobCoordinator;
83     protected final AclInterfaceCache aclInterfaceCache;
84
85     protected final Class<? extends DirectionBase> direction;
86     protected final String directionString;
87
88     /**
89      * Initialize the member variables.
90      *
91      * @param serviceMode the service mode
92      * @param dataBroker the data broker instance.
93      * @param mdsalManager the mdsal manager instance.
94      * @param aclDataUtil the acl data util.
95      * @param aclServiceUtils the acl service util.
96      * @param jobCoordinator the job coordinator
97      * @param aclInterfaceCache the acl interface cache
98      */
99     public AbstractAclServiceImpl(Class<? extends ServiceModeBase> serviceMode, DataBroker dataBroker,
100             IMdsalApiManager mdsalManager, AclDataUtil aclDataUtil, AclServiceUtils aclServiceUtils,
101             JobCoordinator jobCoordinator, AclInterfaceCache aclInterfaceCache) {
102         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
103         this.mdsalManager = mdsalManager;
104         this.serviceMode = serviceMode;
105         this.aclDataUtil = aclDataUtil;
106         this.aclServiceUtils = aclServiceUtils;
107         this.jobCoordinator = jobCoordinator;
108         this.aclInterfaceCache = aclInterfaceCache;
109
110         this.direction =
111                 this.serviceMode.equals(ServiceModeEgress.class) ? DirectionIngress.class : DirectionEgress.class;
112         this.directionString = this.direction.equals(DirectionEgress.class) ? "Egress" : "Ingress";
113     }
114
115     @Override
116     public boolean applyAcl(AclInterface port) {
117         if (port == null) {
118             LOG.error("port cannot be null");
119             return false;
120         }
121         BigInteger dpId = port.getDpId();
122         if (dpId == null || port.getLPortTag() == null) {
123             LOG.error("Unable to find DpId from ACL interface with id {}", port.getInterfaceId());
124             return false;
125         }
126
127         LOG.debug("Applying ACL on port {} with DpId {}", port, dpId);
128         List<FlowEntity> flowEntries = new ArrayList<>();
129         if (port.getInterfaceType() == InterfaceType.DhcpService) {
130             programDhcpService(flowEntries, port, Action.ADD, NwConstants.ADD_FLOW);
131         } else {
132             if (port.getSecurityGroups() == null) {
133                 LOG.info("Port {} without SGs", port.getInterfaceId());
134                 return false;
135             }
136             programAcl(flowEntries, port, Action.ADD, NwConstants.ADD_FLOW);
137             updateRemoteAclFilterTable(flowEntries, port, NwConstants.ADD_FLOW);
138         }
139         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.ADD_FLOW);
140         return true;
141     }
142
143     @Override
144     public boolean bindAcl(AclInterface port) {
145         if (port == null) {
146             LOG.error("Port cannot be null for binding ACL service");
147             return false;
148         }
149         bindService(port);
150         return true;
151     }
152
153     @Override
154     public boolean unbindAcl(AclInterface port) {
155         if (port == null) {
156             LOG.error("Port cannot be null for unbinding ACL service");
157             return false;
158         }
159         if (port.getDpId() != null) {
160             unbindService(port);
161         }
162         return true;
163     }
164
165     @Override
166     public boolean updateAcl(AclInterface portBefore, AclInterface portAfter) {
167         // this check is to avoid situations of port update coming before interface state is up
168         if (portAfter.getDpId() == null || portAfter.getLPortTag() == null) {
169             LOG.debug("Unable to find DpId from ACL interface with id {} and lport {}", portAfter.getInterfaceId(),
170                     portAfter.getLPortTag());
171             return false;
172         }
173         boolean result = true;
174         boolean isPortSecurityEnable = portAfter.isPortSecurityEnabled();
175         boolean isPortSecurityEnableBefore = portBefore.isPortSecurityEnabled();
176         // if port security is changed, apply/remove Acls
177         if (isPortSecurityEnableBefore != isPortSecurityEnable) {
178             LOG.debug("On ACL update, Port security is {} for {}", isPortSecurityEnable ? "Enabled" :
179                     "Disabled", portAfter.getInterfaceId());
180             if (isPortSecurityEnable) {
181                 result = applyAcl(portAfter);
182             } else {
183                 result = removeAcl(portBefore);
184             }
185         } else if (isPortSecurityEnable) {
186             // Acls has been updated, find added/removed Acls and act accordingly.
187             processInterfaceUpdate(portBefore, portAfter);
188             LOG.debug("On ACL update, ACL has been updated for {}", portAfter.getInterfaceId());
189         } else if (portAfter.getInterfaceType() == InterfaceType.DhcpService) {
190             processDhcpServiceInterfaceUpdate(portBefore, portAfter);
191         }
192
193         return result;
194     }
195
196     private void processDhcpServiceInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
197         List<FlowEntity> addFlowEntries = new ArrayList<>();
198         List<FlowEntity> deleteFlowEntries = new ArrayList<>();
199         List<AllowedAddressPairs> addedAaps = AclServiceUtils
200                 .getUpdatedAllowedAddressPairs(portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
201         List<AllowedAddressPairs> deletedAaps = AclServiceUtils
202                 .getUpdatedAllowedAddressPairs(portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
203         if (!deletedAaps.isEmpty()) {
204             processDhcpServiceUpdate(deleteFlowEntries, portBefore, deletedAaps, NwConstants.DEL_FLOW);
205         }
206         if (!addedAaps.isEmpty()) {
207             processDhcpServiceUpdate(addFlowEntries, portAfter, addedAaps, NwConstants.ADD_FLOW);
208         }
209         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), deleteFlowEntries,
210                 NwConstants.DEL_FLOW);
211         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), addFlowEntries,
212                 NwConstants.ADD_FLOW);
213     }
214
215     private void processInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
216         List<FlowEntity> addFlowEntries = new ArrayList<>();
217         List<FlowEntity> deleteFlowEntries = new ArrayList<>();
218         List<AllowedAddressPairs> addedAaps = AclServiceUtils
219                 .getUpdatedAllowedAddressPairs(portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
220         List<AllowedAddressPairs> deletedAaps = AclServiceUtils
221                 .getUpdatedAllowedAddressPairs(portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
222         if (!deletedAaps.isEmpty()) {
223             programAclWithAllowedAddress(deleteFlowEntries, portBefore, deletedAaps, Action.UPDATE,
224                     NwConstants.DEL_FLOW);
225             updateRemoteAclFilterTable(deleteFlowEntries, portBefore, portBefore.getSecurityGroups(), deletedAaps,
226                     NwConstants.DEL_FLOW);
227         }
228         if (!addedAaps.isEmpty()) {
229             programAclWithAllowedAddress(addFlowEntries, portAfter, addedAaps, Action.UPDATE, NwConstants.ADD_FLOW);
230             updateRemoteAclFilterTable(addFlowEntries, portAfter, portAfter.getSecurityGroups(), addedAaps,
231                     NwConstants.ADD_FLOW);
232         }
233         if (portAfter.getSubnetInfo() != null && portBefore.getSubnetInfo() == null) {
234             programBroadcastRules(addFlowEntries, portAfter, Action.UPDATE, NwConstants.ADD_FLOW);
235         }
236         handleSubnetChange(portBefore, portAfter, addFlowEntries, deleteFlowEntries);
237
238         List<Uuid> addedAcls = AclServiceUtils.getUpdatedAclList(portAfter.getSecurityGroups(),
239                 portBefore.getSecurityGroups());
240         List<Uuid> deletedAcls = AclServiceUtils.getUpdatedAclList(portBefore.getSecurityGroups(),
241                 portAfter.getSecurityGroups());
242         if (!deletedAcls.isEmpty() || !addedAcls.isEmpty()) {
243             handleAclChange(deleteFlowEntries, portBefore, deletedAcls, NwConstants.DEL_FLOW);
244             handleAclChange(addFlowEntries, portAfter, addedAcls, NwConstants.ADD_FLOW);
245         }
246
247         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), deleteFlowEntries,
248                 NwConstants.DEL_FLOW);
249         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), addFlowEntries,
250                 NwConstants.ADD_FLOW);
251     }
252
253     private void handleSubnetChange(AclInterface portBefore, AclInterface portAfter,
254             List<FlowEntity> addFlowEntries, List<FlowEntity> deleteFlowEntries) {
255         List<SubnetInfo> deletedSubnets =
256                 AclServiceUtils.getSubnetDiff(portBefore.getSubnetInfo(), portAfter.getSubnetInfo());
257         List<SubnetInfo> addedSubnets =
258                 AclServiceUtils.getSubnetDiff(portAfter.getSubnetInfo(), portBefore.getSubnetInfo());
259
260         if (deletedSubnets != null && !deletedSubnets.isEmpty()) {
261             programIcmpv6RARule(deleteFlowEntries, portAfter, deletedSubnets, NwConstants.DEL_FLOW);
262             programSubnetBroadcastRules(deleteFlowEntries, portAfter, deletedSubnets, NwConstants.DEL_FLOW);
263         }
264         if (addedSubnets != null && !addedSubnets.isEmpty()) {
265             programIcmpv6RARule(addFlowEntries, portAfter, addedSubnets, NwConstants.ADD_FLOW);
266             programSubnetBroadcastRules(addFlowEntries, portAfter, addedSubnets, NwConstants.ADD_FLOW);
267         }
268     }
269
270     private void handleAclChange(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclList,
271             int addOrRemove) {
272         int operationForAclRules = addOrRemove == NwConstants.DEL_FLOW ? NwConstants.MOD_FLOW : addOrRemove;
273         programAclRules(flowEntries, port, aclList, operationForAclRules);
274         updateRemoteAclFilterTable(flowEntries, port, aclList, port.getAllowedAddressPairs(), addOrRemove);
275         programAclDispatcherTable(flowEntries, port, addOrRemove);
276     }
277
278     protected SortedSet<Integer> getRemoteAclTags(AclInterface port) {
279         return this.direction == DirectionIngress.class ? port.getIngressRemoteAclTags()
280                 : port.getEgressRemoteAclTags();
281     }
282
283     protected void programAclDispatcherTable(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove) {
284         SortedSet<Integer> remoteAclTags = getRemoteAclTags(port);
285         if (remoteAclTags.isEmpty()) {
286             LOG.debug("No {} rules with remote group id for port={}", this.directionString, port.getInterfaceId());
287             return;
288         }
289         Integer firstRemoteAclTag = remoteAclTags.first();
290         Integer lastRemoteAclTag = remoteAclTags.last();
291
292         programFirstRemoteAclEntryInDispatcherTable(flowEntries, port, firstRemoteAclTag, addOrRemove);
293         programLastRemoteAclEntryInDispatcherTable(flowEntries, port, lastRemoteAclTag, addOrRemove);
294
295         Integer previousRemoteAclTag = firstRemoteAclTag;
296         for (Integer remoteAclTag : remoteAclTags) {
297             if (remoteAclTag.equals(firstRemoteAclTag)) {
298                 continue;
299             }
300             List<MatchInfoBase> matches = new ArrayList<>();
301             matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(),
302                     previousRemoteAclTag, serviceMode));
303             String flowId = this.directionString + "_ACL_Dispatcher_" + port.getDpId() + "_" + port.getLPortTag() + "_"
304                     + remoteAclTag;
305
306             List<InstructionInfo> instructions =
307                     AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRuleBasedFilterTable());
308             instructions.add(AclServiceUtils.getWriteMetadataForRemoteAclTag(remoteAclTag));
309             addFlowEntryToList(flowEntries, Uint64.valueOf(port.getDpId()), getAclFilterCumDispatcherTable(), flowId,
310                     AclConstants.ACE_GOTO_NEXT_REMOTE_ACL_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches,
311                     instructions, addOrRemove);
312
313             previousRemoteAclTag = remoteAclTag;
314         }
315     }
316
317     protected void programFirstRemoteAclEntryInDispatcherTable(List<FlowEntity> flowEntries, AclInterface port,
318             Integer firstRemoteAclTag, int addOrRemove) {
319         List<MatchInfoBase> matches = new ArrayList<>();
320         matches.add(AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode));
321         String flowId = this.directionString + "_ACL_Dispatcher_First_" + port.getDpId() + "_" + port.getLPortTag()
322                 + "_" + firstRemoteAclTag;
323
324         List<InstructionInfo> instructions =
325                 AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRuleBasedFilterTable());
326         instructions.add(AclServiceUtils.getWriteMetadataForRemoteAclTag(firstRemoteAclTag));
327         addFlowEntryToList(flowEntries, Uint64.valueOf(port.getDpId()), getAclFilterCumDispatcherTable(), flowId,
328                 AclConstants.ACE_FIRST_REMOTE_ACL_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions,
329                 addOrRemove);
330     }
331
332     protected void programLastRemoteAclEntryInDispatcherTable(List<FlowEntity> flowEntries, AclInterface port,
333             Integer lastRemoteAclTag, int addOrRemove) {
334         List<MatchInfoBase> matches = new ArrayList<>();
335         matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(), lastRemoteAclTag,
336                 serviceMode));
337         String flowId = this.directionString + "_ACL_Dispatcher_Last_" + port.getDpId() + "_" + port.getLPortTag() + "_"
338                 + lastRemoteAclTag;
339
340         List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
341         addFlowEntryToList(flowEntries, Uint64.valueOf(port.getDpId()), getAclFilterCumDispatcherTable(), flowId,
342                 AclConstants.ACE_LAST_REMOTE_ACL_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(port.getLPortTag()),
343                 matches, instructions, addOrRemove);
344     }
345
346     private void programAcl(List<FlowEntity> flowEntries, AclInterface port, Action action, int addOrRemove) {
347         programAclWithAllowedAddress(flowEntries, port, port.getAllowedAddressPairs(), action, addOrRemove);
348     }
349
350     private void programAclWithAllowedAddress(List<FlowEntity> flowEntries, AclInterface port,
351             List<AllowedAddressPairs> allowedAddresses, Action action, int addOrRemove) {
352         Uint64 dpId = Uint64.valueOf(port.getDpId());
353         int lportTag = port.getLPortTag();
354         LOG.debug("Applying ACL Allowed Address on DpId {}, lportTag {}, Action {}", dpId, lportTag, action);
355         String portId = port.getInterfaceId();
356         programAntiSpoofingRules(flowEntries, port, allowedAddresses, action, addOrRemove);
357         programAclPortSpecificFixedRules(flowEntries, dpId, allowedAddresses, lportTag, portId, action, addOrRemove);
358         if (action == Action.ADD || action == Action.REMOVE) {
359             programAclRules(flowEntries, port, port.getSecurityGroups(), addOrRemove);
360             programAclDispatcherTable(flowEntries, port, addOrRemove);
361         }
362     }
363
364     /**
365      * Programs the acl custom rules.
366      *
367      * @param flowEntries the flow entries
368      * @param port acl interface
369      * @param aclUuidList the list of acl uuid to be applied
370      * @param addOrRemove whether to delete or add flow
371      * @return program succeeded
372      */
373     protected boolean programAclRules(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclUuidList,
374             int addOrRemove) {
375         BigInteger dpId = port.getDpId();
376         LOG.debug("Applying custom rules on DpId {}, lportTag {}", dpId, port.getLPortTag());
377         if (aclUuidList == null || dpId == null) {
378             LOG.warn("{} ACL parameters can not be null. dpId={}, aclUuidList={}", this.directionString, dpId,
379                     aclUuidList);
380             return false;
381         }
382         for (Uuid aclUuid : aclUuidList) {
383             Acl acl = this.aclDataUtil.getAcl(aclUuid.getValue());
384             if (null == acl) {
385                 LOG.warn("The ACL {} not found in cache", aclUuid.getValue());
386                 continue;
387             }
388             for (Ace ace : AclServiceUtils.aceList(acl)) {
389                 programAceRule(flowEntries, port, aclUuid.getValue(), ace, addOrRemove);
390             }
391         }
392         return true;
393     }
394
395     /**
396      * Programs the ace specific rule.
397      *
398      * @param flowEntries flow entries
399      * @param port acl interface
400      * @param aclName the acl name
401      * @param ace rule to be program
402      * @param addOrRemove whether to delete or add flow
403      */
404     protected void programAceRule(List<FlowEntity> flowEntries, AclInterface port, String aclName, Ace ace,
405             int addOrRemove) {
406         SecurityRuleAttr aceAttr = AclServiceUtils.getAccessListAttributes(ace);
407         if (aceAttr == null) {
408             LOG.error("Ace {} of Acl {} is either null or not having SecurityRuleAttr",
409                     ace == null ? null : ace.getRuleName(), aclName);
410             return;
411         }
412         if (addOrRemove == NwConstants.ADD_FLOW && aceAttr.isDeleted()) {
413             LOG.trace("Ignoring {} rule which is already deleted", ace.getRuleName());
414             return;
415         }
416         if (!isValidDirection(aceAttr.getDirection())) {
417             LOG.trace("Ignoring {} direction while processing for {} ACE Rule {}", aceAttr.getDirection(),
418                     this.directionString, ace.getRuleName());
419             return;
420         }
421         LOG.debug("Program {} ACE rule for dpId={}, lportTag={}, addOrRemove={}, ace={}, portId={}",
422                 this.directionString, port.getDpId(), port.getLPortTag(), addOrRemove, ace.getRuleName(),
423                 port.getInterfaceId());
424
425         Matches matches = ace.getMatches();
426         if (matches != null && matches.getAceType() instanceof AceIp) {
427             Map<String, List<MatchInfoBase>> flowMap = AclServiceOFFlowBuilder.programIpFlow(matches);
428             if (!AclServiceUtils.doesAceHaveRemoteGroupId(aceAttr)) {
429                 // programming for ACE which doesn't have any remote group Id
430                 programForAceNotHavingRemoteAclId(flowEntries, port, aclName, ace, flowMap, addOrRemove);
431             } else {
432                 Uuid remoteAclId = aceAttr.getRemoteGroupId();
433                 // programming for ACE which have remote group Id
434                 programAceSpecificFlows(flowEntries, port, aclName, ace, flowMap, remoteAclId, addOrRemove);
435             }
436         }
437     }
438
439     protected void programForAceNotHavingRemoteAclId(List<FlowEntity> flowEntries, AclInterface port, String aclName,
440             Ace ace, @Nullable Map<String, List<MatchInfoBase>> flowMap, int addOrRemove) {
441         if (null == flowMap) {
442             return;
443         }
444         MatchInfoBase lportTagMatch = AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode);
445         List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclCommitterTable());
446         Integer flowPriority = this.aclServiceUtils.getAceFlowPriority(aclName);
447
448         for (Entry<String, List<MatchInfoBase>> entry : flowMap.entrySet()) {
449             String flowName = entry.getKey();
450             List<MatchInfoBase> matches = entry.getValue();
451             matches.add(lportTagMatch);
452             String flowId = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag() + "_"
453                     + ace.key().getRuleName();
454
455             int operation = addOrRemove == NwConstants.MOD_FLOW ? NwConstants.DEL_FLOW : addOrRemove;
456             addFlowEntryToList(flowEntries, Uint64.valueOf(port.getDpId()), getAclFilterCumDispatcherTable(),
457                     flowId, flowPriority, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, operation);
458
459             if (addOrRemove != NwConstants.DEL_FLOW) {
460                 programAclForExistingTrafficTable(port, ace, addOrRemove, flowName, matches, flowPriority);
461             }
462         }
463     }
464
465     protected void programAceSpecificFlows(List<FlowEntity> flowEntries, AclInterface port, String aclName, Ace ace,
466             @Nullable Map<String, List<MatchInfoBase>> flowMap, Uuid remoteAclId, int addOrRemove) {
467         if (null == flowMap) {
468             return;
469         }
470         Integer remoteAclTag = this.aclServiceUtils.getAclTag(remoteAclId);
471         if (remoteAclTag == null || remoteAclTag == AclConstants.INVALID_ACL_TAG) {
472             LOG.error("remoteAclTag={} is null or invalid for remoteAclId={}", remoteAclTag, remoteAclId);
473             return;
474         }
475         List<MatchInfoBase> lportAndAclMatches =
476                 AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(), remoteAclTag, serviceMode);
477         List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRemoteAclTable());
478         Integer flowPriority = this.aclServiceUtils.getAceFlowPriority(aclName);
479
480         for (Entry<String, List<MatchInfoBase>> entry : flowMap.entrySet()) {
481             String flowName = entry.getKey();
482             List<MatchInfoBase> matches = entry.getValue();
483             matches.addAll(lportAndAclMatches);
484             String flowId = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag() + "_"
485                     + ace.key().getRuleName();
486
487             int operation = addOrRemove == NwConstants.MOD_FLOW ? NwConstants.DEL_FLOW : addOrRemove;
488             addFlowEntryToList(flowEntries, Uint64.valueOf(port.getDpId()), getAclRuleBasedFilterTable(), flowId,
489                     flowPriority, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, operation);
490
491             if (addOrRemove != NwConstants.DEL_FLOW) {
492                 programAclForExistingTrafficTable(port, ace, addOrRemove, flowName, matches, flowPriority);
493             }
494         }
495     }
496
497     private void programAclForExistingTrafficTable(AclInterface port, Ace ace, int addOrRemove, String flowName,
498             List<MatchInfoBase> matches, Integer priority) {
499         AceIp acl = (AceIp) ace.getMatches().getAceType();
500         final String newFlowName = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag()
501                 + "_" + (acl.getAceIpVersion() instanceof AceIpv4 ? "_IPv4" : "_IPv6") + "_FlowAfterRuleDeleted";
502
503         final List<MatchInfoBase> newMatches =
504                 matches.stream().filter(obj -> !(obj instanceof NxMatchCtState || obj instanceof MatchMetadata))
505                         .collect(Collectors.toList());
506         newMatches.add(AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode));
507         newMatches.add(new NxMatchCtState(AclConstants.TRACKED_RPL_CT_STATE, AclConstants.TRACKED_RPL_CT_STATE_MASK));
508
509         List<InstructionInfo> instructions =
510                 AclServiceUtils.createCtMarkInstructionForNewState(getAclFilterCumDispatcherTable(), port.getElanId());
511         // Reversing the flow add/delete operation for this table.
512         List<FlowEntity> flowEntries = new ArrayList<>();
513         int operation = addOrRemove == NwConstants.ADD_FLOW ? NwConstants.DEL_FLOW : NwConstants.ADD_FLOW;
514         addFlowEntryToList(flowEntries, Uint64.valueOf(port.getDpId()), getAclForExistingTrafficTable(), newFlowName,
515                 priority, 0, AclServiceUtils.getHardTimoutForApplyStatefulChangeOnExistingTraffic(ace, aclServiceUtils),
516                 AclConstants.COOKIE_ACL_BASE, newMatches, instructions, operation);
517         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, operation);
518     }
519
520     @Override
521     public boolean removeAcl(AclInterface port) {
522         if (port.getDpId() == null) {
523             LOG.warn("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
524             return false;
525         }
526         List<FlowEntity> flowEntries = new ArrayList<>();
527         if (port.getInterfaceType() == InterfaceType.DhcpService) {
528             programDhcpService(flowEntries, port, Action.REMOVE, NwConstants.DEL_FLOW);
529         } else {
530             programAcl(flowEntries, port, Action.REMOVE, NwConstants.DEL_FLOW);
531             updateRemoteAclFilterTable(flowEntries, port, NwConstants.DEL_FLOW);
532         }
533         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.DEL_FLOW);
534         return true;
535     }
536
537     @Override
538     public boolean applyAce(AclInterface port, String aclName, Ace ace) {
539         if (!port.isPortSecurityEnabled() || port.getDpId() == null) {
540             return false;
541         }
542         List<FlowEntity> flowEntries = new ArrayList<>();
543         programAceRule(flowEntries, port, aclName, ace, NwConstants.ADD_FLOW);
544         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.ADD_FLOW);
545         return true;
546     }
547
548     @Override
549     public boolean removeAce(AclInterface port, String aclName, Ace ace) {
550         if (!port.isPortSecurityEnabled() || port.getDpId() == null) {
551             return false;
552         }
553         List<FlowEntity> flowEntries = new ArrayList<>();
554         programAceRule(flowEntries, port, aclName, ace, NwConstants.MOD_FLOW);
555         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.DEL_FLOW);
556         return true;
557     }
558
559     @Override
560     public void updateRemoteAcl(Acl aclBefore, Acl aclAfter, Collection<AclInterface> portsBefore) {
561         handleRemoteAclUpdate(aclBefore, aclAfter, portsBefore);
562     }
563
564     /**
565      * Bind service.
566      *
567      * @param aclInterface the acl interface
568      */
569     public abstract void bindService(AclInterface aclInterface);
570
571     /**
572      * Unbind service.
573      *
574      * @param aclInterface the acl interface
575      */
576     protected abstract void unbindService(AclInterface aclInterface);
577
578     /**
579      * Programs DHCP Service flows.
580      *
581      * @param flowEntries the flow entries
582      * @param port the acl interface
583      * @param action add/modify/remove action
584      * @param addOrRemove addorRemove
585      */
586     protected abstract void programDhcpService(List<FlowEntity> flowEntries, AclInterface port,
587             Action action, int addOrRemove);
588
589     /**
590      * Programs DHCP service flows.
591      *
592      * @param flowEntries the flow entries
593      * @param port the acl interface
594      * @param allowedAddresses the allowed addresses
595      * @param addOrRemove addorRemove
596      */
597     protected abstract void processDhcpServiceUpdate(List<FlowEntity> flowEntries, AclInterface port,
598             List<AllowedAddressPairs> allowedAddresses, int addOrRemove);
599
600     /**
601      * Programs the anti-spoofing rules.
602      *
603      * @param flowEntries the flow entries
604      * @param port the acl interface
605      * @param allowedAddresses the allowed addresses
606      * @param action add/modify/remove action
607      * @param addOrRemove addorRemove
608      */
609     protected abstract void programAntiSpoofingRules(List<FlowEntity> flowEntries, AclInterface port,
610             List<AllowedAddressPairs> allowedAddresses, Action action, int addOrRemove);
611
612     /**
613      * Programs broadcast rules.
614      *
615      * @param flowEntries the flow entries
616      * @param port the Acl Interface port
617      * @param addOrRemove whether to delete or add flow
618      */
619     protected abstract void programBroadcastRules(List<FlowEntity> flowEntries, AclInterface port, Action action,
620             int addOrRemove);
621
622     /**
623      * Programs broadcast rules.
624      *
625      * @param flowEntries the flow entries
626      * @param port the Acl Interface port
627      * @param subnetInfoList the port subnet info list
628      * @param addOrRemove whether to delete or add flow
629      */
630     protected abstract void programSubnetBroadcastRules(List<FlowEntity> flowEntries, AclInterface port,
631             List<SubnetInfo> subnetInfoList, int addOrRemove);
632
633     protected abstract void programIcmpv6RARule(List<FlowEntity> flowEntries, AclInterface port,
634             List<SubnetInfo> subnets, int addOrRemove);
635
636     /**
637      * Add Flow to list.
638      *
639      * @param dpId
640      *            the dpId
641      * @param tableId
642      *            the tableId
643      * @param flowId
644      *            the flowId
645      * @param priority
646      *            the priority
647      * @param idleTimeOut
648      *            the idle timeout
649      * @param hardTimeOut
650      *            the hard timeout
651      * @param cookie
652      *            the cookie
653      * @param matches
654      *            the list of matches to be writted
655      * @param instructions
656      *            the list of instruction to be written.
657      * @param addOrRemove
658      *            add or remove the entries.
659      */
660     protected void addFlowEntryToList(List<FlowEntity> flowEntries, Uint64 dpId, short tableId, String flowId,
661             int priority, int idleTimeOut, int hardTimeOut, Uint64 cookie, List<? extends MatchInfoBase> matches,
662             List<InstructionInfo> instructions, int addOrRemove) {
663         List<InstructionInfo> instructionInfos = null;
664         if (addOrRemove == NwConstants.ADD_FLOW) {
665             instructionInfos = instructions;
666         }
667         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority,
668                 flowId, idleTimeOut, hardTimeOut, cookie, matches, instructionInfos);
669         LOG.trace("Adding flow to list: DpnId {}, flowId {}", dpId, flowId);
670         flowEntries.add(flowEntity);
671     }
672
673     protected void programFlows(String jobName, List<FlowEntity> flowEntries, int addOrRemove) {
674         List<List<FlowEntity>> flowEntityParts = Lists.partition(flowEntries, AclConstants.FLOWS_PER_TRANSACTION);
675         for (List<FlowEntity> part : flowEntityParts) {
676             jobCoordinator.enqueueJob(jobName,
677                 () -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
678                     tx -> {
679                         if (addOrRemove == NwConstants.ADD_FLOW) {
680                             for (FlowEntity flowEntity: part) {
681                                 mdsalManager.addFlow(tx, flowEntity);
682                             }
683                         } else {
684                             for (FlowEntity flowEntity: part) {
685                                 mdsalManager.removeFlow(tx, flowEntity);
686                             }
687                         }
688                     })), AclConstants.JOB_MAX_RETRIES);
689         }
690     }
691
692     protected List<InstructionInfo> getDispatcherTableResubmitInstructions() {
693         return getDispatcherTableResubmitInstructions(new ArrayList<>());
694     }
695
696     /**
697      * Gets the dispatcher table resubmit instructions based on ingress/egress service mode w.r.t switch.
698      *
699      * @param actionsInfos
700      *            the actions infos
701      * @return the instructions for dispatcher table resubmit
702      */
703     protected List<InstructionInfo> getDispatcherTableResubmitInstructions(List<ActionInfo> actionsInfos) {
704         short dispatcherTableId = NwConstants.LPORT_DISPATCHER_TABLE;
705         if (ServiceModeEgress.class.equals(this.serviceMode)) {
706             dispatcherTableId = NwConstants.EGRESS_LPORT_DISPATCHER_TABLE;
707         }
708
709         List<InstructionInfo> instructions = new ArrayList<>();
710         actionsInfos.add(new ActionNxResubmit(dispatcherTableId));
711         instructions.add(new InstructionApplyActions(actionsInfos));
712         return instructions;
713     }
714
715     protected void handleRemoteAclUpdate(Acl aclBefore, Acl aclAfter, Collection<AclInterface> portsBefore) {
716         String aclName = aclAfter.getAclName();
717         Collection<AclInterface> interfaceList = aclDataUtil.getInterfaceList(new Uuid(aclName));
718         if (interfaceList.isEmpty()) {
719             LOG.trace("handleRemoteAclUpdate: No interfaces found with ACL={}", aclName);
720             return;
721         }
722         Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, this.direction);
723         Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, this.direction);
724
725         Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
726         remoteAclsAdded.removeAll(remoteAclsBefore);
727
728         Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
729         remoteAclsDeleted.removeAll(remoteAclsAfter);
730
731         List<FlowEntity> addFlowEntries = new ArrayList<>();
732         List<FlowEntity> deleteFlowEntries = new ArrayList<>();
733         if (!remoteAclsAdded.isEmpty() || !remoteAclsDeleted.isEmpty()) {
734             // delete and add flows in ACL dispatcher table for all applicable
735             // ports
736             for (AclInterface portBefore : portsBefore) {
737                 programAclDispatcherTable(deleteFlowEntries, portBefore, NwConstants.DEL_FLOW);
738             }
739             for (AclInterface port : interfaceList) {
740                 programAclDispatcherTable(addFlowEntries, port, NwConstants.ADD_FLOW);
741             }
742         }
743         Set<BigInteger> dpns = interfaceList.stream().map(AclInterface::getDpId).collect(Collectors.toSet());
744
745         programRemoteAclTable(deleteFlowEntries, aclName, remoteAclsDeleted, dpns, NwConstants.DEL_FLOW);
746         programRemoteAclTable(addFlowEntries, aclName, remoteAclsAdded, dpns, NwConstants.ADD_FLOW);
747
748         programFlows(aclName, deleteFlowEntries, NwConstants.DEL_FLOW);
749         programFlows(aclName, addFlowEntries, NwConstants.ADD_FLOW);
750     }
751
752     private void programRemoteAclTable(List<FlowEntity> flowEntries, String aclName, Set<Uuid> remoteAclIds,
753             Set<BigInteger> dpns, int addOrRemove) {
754         for (Uuid remoteAclId : remoteAclIds) {
755             Collection<AclInterface> remoteAclInterfaces = aclDataUtil.getInterfaceList(remoteAclId);
756             if (remoteAclInterfaces.isEmpty()) {
757                 continue;
758             }
759             Set<AllowedAddressPairs> aaps =
760                     remoteAclInterfaces.stream().map(AclInterface::getAllowedAddressPairs).flatMap(List::stream)
761                             .filter(AclServiceUtils::isNotIpAllNetwork).collect(Collectors.toSet());
762
763             Integer aclTag = aclServiceUtils.getAclTag(remoteAclId);
764             if (addOrRemove == NwConstants.ADD_FLOW) {
765                 for (BigInteger dpn : dpns) {
766                     for (AllowedAddressPairs aap : aaps) {
767                         programRemoteAclTableFlow(flowEntries, Uint64.valueOf(dpn), aclTag, aap, addOrRemove);
768                     }
769                 }
770             } else if (addOrRemove == NwConstants.DEL_FLOW) {
771                 Set<BigInteger> remoteAclDpns = new HashSet<>();
772                 Map<String, Set<AclInterface>> mapAclWithPortSet =
773                         aclDataUtil.getRemoteAclInterfaces(remoteAclId, this.direction);
774                 if (mapAclWithPortSet != null) {
775                     Map<String, Set<AclInterface>> copyOfMapAclWithPortSet = new HashMap<>(mapAclWithPortSet);
776                     copyOfMapAclWithPortSet.remove(aclName);
777                     remoteAclDpns = collectDpns(copyOfMapAclWithPortSet);
778                 }
779                 Set<BigInteger> dpnsToOperate = new HashSet<>(dpns);
780                 dpnsToOperate.removeAll(remoteAclDpns);
781                 LOG.debug(
782                         "Deleting flows in Remote ACL table for remoteAclId={}, direction={}, dpnsToOperate={}, "
783                                 + "remoteAclDpns={}, dpns={}",
784                         remoteAclId.getValue(), directionString, dpnsToOperate, remoteAclDpns, dpns);
785
786                 for (BigInteger dpn : dpnsToOperate) {
787                     for (AllowedAddressPairs aap : aaps) {
788                         programRemoteAclTableFlow(flowEntries, Uint64.valueOf(dpn), aclTag, aap, addOrRemove);
789                     }
790                 }
791             }
792         }
793     }
794
795     private void updateRemoteAclFilterTable(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove) {
796         updateRemoteAclFilterTable(flowEntries, port, port.getSecurityGroups(), port.getAllowedAddressPairs(),
797                 addOrRemove);
798     }
799
800     private void updateRemoteAclFilterTable(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclList,
801             List<AllowedAddressPairs> aaps, int addOrRemove) {
802         if (aclList == null) {
803             LOG.debug("Port {} without SGs", port.getInterfaceId());
804             return;
805         }
806         String portId = port.getInterfaceId();
807         LOG.trace("updateRemoteAclFilterTable for portId={}, aclList={}, aaps={}, addOrRemove={}", portId, aclList,
808                 aaps, addOrRemove);
809         for (Uuid aclId : aclList) {
810             if (aclDataUtil.getRemoteAcl(aclId, this.direction) != null) {
811                 Integer aclTag = aclServiceUtils.getAclTag(aclId);
812                 if (addOrRemove == NwConstants.ADD_FLOW) {
813                     syncRemoteAclTable(flowEntries, portId, aclId, aclTag, aaps, addOrRemove);
814                 }
815                 else if (addOrRemove == NwConstants.DEL_FLOW) {
816                     jobCoordinator.enqueueJob(aclId.getValue(), () -> {
817                         List<FlowEntity> remoteTableFlowEntries = new ArrayList<>();
818                         syncRemoteAclTable(remoteTableFlowEntries, portId, aclId, aclTag, aaps, addOrRemove);
819                         programFlows(AclConstants.ACL_JOB_KEY_PREFIX + aclId.getValue(),
820                                 remoteTableFlowEntries, NwConstants.DEL_FLOW);
821                         return Collections.emptyList();
822                     });
823                 }
824             }
825         }
826         Set<Uuid> remoteAclIds = aclServiceUtils.getRemoteAclIdsByDirection(aclList, direction);
827         for (Uuid remoteAclId : remoteAclIds) {
828             syncRemoteAclTableFromOtherDpns(flowEntries, port, remoteAclId, addOrRemove);
829         }
830     }
831
832     private void syncRemoteAclTable(List<FlowEntity> flowEntries, String portId, Uuid acl, Integer aclTag,
833             List<AllowedAddressPairs> aaps, int addOrRemove) {
834         Map<String, Set<AclInterface>> mapAclWithPortSet = aclDataUtil.getRemoteAclInterfaces(acl, this.direction);
835         Set<BigInteger> dpns = collectDpns(mapAclWithPortSet);
836         for (AllowedAddressPairs aap : aaps) {
837             if (!AclServiceUtils.isNotIpAllNetwork(aap)) {
838                 continue;
839             }
840             if (aclServiceUtils.skipDeleteInCaseOfOverlappingIP(portId, acl, aap.getIpAddress(),
841                     addOrRemove)) {
842                 LOG.debug("Skipping delete of IP={} in remote ACL table for remoteAclId={}, portId={}",
843                         aap.getIpAddress(), portId, acl.getValue());
844                 continue;
845             }
846             for (BigInteger dpId : dpns) {
847                 programRemoteAclTableFlow(flowEntries, Uint64.valueOf(dpId), aclTag, aap, addOrRemove);
848             }
849         }
850     }
851
852     private void syncRemoteAclTableFromOtherDpns(List<FlowEntity> flowEntries, AclInterface port, Uuid remoteAclId,
853             int addOrRemove) {
854         Collection<AclInterface> aclInterfaces = aclDataUtil.getInterfaceList(remoteAclId);
855
856         if (!aclInterfaces.isEmpty() && isFirstPortInDpnWithRemoteAclId(port, remoteAclId)) {
857             Integer aclTag = aclServiceUtils.getAclTag(remoteAclId);
858             for (AclInterface aclInterface : aclInterfaces) {
859                 if (port.getInterfaceId().equals(aclInterface.getInterfaceId())) {
860                     continue;
861                 }
862                 for (AllowedAddressPairs aap : aclInterface.getAllowedAddressPairs()) {
863                     if (AclServiceUtils.isNotIpAllNetwork(aap)) {
864                         programRemoteAclTableFlow(flowEntries, Uint64.valueOf(port.getDpId()),
865                             aclTag, aap, addOrRemove);
866                     }
867                 }
868             }
869         }
870     }
871
872     private boolean isFirstPortInDpnWithRemoteAclId(AclInterface port, Uuid remoteAclId) {
873         String portId = port.getInterfaceId();
874         BigInteger dpId = port.getDpId();
875         Map<String, Set<AclInterface>> remoteAclInterfacesMap =
876                 aclDataUtil.getRemoteAclInterfaces(remoteAclId, direction);
877         if (remoteAclInterfacesMap != null) {
878             for (Set<AclInterface> interfaceSet : remoteAclInterfacesMap.values()) {
879                 for (AclInterface aclInterface : interfaceSet) {
880                     if (portId.equals(aclInterface.getInterfaceId())) {
881                         continue;
882                     }
883                     if (dpId.equals(aclInterface.getDpId())) {
884                         return false;
885                     }
886                 }
887             }
888         }
889         return true;
890     }
891
892     protected abstract void programRemoteAclTableFlow(List<FlowEntity> flowEntries, Uint64 dpId, Integer aclTag,
893             AllowedAddressPairs aap, int addOrRemove);
894
895     protected Set<BigInteger> collectDpns(@Nullable Map<String, Set<AclInterface>> mapAclWithPortSet) {
896         Set<BigInteger> dpns = new HashSet<>();
897         if (mapAclWithPortSet == null) {
898             return dpns;
899         }
900         for (Set<AclInterface> innerSet : mapAclWithPortSet.values()) {
901             if (innerSet == null) {
902                 continue;
903             }
904             for (AclInterface inter : innerSet) {
905                 dpns.add(inter.getDpId());
906             }
907         }
908         return dpns;
909     }
910
911     /**
912      * Programs the port specific fixed rules.
913      *
914      * @param flowEntries the flow entries
915      * @param dpId the dp id
916      * @param allowedAddresses the allowed addresses
917      * @param lportTag the lport tag
918      * @param portId the portId
919      * @param action the action
920      * @param write whether to add or remove the flow.
921      */
922     protected void programAclPortSpecificFixedRules(List<FlowEntity> flowEntries, Uint64 dpId,
923             List<AllowedAddressPairs> allowedAddresses, int lportTag, String portId, Action action, int write) {
924         programGotoClassifierTableRules(flowEntries, dpId, allowedAddresses, lportTag, write);
925         if (action == Action.ADD || action == Action.REMOVE) {
926             programConntrackRecircRules(flowEntries, dpId, allowedAddresses, lportTag, portId, write);
927             programPortSpecificDropRules(flowEntries, dpId, lportTag, write);
928             programAclCommitRules(flowEntries, dpId, lportTag, portId, write);
929         }
930         LOG.info("programAclPortSpecificFixedRules: flows for dpId={}, lportId={}, action={}, write={}", dpId, lportTag,
931                 action, write);
932     }
933
934     protected abstract void programGotoClassifierTableRules(List<FlowEntity> flowEntries, Uint64 dpId,
935             List<AllowedAddressPairs> aaps, int lportTag, int addOrRemove);
936
937     /**
938      * Adds the rule to send the packet to the netfilter to check whether it is a known packet.
939      *
940      * @param flowEntries the flow entries
941      * @param dpId the dpId
942      * @param aaps the allowed address pairs
943      * @param lportTag the lport tag
944      * @param portId the portId
945      * @param addOrRemove whether to add or remove the flow
946      */
947     protected void programConntrackRecircRules(List<FlowEntity> flowEntries, Uint64 dpId,
948             List<AllowedAddressPairs> aaps, int lportTag, String portId, int addOrRemove) {
949         if (AclServiceUtils.doesIpv4AddressExists(aaps)) {
950             programConntrackRecircRule(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV4, addOrRemove);
951         }
952         if (AclServiceUtils.doesIpv6AddressExists(aaps)) {
953             programConntrackRecircRule(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV6, addOrRemove);
954         }
955     }
956
957     protected void programConntrackRecircRule(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag,
958             String portId, MatchEthernetType matchEtherType, int addOrRemove) {
959         List<MatchInfoBase> matches = new ArrayList<>();
960         matches.add(matchEtherType);
961         matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
962
963         List<InstructionInfo> instructions = new ArrayList<>();
964         if (addOrRemove == NwConstants.ADD_FLOW) {
965             Long elanTag = getElanIdFromAclInterface(portId);
966             if (elanTag == null) {
967                 LOG.error("ElanId not found for portId={}; Context: dpId={}, lportTag={}, addOrRemove={},", portId,
968                         dpId, lportTag, addOrRemove);
969                 return;
970             }
971             List<ActionInfo> actionsInfos = new ArrayList<>();
972             actionsInfos.add(new ActionNxConntrack(2, 0, 0, elanTag.intValue(), getAclForExistingTrafficTable()));
973             instructions.add(new InstructionApplyActions(actionsInfos));
974         }
975
976         String flowName =
977                 this.directionString + "_Fixed_Conntrk_" + dpId.toString() + "_"
978                     + lportTag + "_" + matchEtherType + "_Recirc";
979         addFlowEntryToList(flowEntries, dpId, getAclConntrackSenderTable(), flowName,
980                 AclConstants.ACL_DEFAULT_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions,
981                 addOrRemove);
982     }
983
984     /**
985      * Adds the rules to drop the unknown/invalid packets .
986      *
987      * @param flowEntries the flow entries
988      * @param dpId the dpId
989      * @param lportTag the lport tag
990      * @param addOrRemove whether to add or remove the flow
991      */
992     protected void programPortSpecificDropRules(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag,
993             int addOrRemove) {
994         LOG.debug("Programming Drop Rules: DpId={}, lportTag={}, addOrRemove={}", dpId, lportTag, addOrRemove);
995         programConntrackInvalidDropRule(flowEntries, dpId, lportTag, addOrRemove);
996         programAclRuleMissDropRule(flowEntries, dpId, lportTag, addOrRemove);
997     }
998
999     /**
1000      * Adds the rule to drop the conntrack invalid packets .
1001      *
1002      * @param flowEntries the flow entries
1003      * @param dpId the dpId
1004      * @param lportTag the lport tag
1005      * @param addOrRemove whether to add or remove the flow
1006      */
1007     protected void programConntrackInvalidDropRule(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag,
1008             int addOrRemove) {
1009         List<MatchInfoBase> matches = AclServiceOFFlowBuilder.addLPortTagMatches(lportTag,
1010                 AclConstants.TRACKED_INV_CT_STATE, AclConstants.TRACKED_INV_CT_STATE_MASK, serviceMode);
1011         List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
1012
1013         String flowId = this.directionString + "_Fixed_Conntrk_Drop" + dpId.toString()
1014                             + "_" + lportTag + "_Tracked_Invalid";
1015         addFlowEntryToList(flowEntries, dpId, getAclFilterCumDispatcherTable(), flowId,
1016                 AclConstants.CT_STATE_TRACKED_INVALID_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(lportTag),
1017                 matches, instructions, addOrRemove);
1018     }
1019
1020     /**
1021      * Program ACL rule miss drop rule for a port.
1022      *
1023      * @param flowEntries the flow entries
1024      * @param dpId the dp id
1025      * @param lportTag the lport tag
1026      * @param addOrRemove the add or remove
1027      */
1028     protected void programAclRuleMissDropRule(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag,
1029             int addOrRemove) {
1030         List<MatchInfoBase> matches = new ArrayList<>();
1031         matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
1032         List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
1033
1034         String flowId = this.directionString + "_Fixed_Acl_Rule_Miss_Drop_" + dpId.toString() + "_" + lportTag;
1035         addFlowEntryToList(flowEntries, dpId, getAclFilterCumDispatcherTable(), flowId,
1036                 AclConstants.ACL_PORT_SPECIFIC_DROP_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(lportTag),
1037                 matches, instructions, addOrRemove);
1038     }
1039
1040     /**
1041      * Program acl commit rules.
1042      *
1043      * @param flowEntries the flow entries
1044      * @param dpId the dp id
1045      * @param lportTag the lport tag
1046      * @param portId the port id
1047      * @param addOrRemove the add or remove
1048      */
1049     protected void programAclCommitRules(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag, String portId,
1050             int addOrRemove) {
1051         programAclCommitRuleForConntrack(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV4, addOrRemove);
1052         programAclCommitRuleForConntrack(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV6, addOrRemove);
1053         programAclCommitRuleForNonConntrack(flowEntries, dpId, lportTag, addOrRemove);
1054     }
1055
1056     /**
1057      * Program acl commit rule for conntrack.
1058      *
1059      * @param flowEntries the flow entries
1060      * @param dpId the dp id
1061      * @param lportTag the lport tag
1062      * @param portId the port id
1063      * @param matchEtherType the match ether type
1064      * @param addOrRemove the add or remove
1065      */
1066     protected void programAclCommitRuleForConntrack(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag,
1067             String portId, MatchEthernetType matchEtherType, int addOrRemove) {
1068         List<MatchInfoBase> matches = new ArrayList<>();
1069         matches.add(matchEtherType);
1070         matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndConntrackClassifierType(lportTag,
1071                 AclConntrackClassifierType.CONNTRACK_SUPPORTED, serviceMode));
1072
1073         List<ActionInfo> actionsInfos = new ArrayList<>();
1074         if (addOrRemove == NwConstants.ADD_FLOW) {
1075             Long elanId = getElanIdFromAclInterface(portId);
1076             if (elanId == null) {
1077                 LOG.error("ElanId not found for portId={}; Context: dpId={}, lportTag={}, addOrRemove={}", portId, dpId,
1078                         lportTag, addOrRemove);
1079                 return;
1080             }
1081             List<NxCtAction> ctActionsList =
1082                     Lists.newArrayList(new ActionNxConntrack.NxCtMark(AclConstants.CT_MARK_EST_STATE));
1083             actionsInfos.add(new ActionNxConntrack(2, 1, 0, elanId.intValue(), (short) 255, ctActionsList));
1084             actionsInfos.add(new ActionNxCtClear());
1085         }
1086         List<InstructionInfo> instructions = getDispatcherTableResubmitInstructions(actionsInfos);
1087
1088         String flowName = directionString + "_Acl_Commit_Conntrack_" + dpId.toString()
1089                             + "_" + lportTag + "_" + matchEtherType;
1090         // Flow for conntrack traffic to commit and resubmit to dispatcher
1091         addFlowEntryToList(flowEntries, dpId, getAclCommitterTable(), flowName, AclConstants.ACL_DEFAULT_PRIORITY,
1092                 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, addOrRemove);
1093     }
1094
1095     /**
1096      * Program acl commit rule for non conntrack.
1097      *
1098      * @param flowEntries the flow entries
1099      * @param dpId the dp id
1100      * @param lportTag the lport tag
1101      * @param addOrRemove the add or remove
1102      */
1103     protected void programAclCommitRuleForNonConntrack(List<FlowEntity> flowEntries, Uint64 dpId, int lportTag,
1104             int addOrRemove) {
1105         List<MatchInfoBase> matches = new ArrayList<>();
1106         matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndConntrackClassifierType(lportTag,
1107                 AclConntrackClassifierType.NON_CONNTRACK_SUPPORTED, serviceMode));
1108
1109         List<InstructionInfo> instructions = getDispatcherTableResubmitInstructions();
1110         String flowName = this.directionString + "_Acl_Commit_Non_Conntrack_" + dpId + "_" + lportTag;
1111         // Flow for non-conntrack traffic to resubmit to dispatcher
1112         addFlowEntryToList(flowEntries, dpId, getAclCommitterTable(), flowName, AclConstants.ACL_DEFAULT_PRIORITY,
1113                 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, addOrRemove);
1114     }
1115
1116     @Nullable
1117     protected Long getElanIdFromAclInterface(String elanInterfaceName) {
1118         AclInterface aclInterface = aclInterfaceCache.get(elanInterfaceName);
1119         if (null != aclInterface) {
1120             return aclInterface.getElanId();
1121         }
1122         return null;
1123     }
1124
1125     protected abstract boolean isValidDirection(Class<? extends DirectionBase> direction);
1126
1127     protected abstract short getAclConntrackSenderTable();
1128
1129     protected abstract short getAclForExistingTrafficTable();
1130
1131     protected abstract short getAclFilterCumDispatcherTable();
1132
1133     protected abstract short getAclRuleBasedFilterTable();
1134
1135     protected abstract short getAclRemoteAclTable();
1136
1137     protected abstract short getAclCommitterTable();
1138 }