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