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