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.OPERATIONAL;
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;
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;
148 public final class AclServiceUtils {
150 private static final Logger LOG = LoggerFactory.getLogger(AclServiceUtils.class);
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;
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;
171 * Retrieves the Interface from the datastore.
172 * @param broker the data broker
173 * @param interfaceName the interface name
174 * @return the interface.
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));
182 * Builds the interface identifier.
183 * @param interfaceName the interface name.
184 * @return the interface identifier.
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)
190 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
191 .Interface.class, new InterfaceKey(interfaceName)).build();
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.
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();
213 * Retrieves the interface state.
214 * @param dataBroker the data broker.
215 * @param interfaceName the interface name.
216 * @return the interface state.
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();
227 * Build the interface state.
228 * @param interfaceName the interface name.
229 * @return the interface state.
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();
242 * Retrieves the security rule attribute augmentation from the access list.
243 * @param ace the access list entry
244 * @return the security rule attributes
247 public static SecurityRuleAttr getAccessListAttributes(Ace ace) {
249 LOG.error("Ace is Null");
252 SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
253 if (aceAttributes == null) {
254 LOG.error("Ace is null");
257 return aceAttributes;
261 * Returns the DHCP match.
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.
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));
281 * Returns the DHCPv6 match.
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.
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));
301 * Returns the ICMPv6 match.
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.
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);
315 matches.add(new MatchIcmpv6((short) icmpType, (short) icmpCode));
317 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
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));
329 public static List<MatchInfoBase> buildL2BroadcastMatches() {
330 List<MatchInfoBase> matches = new ArrayList<>();
331 matches.add(new MatchEthernetDestination(new MacAddress(AclConstants.BROADCAST_MAC)));
336 * Builds the service id.
338 * @param interfaceName the interface name
339 * @param serviceIndex the service index
340 * @param serviceMode the service mode
341 * @return the instance identifier
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();
351 * Gets the bound services.
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
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();
369 public static List<Uuid> getUpdatedAclList(List<Uuid> updatedAclList, List<Uuid> currentAclList) {
370 if (updatedAclList == null) {
371 return Collections.emptyList();
373 List<Uuid> newAclList = new ArrayList<>(updatedAclList);
374 if (currentAclList == null) {
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())) {
390 public static List<AllowedAddressPairs> getUpdatedAllowedAddressPairs(
391 @Nullable List<AllowedAddressPairs> updatedAllowedAddressPairs,
392 @Nullable List<AllowedAddressPairs> currentAllowedAddressPairs) {
393 if (updatedAllowedAddressPairs == null) {
396 List<AllowedAddressPairs> newAllowedAddressPairs = new ArrayList<>(updatedAllowedAddressPairs);
397 if (currentAllowedAddressPairs == null) {
398 return newAllowedAddressPairs;
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())) {
410 return newAllowedAddressPairs;
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));
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()));
436 return ipBroadcastAddresses;
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]);
444 for (int j = 0; j < cidrPart; ++j) {
445 netmask |= 1 << 31 - j;
447 int network = address & netmask;
448 int broadcast = network | ~netmask;
449 return InetAddresses.toAddrString(InetAddresses.fromInteger(broadcast));
453 * Builds the ip matches.
455 * @param ipPrefixOrAddress the ip prefix or address
456 * @param matchCriteria the source_ip or destination_ip used for the match
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));
472 flowMatches.add(MatchEthernetType.IPV6);
473 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
474 ipPrefix.getIpv6Prefix()) : new MatchIpv6Destination(ipPrefix.getIpv6Prefix()));
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"));
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"));
494 * Builds the arp ip matches.
495 * @param ipPrefixOrAddress the ip prefix or address
496 * @return the MatchInfoBase list
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));
507 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
508 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
509 flowMatches.add(new MatchArpSpa(ipAddress.getIpv4Address().getValue(), "32"));
515 public static MatchInfoBase buildRemoteAclTagMetadataMatch(Integer remoteAclTag) {
516 return new MatchMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
517 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
520 public static BigInteger getRemoteAclTagMetadata(BigInteger remoteAclTag) {
521 return remoteAclTag.shiftLeft(4);
524 public static BigInteger getDropFlowCookie(int lport) {
525 return MetaDataUtil.getLportTagMetaData(lport).or(AclConstants.COOKIE_ACL_DROP_FLOW);
529 * Does IPv4 address exists in the list of allowed address pair.
531 * @param aaps the allowed address pairs
532 * @return true, if successful
534 public static boolean doesIpv4AddressExists(List<AllowedAddressPairs> aaps) {
538 for (AllowedAddressPairs aap : aaps) {
539 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
540 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
541 if (ipPrefix != null) {
542 if (ipPrefix.getIpv4Prefix() != null) {
546 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
547 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
556 * Does IPv6 address exists in the list of allowed address pair.
558 * @param aaps the allowed address pairs
559 * @return true, if successful
561 public static boolean doesIpv6AddressExists(List<AllowedAddressPairs> aaps) {
565 for (AllowedAddressPairs aap : aaps) {
566 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
567 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
568 if (ipPrefix != null) {
569 if (ipPrefix.getIpv6Prefix() != null) {
573 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
574 if (ipAddress != null && ipAddress.getIpv6Address() != null) {
583 * Gets the lport tag match.
584 * Ingress match is based on metadata and egress match is based on masked reg6
586 * @param lportTag the lport tag
587 * @param serviceMode ingress or egress service mode
588 * @return the lport tag match
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());
595 return new MatchMetadata(MetaDataUtil.getLportTagMetaData(lportTag), MetaDataUtil.METADATA_MASK_LPORT_TAG);
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));
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));
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));
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));
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);
644 public static InstructionWriteMetadata getWriteMetadataForDropFlag() {
645 return new InstructionWriteMetadata(MetaDataUtil.getAclDropMetaData(AclConstants.METADATA_DROP_FLAG),
646 MetaDataUtil.METADATA_MASK_ACL_DROP);
649 public static InstructionWriteMetadata getWriteMetadataForRemoteAclTag(Integer remoteAclTag) {
650 return new InstructionWriteMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
651 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
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);
661 public AclserviceConfig getConfig() {
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) {
673 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
674 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
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)) {
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)) {
699 public static boolean isNotIpAllNetwork(AllowedAddressPairs aap) {
700 return isNotIpv4AllNetwork(aap) && isNotIpv6AllNetwork(aap);
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();
714 public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName,DataBroker broker) {
715 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
716 return read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
719 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
720 return InstanceIdentifier.builder(ElanInterfaces.class)
721 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
724 // elan-instances config container
726 public static ElanInstance getElanInstanceByName(String elanInstanceName, DataBroker broker) {
727 InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
728 return read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
731 public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
732 return InstanceIdentifier.builder(ElanInstances.class)
733 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
737 public List<SubnetInfo> getSubnetInfo(String portId) {
738 InstanceIdentifier<PortSubnet> id = InstanceIdentifier.builder(PortSubnets.class)
739 .child(PortSubnet.class, new PortSubnetKey(portId)).build();
741 Optional<PortSubnet> portSubnet = read(dataBroker, LogicalDatastoreType.OPERATIONAL, id);
742 if (portSubnet.isPresent()) {
743 return portSubnet.get().getSubnetInfo();
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);
755 public static Integer allocateId(IdManagerService idManager, String poolName, String idKey, Integer defaultId) {
756 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
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);
765 LOG.error("RPC Call to Get Unique Id for key {} from pool {} returned with Errors {}",
766 idKey, poolName, rpcResult.getErrors());
768 } catch (InterruptedException | ExecutionException e) {
769 LOG.error("Exception when getting Unique Id for key {} from pool {} ", idKey, poolName, e);
774 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
775 ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
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());
782 LOG.debug("Released ACL ID with key: {} from pool: {}", idKey, poolName);
784 } catch (InterruptedException | ExecutionException e) {
785 LOG.error("Exception when releasing Id for key {} from pool {} ", idKey, poolName, e);
790 * Gets the ACL tag from cache. If not found in cache, tries to allocate and
793 * @param aclId the acl id
794 * @return the acl tag
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);
813 * @param aclName the ACL name
814 * @return the integer
816 public Integer allocateAclTag(String aclName) {
817 return AclServiceUtils.allocateId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName,
818 AclConstants.INVALID_ACL_TAG);
824 * @param aclName the ACL name
826 public void releaseAclTag(String aclName) {
827 AclServiceUtils.releaseId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName);
831 * Indicates whether the interface has port security enabled.
833 * @param aclInterface the interface.
834 * @return true if port is security enabled.
836 public static boolean isOfInterest(AclInterface aclInterface) {
837 return aclInterface != null && aclInterface.isPortSecurityEnabled();
841 * Creates the id pool for ACL tag.
843 * @param poolName the pool name
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();
850 Future<RpcResult<CreateIdPoolOutput>> result = this.idManager.createIdPool(createPool);
851 if (result != null && result.get().isSuccessful()) {
852 LOG.debug("Created IdPool for {}", poolName);
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);
863 * @param poolName the pool name
865 public void deleteIdPool(String poolName) {
866 DeleteIdPoolInput deletePool = new DeleteIdPoolInputBuilder().setPoolName(poolName).build();
868 Future<RpcResult<DeleteIdPoolOutput>> result = this.idManager.deleteIdPool(deletePool);
869 if (result != null && result.get().isSuccessful()) {
870 LOG.debug("Deleted IdPool for {}", poolName);
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);
879 * Creates remote the acl id pools.
881 public void createRemoteAclIdPool() {
882 createIdPoolForAclTag(AclConstants.ACL_TAG_POOL_NAME);
886 * Delete remote the acl id pools.
888 public void deleteRemoteAclIdPool() {
889 deleteIdPool(AclConstants.ACL_TAG_POOL_NAME);
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);
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);
925 public static List<? extends MatchInfoBase> buildIpAndDstServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
926 List<MatchInfoBase> flowMatches = new ArrayList<>();
927 flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
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);
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);
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;
972 * Builds the ip protocol matches.
974 * @param etherType the ether type
975 * @param protocol the protocol
976 * @return the list of matches.
978 public static List<MatchInfoBase> buildIpProtocolMatches(MatchEthernetType etherType, IPProtocols protocol) {
979 return Lists.newArrayList(etherType, new MatchIpProtocol(protocol.shortValue()));
983 * Does ACE have remote group id.
985 * @param aceAttr the ace attr
986 * @return true, if successful
988 public static boolean doesAceHaveRemoteGroupId(final SecurityRuleAttr aceAttr) {
989 return aceAttr != null && aceAttr.getRemoteGroupId() != null;
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);
1001 return remoteAclTags;
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;
1010 for (Uuid aclId : aclIds) {
1011 Acl acl = this.aclDataUtil.getAcl(aclId.getValue());
1013 LOG.warn("ACL {} not found in cache.", aclId.getValue());
1016 remoteAclIds.addAll(getRemoteAclIdsByDirection(acl, direction));
1018 return remoteAclIds;
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());
1032 return remoteAclIds;
1036 * Skip delete in case of overlapping IP.
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
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
1052 public boolean skipDeleteInCaseOfOverlappingIP(String portId, Uuid remoteAclId, IpPrefixOrAddress ipPrefix,
1054 boolean skipDelete = false;
1055 if (addOrRemove != NwConstants.DEL_FLOW) {
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) {
1072 public static InstanceIdentifier<AclPortsByIp> aclPortsByIpPath(String aclName) {
1073 return InstanceIdentifier.builder(AclPortsLookup.class)
1074 .child(AclPortsByIp.class, new AclPortsByIpKey(aclName)).build();
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();
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))
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);
1097 List<Uuid> addedAcls = getUpdatedAclList(portAfter.getSecurityGroups(), portBefore.getSecurityGroups());
1098 if (addedAcls != null && !addedAcls.isEmpty()) {
1099 addAclPortsLookup(portAfter, addedAcls, portAfter.getAllowedAddressPairs());
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);
1111 List<Uuid> deletedAcls = getUpdatedAclList(portBefore.getSecurityGroups(), portAfter.getSecurityGroups());
1112 if (deletedAcls != null && !deletedAcls.isEmpty()) {
1113 deleteAclPortsLookup(portAfter, deletedAcls, portAfter.getAllowedAddressPairs());
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);
1122 if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1123 LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
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) {
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);
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);
1151 if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1152 LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
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);
1168 cleanUpStaleEntriesInAclPortsLookup(aclName, tx);
1175 private void cleanUpStaleEntriesInAclPortsLookup(String aclName, TypedWriteTransaction<Operational> tx) {
1176 AclPortsByIp aclPortsByIp = getAclPortsByIpFromOperDs(aclName);
1177 if (aclPortsByIp == null) {
1180 boolean deleteEntireAcl;
1181 List<AclIpPrefixes> ipPrefixes = aclPortsByIp.getAclIpPrefixes();
1182 if (ipPrefixes == null || ipPrefixes.isEmpty()) {
1183 deleteEntireAcl = true;
1185 boolean deleteMap = true;
1186 for (AclIpPrefixes ipPrefix : ipPrefixes) {
1187 if (ipPrefix.getPortIds() != null && !ipPrefix.getPortIds().isEmpty()) {
1192 deleteEntireAcl = deleteMap;
1194 if (deleteEntireAcl) {
1195 tx.delete(AclServiceUtils.aclPortsByIpPath(aclName));
1197 for (AclIpPrefixes ipPrefix : ipPrefixes) {
1198 if (ipPrefix.getPortIds() == null || ipPrefix.getPortIds().isEmpty()) {
1199 InstanceIdentifier<AclIpPrefixes> delPath =
1200 AclServiceUtils.getAclIpPrefixesPath(aclName, ipPrefix.getIpPrefix());
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);
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);
1230 * Gets the ace flow priority.
1232 * @param aclName the acl name
1233 * @return the ace flow priority
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
1242 LOG.warn("aclTag={} is null or invalid for aclName={}", aclTag, aclName);
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.
1251 * @param ace the ace
1252 * @param aclServiceUtils acl service utils
1253 * @return the hard time out
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) {
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();
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.
1275 * @param filterTable the filterTable
1276 * @param elanId the Elan id
1277 * @return list of instruction
1279 public static List<InstructionInfo> createCtMarkInstructionForNewState(Short filterTable, Long elanId) {
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);
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));
1293 return instructions;
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);
1306 return filteredAAPs;
1309 public static String getRecoverServiceRegistryKey() {
1310 return NetvirtAcl.class.toString();
1314 private static InetAddress getInetAddress(IpPrefixOrAddress ipPrefixOrAddress) {
1317 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
1318 if (ipPrefix != null) {
1319 addr = ipPrefix.stringValue().split("/")[0];
1321 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
1322 if (ipAddress == null) {
1323 LOG.error("Invalid address : {}", ipPrefixOrAddress);
1326 addr = ipAddress.stringValue();
1330 return InetAddress.getByName(addr);
1331 } catch (UnknownHostException e) {
1332 LOG.error("Invalid address : {}", addr, e);
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())) {
1349 * Gets the subnet difference by performing (subnetInfo1 - subnetInfo2).
1351 * @param subnetInfo1 the subnet info 1
1352 * @param subnetInfo2 the subnet info 2
1353 * @return the subnet diff
1355 public static List<SubnetInfo> getSubnetDiff(List<SubnetInfo> subnetInfo1, List<SubnetInfo> subnetInfo2) {
1356 if (subnetInfo1 == null) {
1357 return Collections.emptyList();
1359 List<SubnetInfo> newSubnetList = new ArrayList<>(subnetInfo1);
1360 if (subnetInfo2 == null) {
1361 return newSubnetList;
1363 newSubnetList.removeAll(subnetInfo2);
1364 return newSubnetList;