2 * Copyright (c) 2016, 2018 Red Hat, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netvirt.aclservice.utils;
11 import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
12 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
13 import static org.opendaylight.genius.infra.Datastore.OPERATIONAL;
15 import com.google.common.base.Optional;
16 import com.google.common.collect.Lists;
17 import com.google.common.net.InetAddresses;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import java.math.BigInteger;
20 import java.net.InetAddress;
21 import java.net.UnknownHostException;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Objects;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.Future;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
38 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
41 import org.opendaylight.genius.infra.Datastore.Operational;
42 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
43 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
44 import org.opendaylight.genius.infra.TypedWriteTransaction;
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.actions.ActionNxConntrack;
52 import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack.NxCtAction;
53 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
54 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
55 import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
56 import org.opendaylight.genius.mdsalutil.matches.MatchArpSpa;
57 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
58 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
59 import org.opendaylight.genius.mdsalutil.matches.MatchIcmpv6;
60 import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
61 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
62 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source;
63 import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Destination;
64 import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Source;
65 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
66 import org.opendaylight.genius.mdsalutil.matches.MatchUdpDestinationPort;
67 import org.opendaylight.genius.mdsalutil.matches.MatchUdpSourcePort;
68 import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchRegister;
69 import org.opendaylight.genius.mdsalutil.packet.IPProtocols;
70 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
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.InterfaceKey;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolOutput;
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.DeleteIdPoolOutput;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdOutput;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.config.rev160806.AclserviceConfig;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.AclPortsLookup;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddress;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddressBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpVersionV6;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.AclPortsByIp;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.AclPortsByIpKey;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.AclIpPrefixes;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.AclIpPrefixesKey;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIds;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIdsBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIdsKey;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.SubnetInfo;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.serviceutils.srm.types.rev180626.NetvirtAcl;
141 import org.opendaylight.yangtools.yang.binding.DataObject;
142 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
143 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
144 import org.opendaylight.yangtools.yang.common.RpcResult;
145 import org.opendaylight.yangtools.yang.common.Uint64;
146 import org.slf4j.Logger;
147 import org.slf4j.LoggerFactory;
150 public final class AclServiceUtils {
152 private static final Logger LOG = LoggerFactory.getLogger(AclServiceUtils.class);
154 private final DataBroker dataBroker;
155 private final ManagedNewTransactionRunner txRunner;
156 private final AclDataUtil aclDataUtil;
157 private final AclserviceConfig config;
158 private final IdManagerService idManager;
159 private final JobCoordinator jobCoordinator;
162 public AclServiceUtils(DataBroker dataBroker, AclDataUtil aclDataUtil, AclserviceConfig config,
163 IdManagerService idManager, JobCoordinator jobCoordinator) {
164 this.dataBroker = dataBroker;
165 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
166 this.aclDataUtil = aclDataUtil;
167 this.config = config;
168 this.idManager = idManager;
169 this.jobCoordinator = jobCoordinator;
173 * Retrieves the Interface from the datastore.
174 * @param broker the data broker
175 * @param interfaceName the interface name
176 * @return the interface.
178 public static Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
179 .Interface> getInterface(DataBroker broker, String interfaceName) {
180 return read(broker, LogicalDatastoreType.CONFIGURATION, getInterfaceIdentifier(interfaceName));
184 * Builds the interface identifier.
185 * @param interfaceName the interface name.
186 * @return the interface identifier.
188 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
189 .interfaces.Interface> getInterfaceIdentifier(String interfaceName) {
190 return InstanceIdentifier.builder(Interfaces.class)
192 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
193 .Interface.class, new InterfaceKey(interfaceName)).build();
197 * Retrieves the object from the datastore.
198 * @param broker the data broker.
199 * @param datastoreType the data store type.
200 * @param path the wild card path.
201 * @param <T> type of DataObject
202 * @return the required object.
204 public static <T extends DataObject> Optional<T> read(
205 DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
206 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
207 return tx.read(datastoreType, path).checkedGet();
208 } catch (ReadFailedException e) {
209 LOG.error("Failed to read InstanceIdentifier {} from {}", path, datastoreType, e);
210 return Optional.absent();
215 * Retrieves the interface state.
216 * @param dataBroker the data broker.
217 * @param interfaceName the interface name.
218 * @return the interface state.
220 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
221 .@Nullable Interface getInterfaceStateFromOperDS(DataBroker dataBroker, String interfaceName) {
222 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
223 .interfaces.state.Interface> ifStateId = buildStateInterfaceId(interfaceName);
224 return MDSALUtil.read(LogicalDatastoreType.OPERATIONAL, ifStateId, dataBroker).orNull();
228 * Build the interface state.
229 * @param interfaceName the interface name.
230 * @return the interface state.
232 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
233 .interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
234 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
235 .interfaces.state.Interface> idBuilder = InstanceIdentifier.builder(InterfacesState.class)
236 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
237 .state.Interface.class, new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
238 .rev140508.interfaces.state.InterfaceKey(interfaceName));
239 return idBuilder.build();
243 * Retrieves the security rule attribute augmentation from the access list.
244 * @param ace the access list entry
245 * @return the security rule attributes
248 public static SecurityRuleAttr getAccessListAttributes(Ace ace) {
252 SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
253 if (aceAttributes == null) {
256 return aceAttributes;
260 * Returns the DHCP match.
262 * @param srcPort the source port.
263 * @param dstPort the destination port.
264 * @param lportTag the lport tag
265 * @param serviceMode ingress or egress service
266 * @return list of matches.
268 public static List<MatchInfoBase> buildDhcpMatches(int srcPort, int dstPort, int lportTag,
269 Class<? extends ServiceModeBase> serviceMode) {
270 List<MatchInfoBase> matches = new ArrayList<>(5);
271 matches.add(MatchEthernetType.IPV4);
272 matches.add(MatchIpProtocol.UDP);
273 matches.add(new MatchUdpDestinationPort(dstPort));
274 matches.add(new MatchUdpSourcePort(srcPort));
275 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
280 * Returns the DHCPv6 match.
282 * @param srcPort the source port.
283 * @param dstPort the destination port.
284 * @param lportTag the lport tag
285 * @param serviceMode ingress or egress
286 * @return list of matches.
288 public static List<MatchInfoBase> buildDhcpV6Matches(int srcPort, int dstPort, int lportTag,
289 Class<? extends ServiceModeBase> serviceMode) {
290 List<MatchInfoBase> matches = new ArrayList<>(6);
291 matches.add(MatchEthernetType.IPV6);
292 matches.add(MatchIpProtocol.UDP);
293 matches.add(new MatchUdpDestinationPort(dstPort));
294 matches.add(new MatchUdpSourcePort(srcPort));
295 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
300 * Returns the ICMPv6 match.
302 * @param icmpType the icmpv6-type.
303 * @param icmpCode the icmpv6-code.
304 * @param lportTag the lport tag
305 * @param serviceMode ingress or egress
306 * @return list of matches.
308 public static List<MatchInfoBase> buildIcmpV6Matches(int icmpType, int icmpCode, int lportTag,
309 Class<? extends ServiceModeBase> serviceMode) {
310 List<MatchInfoBase> matches = new ArrayList<>();
311 matches.add(MatchEthernetType.IPV6);
312 matches.add(MatchIpProtocol.ICMPV6);
314 matches.add(new MatchIcmpv6((short) icmpType, (short) icmpCode));
316 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
320 public static List<MatchInfoBase> buildBroadcastIpV4Matches(String ipAddr) {
321 List<MatchInfoBase> matches = new ArrayList<>(2);
322 matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
323 matches.addAll(AclServiceUtils.buildIpMatches(IpPrefixOrAddressBuilder.getDefaultInstance(ipAddr),
324 MatchCriteria.MATCH_DESTINATION));
328 public static List<MatchInfoBase> buildL2BroadcastMatches() {
329 List<MatchInfoBase> matches = new ArrayList<>();
330 matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
335 * Builds the service id.
337 * @param interfaceName the interface name
338 * @param serviceIndex the service index
339 * @param serviceMode the service mode
340 * @return the instance identifier
342 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex,
343 Class<? extends ServiceModeBase> serviceMode) {
344 return InstanceIdentifier.builder(ServiceBindings.class)
345 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, serviceMode))
346 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
350 * Gets the bound services.
352 * @param serviceName the service name
353 * @param servicePriority the service priority
354 * @param flowPriority the flow priority
355 * @param cookie the cookie
356 * @param instructions the instructions
357 * @return the bound services
359 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
360 Uint64 cookie, List<Instruction> instructions) {
361 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
362 .setInstruction(instructions);
363 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
364 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
365 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
368 public static List<Uuid> getUpdatedAclList(List<Uuid> updatedAclList, List<Uuid> currentAclList) {
369 if (updatedAclList == null) {
370 return Collections.emptyList();
372 List<Uuid> newAclList = new ArrayList<>(updatedAclList);
373 if (currentAclList == null) {
376 List<Uuid> origAclList = new ArrayList<>(currentAclList);
377 newAclList.removeAll(origAclList);
381 public static List<AllowedAddressPairs> getUpdatedAllowedAddressPairs(
382 @Nullable List<AllowedAddressPairs> updatedAllowedAddressPairs,
383 @Nullable List<AllowedAddressPairs> currentAllowedAddressPairs) {
384 if (updatedAllowedAddressPairs == null) {
385 return Collections.emptyList();
387 List<AllowedAddressPairs> newAllowedAddressPairs = new ArrayList<>(updatedAllowedAddressPairs);
388 if (currentAllowedAddressPairs == null) {
389 return newAllowedAddressPairs;
391 List<AllowedAddressPairs> origAllowedAddressPairs = new ArrayList<>(currentAllowedAddressPairs);
392 for (Iterator<AllowedAddressPairs> iterator = newAllowedAddressPairs.iterator(); iterator.hasNext();) {
393 AllowedAddressPairs updatedAllowedAddressPair = iterator.next();
394 for (AllowedAddressPairs currentAllowedAddressPair : origAllowedAddressPairs) {
395 if (updatedAllowedAddressPair.key().equals(currentAllowedAddressPair.key())) {
401 return newAllowedAddressPairs;
405 public static BigInteger getDpIdFromIterfaceState(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
406 .interfaces.rev140508.interfaces.state.Interface interfaceState) {
407 BigInteger dpId = null;
408 List<String> ofportIds = interfaceState.getLowerLayerIf();
409 if (ofportIds != null && !ofportIds.isEmpty()) {
410 NodeConnectorId nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
411 dpId = BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
416 public static List<String> getIpBroadcastAddresses(List<SubnetInfo> subnetInfoList) {
417 List<String> ipBroadcastAddresses = new ArrayList<>();
418 for (SubnetInfo subnetInfo : subnetInfoList) {
419 IpPrefix cidrIpPrefix = subnetInfo.getIpPrefix().getIpPrefix();
420 if (cidrIpPrefix != null) {
421 Ipv4Prefix cidrIpv4Prefix = cidrIpPrefix.getIpv4Prefix();
422 if (cidrIpv4Prefix != null) {
423 ipBroadcastAddresses.add(getBroadcastAddressFromCidr(cidrIpv4Prefix.getValue()));
427 return ipBroadcastAddresses;
430 public static String getBroadcastAddressFromCidr(String cidr) {
431 String[] ipaddressValues = cidr.split("/");
432 int address = InetAddresses.coerceToInteger(InetAddresses.forString(ipaddressValues[0]));
433 int cidrPart = Integer.parseInt(ipaddressValues[1]);
435 for (int j = 0; j < cidrPart; ++j) {
436 netmask |= 1 << 31 - j;
438 int network = address & netmask;
439 int broadcast = network | ~netmask;
440 return InetAddresses.toAddrString(InetAddresses.fromInteger(broadcast));
444 * Builds the ip matches.
446 * @param ipPrefixOrAddress the ip prefix or address
447 * @param matchCriteria the source_ip or destination_ip used for the match
450 public static List<MatchInfoBase> buildIpMatches(IpPrefixOrAddress ipPrefixOrAddress,
451 MatchCriteria matchCriteria) {
452 List<MatchInfoBase> flowMatches = new ArrayList<>();
453 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
454 if (ipPrefix != null) {
455 Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
456 if (ipv4Prefix != null) {
457 flowMatches.add(MatchEthernetType.IPV4);
458 if (!ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
459 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(ipv4Prefix)
460 : new MatchIpv4Destination(ipv4Prefix));
463 flowMatches.add(MatchEthernetType.IPV6);
464 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
465 ipPrefix.getIpv6Prefix()) : new MatchIpv6Destination(ipPrefix.getIpv6Prefix()));
468 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
469 if (ipAddress.getIpv4Address() != null) {
470 flowMatches.add(MatchEthernetType.IPV4);
471 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(
472 ipAddress.getIpv4Address().getValue(), "32") : new MatchIpv4Destination(
473 ipAddress.getIpv4Address().getValue(), "32"));
475 flowMatches.add(MatchEthernetType.IPV6);
476 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
477 ipAddress.getIpv6Address().getValue() + "/128") : new MatchIpv6Destination(
478 ipAddress.getIpv6Address().getValue() + "/128"));
485 * Builds the arp ip matches.
486 * @param ipPrefixOrAddress the ip prefix or address
487 * @return the MatchInfoBase list
489 public static List<MatchInfoBase> buildArpIpMatches(IpPrefixOrAddress ipPrefixOrAddress) {
490 List<MatchInfoBase> flowMatches = new ArrayList<>();
491 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
492 if (ipPrefix != null) {
493 Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
494 if (ipv4Prefix != null && !ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
495 flowMatches.add(new MatchArpSpa(ipv4Prefix));
498 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
499 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
500 flowMatches.add(new MatchArpSpa(ipAddress.getIpv4Address().getValue(), "32"));
506 public static MatchInfoBase buildRemoteAclTagMetadataMatch(Integer remoteAclTag) {
507 return new MatchMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
508 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
511 public static Uint64 getRemoteAclTagMetadata(BigInteger remoteAclTag) {
512 return Uint64.valueOf(remoteAclTag.shiftLeft(4));
515 public static Uint64 getDropFlowCookie(int lport) {
516 return Uint64.fromLongBits(MetaDataUtil.getLportTagMetaData(lport).longValue()
517 | AclConstants.COOKIE_ACL_DROP_FLOW.longValue());
521 * Does IPv4 address exists in the list of allowed address pair.
523 * @param aaps the allowed address pairs
524 * @return true, if successful
526 public static boolean doesIpv4AddressExists(List<AllowedAddressPairs> aaps) {
530 for (AllowedAddressPairs aap : aaps) {
531 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
532 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
533 if (ipPrefix != null) {
534 if (ipPrefix.getIpv4Prefix() != null) {
538 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
539 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
548 * Does IPv6 address exists in the list of allowed address pair.
550 * @param aaps the allowed address pairs
551 * @return true, if successful
553 public static boolean doesIpv6AddressExists(List<AllowedAddressPairs> aaps) {
557 for (AllowedAddressPairs aap : aaps) {
558 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
559 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
560 if (ipPrefix != null) {
561 if (ipPrefix.getIpv6Prefix() != null) {
565 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
566 if (ipAddress != null && ipAddress.getIpv6Address() != null) {
575 * Gets the lport tag match.
576 * Ingress match is based on metadata and egress match is based on masked reg6
578 * @param lportTag the lport tag
579 * @param serviceMode ingress or egress service mode
580 * @return the lport tag match
582 public static MatchInfoBase buildLPortTagMatch(int lportTag, Class<? extends ServiceModeBase> serviceMode) {
583 if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
584 return new NxMatchRegister(NxmNxReg6.class, MetaDataUtil.getLportTagForReg6(lportTag).longValue(),
585 MetaDataUtil.getLportTagMaskForReg6());
587 return new MatchMetadata(MetaDataUtil.getLportTagMetaData(lportTag), MetaDataUtil.METADATA_MASK_LPORT_TAG);
591 public static List<MatchInfoBase> buildMatchesForLPortTagAndRemoteAclTag(Integer lportTag, Integer remoteAclTag,
592 Class<? extends ServiceModeBase> serviceMode) {
593 List<MatchInfoBase> matches = new ArrayList<>();
594 if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
595 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
596 matches.add(AclServiceUtils.buildRemoteAclTagMetadataMatch(remoteAclTag));
598 // In case of ingress service mode, only metadata is used for
599 // matching both lportTag and aclTag. Hence performing "or"
600 // operation on both lportTag and aclTag metadata.
601 Uint64 metaData = Uint64.fromLongBits(MetaDataUtil.getLportTagMetaData(lportTag).longValue()
602 | (getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)).longValue()));
603 Uint64 metaDataMask = Uint64.fromLongBits(MetaDataUtil.METADATA_MASK_LPORT_TAG.longValue()
604 | MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG.longValue());
605 matches.add(new MatchMetadata(metaData, metaDataMask));
610 public static Collection<? extends MatchInfoBase> buildMatchesForLPortTagAndConntrackClassifierType(int lportTag,
611 AclConntrackClassifierType conntrackClassifierType, Class<? extends ServiceModeBase> serviceMode) {
612 List<MatchInfoBase> matches = new ArrayList<>();
613 if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
614 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
615 matches.add(AclServiceUtils.buildAclConntrackClassifierTypeMatch(conntrackClassifierType));
617 // In case of ingress service mode, only metadata is used for
618 // matching both lportTag and conntrackClassifierType. Hence performing "or"
619 // operation on both lportTag and conntrackClassifierType metadata.
620 Uint64 metaData = Uint64.fromLongBits(MetaDataUtil.getLportTagMetaData(lportTag).longValue()
621 | (MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(
622 Uint64.valueOf(conntrackClassifierType.getValue()))).longValue());
623 Uint64 metaDataMask = Uint64.fromLongBits(MetaDataUtil.METADATA_MASK_LPORT_TAG.longValue()
624 | MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE.longValue());
625 matches.add(new MatchMetadata(metaData, metaDataMask));
630 public static InstructionWriteMetadata getWriteMetadataForAclClassifierType(
631 AclConntrackClassifierType conntrackClassifierType) {
632 return new InstructionWriteMetadata(MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(
633 Uint64.valueOf(conntrackClassifierType.getValue())),
634 MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
637 public static InstructionWriteMetadata getWriteMetadataForDropFlag() {
638 return new InstructionWriteMetadata(MetaDataUtil.getAclDropMetaData(AclConstants.METADATA_DROP_FLAG),
639 MetaDataUtil.METADATA_MASK_ACL_DROP);
642 public static InstructionWriteMetadata getWriteMetadataForRemoteAclTag(Integer remoteAclTag) {
643 return new InstructionWriteMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
644 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
647 public static MatchInfoBase buildAclConntrackClassifierTypeMatch(
648 AclConntrackClassifierType conntrackSupportedType) {
649 return new MatchMetadata(
650 MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(
651 Uint64.valueOf(conntrackSupportedType.getValue())),
652 MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
655 public AclserviceConfig getConfig() {
659 public static boolean isIPv4Address(AllowedAddressPairs aap) {
660 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
661 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
662 if (ipPrefix != null) {
663 if (ipPrefix.getIpv4Prefix() != null) {
667 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
668 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
675 public static boolean isNotIpv4AllNetwork(AllowedAddressPairs aap) {
676 IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
677 if (ipPrefix != null && ipPrefix.getIpv4Prefix() != null
678 && ipPrefix.getIpv4Prefix().getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
684 protected static boolean isNotIpv6AllNetwork(AllowedAddressPairs aap) {
685 IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
686 if (ipPrefix != null && ipPrefix.getIpv6Prefix() != null
687 && ipPrefix.getIpv6Prefix().getValue().equals(AclConstants.IPV6_ALL_NETWORK)) {
693 public static boolean isNotIpAllNetwork(AllowedAddressPairs aap) {
694 return isNotIpv4AllNetwork(aap) && isNotIpv6AllNetwork(aap);
698 public static Long getElanIdFromInterface(String elanInterfaceName, DataBroker broker) {
699 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(elanInterfaceName, broker);
700 if (null != elanInterface) {
701 ElanInstance elanInfo = getElanInstanceByName(elanInterface.getElanInstanceName(), broker);
702 return elanInfo != null ? elanInfo.getElanTag().toJava() : null;
708 public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName,DataBroker broker) {
709 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
710 return read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
713 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
714 return InstanceIdentifier.builder(ElanInterfaces.class)
715 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
718 // elan-instances config container
720 public static ElanInstance getElanInstanceByName(String elanInstanceName, DataBroker broker) {
721 InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
722 return read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
725 public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
726 return InstanceIdentifier.builder(ElanInstances.class)
727 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
730 public void deleteAcesFromConfigDS(String aclName, List<Ace> deletedAceRules) {
731 List<List<Ace>> acesParts = Lists.partition(deletedAceRules, AclConstants.ACES_PER_TRANSACTION);
732 for (List<Ace> acePart : acesParts) {
733 jobCoordinator.enqueueJob(aclName,
734 () -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
736 for (Ace ace: acePart) {
737 InstanceIdentifier<Ace> id = InstanceIdentifier.builder(AccessLists.class)
738 .child(Acl.class, new AclKey(aclName, Ipv4Acl.class)).child(AccessListEntries.class)
739 .child(Ace.class, ace.key()).build();
742 })), AclConstants.ACEDELETE_MAX_RETRIES);
746 public static Integer allocateId(IdManagerService idManager, String poolName, String idKey, Integer defaultId) {
747 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
749 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
750 RpcResult<AllocateIdOutput> rpcResult = result.get();
751 if (rpcResult.isSuccessful()) {
752 Integer allocatedId = rpcResult.getResult().getIdValue().intValue();
753 LOG.debug("Allocated ACL ID: {} with key: {} into pool: {}", allocatedId, idKey, poolName);
756 LOG.error("RPC Call to Get Unique Id for key {} from pool {} returned with Errors {}",
757 idKey, poolName, rpcResult.getErrors());
759 } catch (InterruptedException | ExecutionException e) {
760 LOG.error("Exception when getting Unique Id for key {} from pool {} ", idKey, poolName, e);
765 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
766 ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
768 RpcResult<ReleaseIdOutput> rpcResult = idManager.releaseId(idInput).get();
769 if (!rpcResult.isSuccessful()) {
770 LOG.error("RPC Call to release Id with Key {} from pool {} returned with Errors {}",
771 idKey, poolName, rpcResult.getErrors());
773 LOG.debug("Released ACL ID with key: {} from pool: {}", idKey, poolName);
775 } catch (InterruptedException | ExecutionException e) {
776 LOG.error("Exception when releasing Id for key {} from pool {} ", idKey, poolName, e);
781 * Gets the ACL tag from cache. If not found in cache, tries to allocate and
784 * @param aclId the acl id
785 * @return the acl tag
788 public Integer getAclTag(final Uuid aclId) {
789 String aclName = aclId.getValue();
790 Integer aclTag = this.aclDataUtil.getAclTag(aclName);
791 if (aclTag == null) {
792 LOG.debug("ACL tag not found in cache for ACL={}, trying to allocate again.", aclName);
793 aclTag = allocateAclTag(aclName);
794 if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
795 this.aclDataUtil.addAclTag(aclName, aclTag);
804 * @param aclName the ACL name
805 * @return the integer
807 public Integer allocateAclTag(String aclName) {
808 return AclServiceUtils.allocateId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName,
809 AclConstants.INVALID_ACL_TAG);
815 * @param aclName the ACL name
817 public void releaseAclTag(String aclName) {
818 AclServiceUtils.releaseId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName);
822 * Indicates whether the interface has port security enabled or interface is DHCP service port.
824 * @param aclInterface the interface.
825 * @return true if port is security enabled or is a DHCP service port.
827 public static boolean isOfInterest(AclInterface aclInterface) {
828 return aclInterface != null && (aclInterface.isPortSecurityEnabled()
829 || aclInterface.getInterfaceType() == InterfaceAcl.InterfaceType.DhcpService);
833 * Indicates whether the interface has port security enabled or interface is DHCP service port.
835 * @param aclInterface the interface.
836 * @return true if port is security enabled or is a DHCP service port.
838 public static boolean isOfInterest(InterfaceAcl aclInterface) {
839 return aclInterface != null && (aclInterface.isPortSecurityEnabled()
840 || aclInterface.getInterfaceType() == InterfaceAcl.InterfaceType.DhcpService);
844 * Creates the id pool for ACL tag.
846 * @param poolName the pool name
848 private void createIdPoolForAclTag(String poolName) {
849 CreateIdPoolInput createPool = new CreateIdPoolInputBuilder()
850 .setPoolName(poolName).setLow(AclConstants.ACL_TAG_POOL_START)
851 .setHigh(AclConstants.ACL_TAG_POOL_END).build();
853 Future<RpcResult<CreateIdPoolOutput>> result = this.idManager.createIdPool(createPool);
854 if (result != null && result.get().isSuccessful()) {
855 LOG.debug("Created IdPool for {}", poolName);
857 } catch (InterruptedException | ExecutionException e) {
858 LOG.error("Failed to create ID pool [{}] for remote ACL ids", poolName, e);
859 throw new RuntimeException("Failed to create ID pool [{}] for remote ACL ids", e);
866 * @param poolName the pool name
868 public void deleteIdPool(String poolName) {
869 DeleteIdPoolInput deletePool = new DeleteIdPoolInputBuilder().setPoolName(poolName).build();
871 Future<RpcResult<DeleteIdPoolOutput>> result = this.idManager.deleteIdPool(deletePool);
872 if (result != null && result.get().isSuccessful()) {
873 LOG.debug("Deleted IdPool for {}", poolName);
875 } catch (InterruptedException | ExecutionException e) {
876 LOG.error("Failed to delete ID pool [{}]", poolName, e);
877 throw new RuntimeException("Failed to delete ID pool [" + poolName + "]", e);
882 * Creates remote the acl id pools.
884 public void createRemoteAclIdPool() {
885 createIdPoolForAclTag(AclConstants.ACL_TAG_POOL_NAME);
889 * Delete remote the acl id pools.
891 public void deleteRemoteAclIdPool() {
892 deleteIdPool(AclConstants.ACL_TAG_POOL_NAME);
895 public static List<? extends MatchInfoBase> buildIpAndSrcServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
896 List<MatchInfoBase> flowMatches = new ArrayList<>();
897 flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
898 if (aap.getIpAddress().getIpAddress() != null) {
899 if (aap.getIpAddress().getIpAddress().getIpv4Address() != null) {
900 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
901 flowMatches.add(ipv4EthMatch);
902 MatchIpv4Source srcMatch = new MatchIpv4Source(
903 new Ipv4Prefix(aap.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
904 flowMatches.add(srcMatch);
905 } else if (aap.getIpAddress().getIpAddress().getIpv6Address() != null) {
906 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
907 flowMatches.add(ipv6EthMatch);
908 MatchIpv6Source srcMatch = new MatchIpv6Source(
909 new Ipv6Prefix(aap.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
910 flowMatches.add(srcMatch);
912 } else if (aap.getIpAddress().getIpPrefix() != null) {
913 if (aap.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
914 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
915 flowMatches.add(ipv4EthMatch);
916 MatchIpv4Source srcMatch = new MatchIpv4Source(aap.getIpAddress().getIpPrefix().getIpv4Prefix());
917 flowMatches.add(srcMatch);
918 } else if (aap.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
919 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
920 flowMatches.add(ipv6EthMatch);
921 MatchIpv6Source srcMatch = new MatchIpv6Source(aap.getIpAddress().getIpPrefix().getIpv6Prefix());
922 flowMatches.add(srcMatch);
928 public static List<? extends MatchInfoBase> buildIpAndDstServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
929 List<MatchInfoBase> flowMatches = new ArrayList<>();
930 flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
932 if (aap.getIpAddress().getIpAddress() != null) {
933 if (aap.getIpAddress().getIpAddress().getIpv4Address() != null) {
934 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
935 flowMatches.add(ipv4EthMatch);
936 MatchIpv4Destination dstMatch = new MatchIpv4Destination(
937 new Ipv4Prefix(aap.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
938 flowMatches.add(dstMatch);
939 } else if (aap.getIpAddress().getIpAddress().getIpv6Address() != null) {
940 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
941 flowMatches.add(ipv6EthMatch);
942 MatchIpv6Destination dstMatch = new MatchIpv6Destination(
943 new Ipv6Prefix(aap.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
944 flowMatches.add(dstMatch);
946 } else if (aap.getIpAddress().getIpPrefix() != null) {
947 if (aap.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
948 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
949 flowMatches.add(ipv4EthMatch);
950 MatchIpv4Destination dstMatch =
951 new MatchIpv4Destination(aap.getIpAddress().getIpPrefix().getIpv4Prefix());
952 flowMatches.add(dstMatch);
953 } else if (aap.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
954 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
955 flowMatches.add(ipv6EthMatch);
956 MatchIpv6Destination dstMatch =
957 new MatchIpv6Destination(aap.getIpAddress().getIpPrefix().getIpv6Prefix());
958 flowMatches.add(dstMatch);
964 public static List<Ace> getAceListFromAcl(Acl acl) {
965 if (acl.getAccessListEntries() != null) {
966 List<Ace> aceList = acl.getAccessListEntries().getAce();
967 if (aceList != null && !aceList.isEmpty()
968 && aceList.get(0).augmentation(SecurityRuleAttr.class) != null) {
972 return Collections.emptyList();
976 * Builds the ip protocol matches.
978 * @param etherType the ether type
979 * @param protocol the protocol
980 * @return the list of matches.
982 public static List<MatchInfoBase> buildIpProtocolMatches(MatchEthernetType etherType, IPProtocols protocol) {
983 return Lists.newArrayList(etherType, new MatchIpProtocol(protocol.shortValue()));
987 * Does ACE have remote group id.
989 * @param aceAttr the ace attr
990 * @return true, if successful
992 public static boolean doesAceHaveRemoteGroupId(final SecurityRuleAttr aceAttr) {
993 return aceAttr != null && aceAttr.getRemoteGroupId() != null;
996 public SortedSet<Integer> getRemoteAclTags(@Nullable List<Uuid> aclIds, Class<? extends DirectionBase> direction) {
997 SortedSet<Integer> remoteAclTags = new TreeSet<>();
998 Set<Uuid> remoteAclIds = getRemoteAclIdsByDirection(aclIds, direction);
999 for (Uuid remoteAclId : remoteAclIds) {
1000 Integer remoteAclTag = getAclTag(remoteAclId);
1001 if (remoteAclTag != null && remoteAclTag != AclConstants.INVALID_ACL_TAG) {
1002 remoteAclTags.add(remoteAclTag);
1005 return remoteAclTags;
1008 public Set<Uuid> getRemoteAclIdsByDirection(@Nullable List<Uuid> aclIds, Class<? extends DirectionBase> direction) {
1009 Set<Uuid> remoteAclIds = new HashSet<>();
1010 if (aclIds == null || aclIds.isEmpty()) {
1011 return remoteAclIds;
1014 for (Uuid aclId : aclIds) {
1015 Acl acl = this.aclDataUtil.getAcl(aclId.getValue());
1017 LOG.warn("ACL {} not found in cache.", aclId.getValue());
1020 remoteAclIds.addAll(getRemoteAclIdsByDirection(acl, direction));
1022 return remoteAclIds;
1025 public static Set<Uuid> getRemoteAclIdsByDirection(Acl acl, Class<? extends DirectionBase> direction) {
1026 Set<Uuid> remoteAclIds = new HashSet<>();
1027 AccessListEntries accessListEntries = acl.getAccessListEntries();
1028 if (accessListEntries != null && accessListEntries.getAce() != null) {
1029 for (Ace ace : accessListEntries.getAce()) {
1030 SecurityRuleAttr aceAttr = AclServiceUtils.getAccessListAttributes(ace);
1031 if (aceAttr != null && Objects.equals(aceAttr.getDirection(), direction)
1032 && doesAceHaveRemoteGroupId(aceAttr)) {
1033 remoteAclIds.add(aceAttr.getRemoteGroupId());
1037 return remoteAclIds;
1041 * Skip delete in case of overlapping IP.
1044 * When there are multiple ports (e.g., p1, p2, p3) having same AAP (e.g.,
1045 * 224.0.0.5) configured which are part of single SG, there would be single
1046 * flow in remote ACL table. When one of these ports (say p1) is deleted,
1047 * the single flow which is configured in remote ACL table shouldn't be
1048 * deleted. It should be deleted only when there are no more references to
1051 * @param portId the port id
1052 * @param remoteAclId the remote Acl Id
1053 * @param ipPrefix the ip prefix
1054 * @param addOrRemove the add or remove
1055 * @return true, if successful
1057 public boolean skipDeleteInCaseOfOverlappingIP(String portId, Uuid remoteAclId, IpPrefixOrAddress ipPrefix,
1059 boolean skipDelete = false;
1060 if (addOrRemove != NwConstants.DEL_FLOW) {
1063 AclIpPrefixes aclIpPrefixes = getAclIpPrefixesFromOperDs(remoteAclId.getValue(), ipPrefix);
1064 if (aclIpPrefixes != null && aclIpPrefixes.getPortIds() != null) {
1065 List<String> ignorePorts = Lists.newArrayList(portId);
1066 List<PortIds> portIds = new ArrayList<>(aclIpPrefixes.getPortIds());
1067 // Checking if there are any other ports excluding ignorePorts
1068 long noOfRemotePorts =
1069 portIds.stream().map(PortIds::getPortId).filter(y -> !ignorePorts.contains(y)).count();
1070 if (noOfRemotePorts > 0) {
1077 public static InstanceIdentifier<AclPortsByIp> aclPortsByIpPath(String aclName) {
1078 return InstanceIdentifier.builder(AclPortsLookup.class)
1079 .child(AclPortsByIp.class, new AclPortsByIpKey(aclName)).build();
1082 public static InstanceIdentifier<AclIpPrefixes> getAclIpPrefixesPath(String aclName, IpPrefixOrAddress ipPrefix) {
1083 return InstanceIdentifier.builder(AclPortsLookup.class).child(AclPortsByIp.class, new AclPortsByIpKey(aclName))
1084 .child(AclIpPrefixes.class, new AclIpPrefixesKey(ipPrefix)).build();
1087 public static InstanceIdentifier<PortIds> getPortIdsPathInAclPortsLookup(String ruleName,
1088 IpPrefixOrAddress ipPrefix, String portId) {
1089 return InstanceIdentifier.builder(AclPortsLookup.class).child(AclPortsByIp.class, new AclPortsByIpKey(ruleName))
1090 .child(AclIpPrefixes.class, new AclIpPrefixesKey(ipPrefix)).child(PortIds.class, new PortIdsKey(portId))
1094 public void addAclPortsLookupForInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
1095 LOG.debug("Processing interface additions for port {}", portAfter.getInterfaceId());
1096 List<AllowedAddressPairs> addedAllowedAddressPairs = getUpdatedAllowedAddressPairs(
1097 portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
1098 if (!addedAllowedAddressPairs.isEmpty()) {
1099 addAclPortsLookup(portAfter, portAfter.getSecurityGroups(), addedAllowedAddressPairs);
1102 List<Uuid> addedAcls = getUpdatedAclList(portAfter.getSecurityGroups(), portBefore.getSecurityGroups());
1103 if (!addedAcls.isEmpty()) {
1104 addAclPortsLookup(portAfter, addedAcls, portAfter.getAllowedAddressPairs());
1108 public void deleteAclPortsLookupForInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
1109 LOG.debug("Processing interface removals for port {}", portAfter.getInterfaceId());
1110 List<AllowedAddressPairs> deletedAllowedAddressPairs = getUpdatedAllowedAddressPairs(
1111 portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
1112 if (!deletedAllowedAddressPairs.isEmpty()) {
1113 deleteAclPortsLookup(portAfter, portAfter.getSecurityGroups(), deletedAllowedAddressPairs);
1116 List<Uuid> deletedAcls = getUpdatedAclList(portBefore.getSecurityGroups(), portAfter.getSecurityGroups());
1117 if (!deletedAcls.isEmpty()) {
1118 deleteAclPortsLookup(portAfter, deletedAcls, portAfter.getAllowedAddressPairs());
1122 public void addAclPortsLookup(AclInterface port, List<Uuid> aclList,
1123 List<AllowedAddressPairs> allowedAddresses) {
1124 String portId = port.getInterfaceId();
1125 LOG.trace("Adding AclPortsLookup for port={}, acls={}, AAPs={}", portId, aclList, allowedAddresses);
1127 if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1128 LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
1133 for (Uuid aclId : aclList) {
1134 String aclName = aclId.getValue();
1135 jobCoordinator.enqueueJob(aclName, () -> {
1136 List<ListenableFuture<Void>> futures = new ArrayList<>();
1137 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1138 for (AllowedAddressPairs aap : allowedAddresses) {
1140 new PortIdsBuilder().withKey(new PortIdsKey(portId)).setPortId(portId).build();
1141 InstanceIdentifier<PortIds> path =
1142 AclServiceUtils.getPortIdsPathInAclPortsLookup(aclName, aap.getIpAddress(), portId);
1143 tx.put(path, portIdObj, CREATE_MISSING_PARENTS);
1151 public void deleteAclPortsLookup(AclInterface port, List<Uuid> aclList,
1152 List<AllowedAddressPairs> allowedAddresses) {
1153 String portId = port.getInterfaceId();
1154 LOG.trace("Deleting AclPortsLookup for port={}, acls={}, AAPs={}", portId, aclList, allowedAddresses);
1156 if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1157 LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
1162 for (Uuid aclId : aclList) {
1163 String aclName = aclId.getValue();
1164 jobCoordinator.enqueueJob(aclName, () -> {
1165 List<ListenableFuture<Void>> futures = new ArrayList<>();
1166 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1167 for (AllowedAddressPairs aap : allowedAddresses) {
1168 InstanceIdentifier<PortIds> path =
1169 AclServiceUtils.getPortIdsPathInAclPortsLookup(aclName, aap.getIpAddress(), portId);
1173 cleanUpStaleEntriesInAclPortsLookup(aclName, tx);
1180 private void cleanUpStaleEntriesInAclPortsLookup(String aclName, TypedWriteTransaction<Operational> tx) {
1181 AclPortsByIp aclPortsByIp = getAclPortsByIpFromOperDs(aclName);
1182 if (aclPortsByIp == null) {
1185 boolean deleteEntireAcl;
1186 List<AclIpPrefixes> ipPrefixes = aclPortsByIp.getAclIpPrefixes();
1187 if (ipPrefixes == null || ipPrefixes.isEmpty()) {
1188 deleteEntireAcl = true;
1190 boolean deleteMap = true;
1191 for (AclIpPrefixes ipPrefix : ipPrefixes) {
1192 if (ipPrefix.getPortIds() != null && !ipPrefix.getPortIds().isEmpty()) {
1197 deleteEntireAcl = deleteMap;
1199 if (deleteEntireAcl) {
1200 tx.delete(AclServiceUtils.aclPortsByIpPath(aclName));
1202 for (AclIpPrefixes ipPrefix : ipPrefixes) {
1203 if (ipPrefix.getPortIds() == null || ipPrefix.getPortIds().isEmpty()) {
1204 InstanceIdentifier<AclIpPrefixes> delPath =
1205 AclServiceUtils.getAclIpPrefixesPath(aclName, ipPrefix.getIpPrefix());
1213 private AclPortsByIp getAclPortsByIpFromOperDs(String aclName) {
1214 InstanceIdentifier<AclPortsByIp> path = aclPortsByIpPath(aclName);
1215 try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1216 return tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet().orNull();
1217 } catch (ReadFailedException e) {
1218 LOG.error("Failed to read ACL ports {}", path, e);
1224 private AclIpPrefixes getAclIpPrefixesFromOperDs(String aclName, IpPrefixOrAddress ipPrefix) {
1225 InstanceIdentifier<AclIpPrefixes> path = getAclIpPrefixesPath(aclName, ipPrefix);
1226 try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1227 return tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet().orNull();
1228 } catch (ReadFailedException e) {
1229 LOG.error("Failed to read ACL IP prefixes {}", path, e);
1235 * Gets the ace flow priority.
1237 * @param aclName the acl name
1238 * @return the ace flow priority
1240 public Integer getAceFlowPriority(String aclName) {
1241 Integer priority = AclConstants.ACE_DEFAULT_PRIORITY;
1242 Integer aclTag = getAclTag(new Uuid(aclName));
1243 if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
1244 // To handle overlapping rules, aclTag is added to priority
1247 LOG.warn("aclTag={} is null or invalid for aclName={}", aclTag, aclName);
1253 * Returns the hard timeout based on the protocol when a ACL rule removed from the instance.
1254 * It will returns the timeout configured in the {@link AclserviceConfig} class.
1256 * @param ace the ace
1257 * @param aclServiceUtils acl service utils
1258 * @return the hard time out
1260 public static Integer getHardTimoutForApplyStatefulChangeOnExistingTraffic(Ace ace,
1261 AclServiceUtils aclServiceUtils) {
1262 int hardTimeout = AclConstants.SECURITY_GROUP_ICMP_IDLE_TIME_OUT;
1263 Matches matches = ace.getMatches();
1264 AceIp acl = (AceIp) matches.getAceType();
1265 Short protocol = acl.getProtocol() != null ? acl.getProtocol().toJava() : null;
1266 if (protocol == null) {
1268 } else if (protocol == NwConstants.IP_PROT_TCP
1269 && aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout() != null) {
1270 hardTimeout = aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout().toJava();
1271 } else if (protocol == NwConstants.IP_PROT_UDP
1272 && aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout() != null) {
1273 hardTimeout = aclServiceUtils.getConfig().getSecurityGroupUdpIdleTimeout().toJava();
1279 * This method creates and returns the ct_mark instruction when a ACL rule removed from the
1280 * instance. This instruction will reset the ct_mark value and stops the existing traffics.
1282 * @param filterTable the filterTable
1283 * @param elanId the Elan id
1284 * @return list of instruction
1286 public static List<InstructionInfo> createCtMarkInstructionForNewState(Short filterTable, Long elanId) {
1288 List<InstructionInfo> instructions = new ArrayList<>();
1289 List<ActionInfo> actionsInfos = new ArrayList<>();
1290 List<NxCtAction> ctActionsList = new ArrayList<>();
1291 NxCtAction nxCtMarkClearAction = new ActionNxConntrack.NxCtMark(AclConstants.CT_MARK_NEW_STATE);
1292 ctActionsList.add(nxCtMarkClearAction);
1294 ActionNxConntrack actionNxConntrack = new ActionNxConntrack(2, 1, 0, elanId.intValue(),
1295 (short) 255, ctActionsList);
1296 actionsInfos.add(actionNxConntrack);
1297 instructions.add(new InstructionApplyActions(actionsInfos));
1298 instructions.add(new InstructionGotoTable(filterTable));
1300 return instructions;
1303 public static List<AllowedAddressPairs> excludeMulticastAAPs(@Nullable List<AllowedAddressPairs> allowedAddresses) {
1304 List<AllowedAddressPairs> filteredAAPs = new ArrayList<>();
1305 if (allowedAddresses != null) {
1306 for (AllowedAddressPairs allowedAddress : allowedAddresses) {
1307 InetAddress inetAddr = getInetAddress(allowedAddress.getIpAddress());
1308 if (inetAddr != null && !inetAddr.isMulticastAddress()) {
1309 filteredAAPs.add(allowedAddress);
1313 return filteredAAPs;
1316 public static String getRecoverServiceRegistryKey() {
1317 return NetvirtAcl.class.toString();
1321 private static InetAddress getInetAddress(IpPrefixOrAddress ipPrefixOrAddress) {
1324 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
1325 if (ipPrefix != null) {
1326 addr = ipPrefix.stringValue().split("/")[0];
1328 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
1329 if (ipAddress == null) {
1330 LOG.error("Invalid address : {}", ipPrefixOrAddress);
1333 addr = ipAddress.stringValue();
1337 return InetAddress.getByName(addr);
1338 } catch (UnknownHostException e) {
1339 LOG.error("Invalid address : {}", addr, e);
1344 public static Boolean isIpv6Subnet(List<SubnetInfo> subnetInfoList) {
1345 if (subnetInfoList != null && !subnetInfoList.isEmpty()) {
1346 for (SubnetInfo subnetInfo : subnetInfoList) {
1347 if (subnetInfo != null && IpVersionV6.class.equals(subnetInfo.getIpVersion())) {
1356 * Gets the subnet difference by performing (subnetInfo1 - subnetInfo2).
1358 * @param subnetInfo1 the subnet info 1
1359 * @param subnetInfo2 the subnet info 2
1360 * @return the subnet diff
1362 public static List<SubnetInfo> getSubnetDiff(List<SubnetInfo> subnetInfo1, List<SubnetInfo> subnetInfo2) {
1363 if (subnetInfo1 == null) {
1364 return Collections.emptyList();
1366 List<SubnetInfo> newSubnetList = new ArrayList<>(subnetInfo1);
1367 if (subnetInfo2 == null) {
1368 return newSubnetList;
1370 newSubnetList.removeAll(subnetInfo2);
1371 return newSubnetList;