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.IpPrefixOrAddress;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddressBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpVersionV6;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.AclPortsByIp;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.AclPortsByIpKey;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.AclIpPrefixes;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.AclIpPrefixesKey;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIds;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIdsBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.acl.ports.lookup.acl.ports.by.ip.acl.ip.prefixes.PortIdsKey;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.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.
218 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
219 .@Nullable Interface getInterfaceStateFromOperDS(DataBroker dataBroker, String interfaceName) {
220 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
221 .interfaces.state.Interface> ifStateId = buildStateInterfaceId(interfaceName);
222 return MDSALUtil.read(LogicalDatastoreType.OPERATIONAL, ifStateId, dataBroker).orNull();
226 * Build the interface state.
227 * @param interfaceName the interface name.
228 * @return the interface state.
230 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
231 .interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
232 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
233 .interfaces.state.Interface> idBuilder = InstanceIdentifier.builder(InterfacesState.class)
234 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
235 .state.Interface.class, new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
236 .rev140508.interfaces.state.InterfaceKey(interfaceName));
237 return idBuilder.build();
241 * Retrieves the security rule attribute augmentation from the access list.
242 * @param ace the access list entry
243 * @return the security rule attributes
246 public static SecurityRuleAttr getAccessListAttributes(Ace ace) {
248 LOG.error("Ace is Null");
251 SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
252 if (aceAttributes == null) {
253 LOG.error("Ace is 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 BigInteger 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 for (Iterator<Uuid> iterator = newAclList.iterator(); iterator.hasNext();) {
378 Uuid updatedAclUuid = iterator.next();
379 for (Uuid currentAclUuid :origAclList) {
380 if (updatedAclUuid.getValue().equals(currentAclUuid.getValue())) {
389 public static List<AllowedAddressPairs> getUpdatedAllowedAddressPairs(
390 @Nullable List<AllowedAddressPairs> updatedAllowedAddressPairs,
391 @Nullable List<AllowedAddressPairs> currentAllowedAddressPairs) {
392 if (updatedAllowedAddressPairs == null) {
395 List<AllowedAddressPairs> newAllowedAddressPairs = new ArrayList<>(updatedAllowedAddressPairs);
396 if (currentAllowedAddressPairs == null) {
397 return newAllowedAddressPairs;
399 List<AllowedAddressPairs> origAllowedAddressPairs = new ArrayList<>(currentAllowedAddressPairs);
400 for (Iterator<AllowedAddressPairs> iterator = newAllowedAddressPairs.iterator(); iterator.hasNext();) {
401 AllowedAddressPairs updatedAllowedAddressPair = iterator.next();
402 for (AllowedAddressPairs currentAllowedAddressPair : origAllowedAddressPairs) {
403 if (updatedAllowedAddressPair.key().equals(currentAllowedAddressPair.key())) {
409 return newAllowedAddressPairs;
413 public static BigInteger getDpIdFromIterfaceState(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
414 .interfaces.rev140508.interfaces.state.Interface interfaceState) {
415 BigInteger dpId = null;
416 List<String> ofportIds = interfaceState.getLowerLayerIf();
417 if (ofportIds != null && !ofportIds.isEmpty()) {
418 NodeConnectorId nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
419 dpId = BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
424 public static List<String> getIpBroadcastAddresses(List<SubnetInfo> subnetInfoList) {
425 List<String> ipBroadcastAddresses = new ArrayList<>();
426 for (SubnetInfo subnetInfo : subnetInfoList) {
427 IpPrefix cidrIpPrefix = subnetInfo.getIpPrefix().getIpPrefix();
428 if (cidrIpPrefix != null) {
429 Ipv4Prefix cidrIpv4Prefix = cidrIpPrefix.getIpv4Prefix();
430 if (cidrIpv4Prefix != null) {
431 ipBroadcastAddresses.add(getBroadcastAddressFromCidr(cidrIpv4Prefix.getValue()));
435 return ipBroadcastAddresses;
438 public static String getBroadcastAddressFromCidr(String cidr) {
439 String[] ipaddressValues = cidr.split("/");
440 int address = InetAddresses.coerceToInteger(InetAddresses.forString(ipaddressValues[0]));
441 int cidrPart = Integer.parseInt(ipaddressValues[1]);
443 for (int j = 0; j < cidrPart; ++j) {
444 netmask |= 1 << 31 - j;
446 int network = address & netmask;
447 int broadcast = network | ~netmask;
448 return InetAddresses.toAddrString(InetAddresses.fromInteger(broadcast));
452 * Builds the ip matches.
454 * @param ipPrefixOrAddress the ip prefix or address
455 * @param matchCriteria the source_ip or destination_ip used for the match
458 public static List<MatchInfoBase> buildIpMatches(IpPrefixOrAddress ipPrefixOrAddress,
459 MatchCriteria matchCriteria) {
460 List<MatchInfoBase> flowMatches = new ArrayList<>();
461 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
462 if (ipPrefix != null) {
463 Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
464 if (ipv4Prefix != null) {
465 flowMatches.add(MatchEthernetType.IPV4);
466 if (!ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
467 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(ipv4Prefix)
468 : new MatchIpv4Destination(ipv4Prefix));
471 flowMatches.add(MatchEthernetType.IPV6);
472 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
473 ipPrefix.getIpv6Prefix()) : new MatchIpv6Destination(ipPrefix.getIpv6Prefix()));
476 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
477 if (ipAddress.getIpv4Address() != null) {
478 flowMatches.add(MatchEthernetType.IPV4);
479 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv4Source(
480 ipAddress.getIpv4Address().getValue(), "32") : new MatchIpv4Destination(
481 ipAddress.getIpv4Address().getValue(), "32"));
483 flowMatches.add(MatchEthernetType.IPV6);
484 flowMatches.add(matchCriteria == MatchCriteria.MATCH_SOURCE ? new MatchIpv6Source(
485 ipAddress.getIpv6Address().getValue() + "/128") : new MatchIpv6Destination(
486 ipAddress.getIpv6Address().getValue() + "/128"));
493 * Builds the arp ip matches.
494 * @param ipPrefixOrAddress the ip prefix or address
495 * @return the MatchInfoBase list
497 public static List<MatchInfoBase> buildArpIpMatches(IpPrefixOrAddress ipPrefixOrAddress) {
498 List<MatchInfoBase> flowMatches = new ArrayList<>();
499 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
500 if (ipPrefix != null) {
501 Ipv4Prefix ipv4Prefix = ipPrefix.getIpv4Prefix();
502 if (ipv4Prefix != null && !ipv4Prefix.getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
503 flowMatches.add(new MatchArpSpa(ipv4Prefix));
506 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
507 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
508 flowMatches.add(new MatchArpSpa(ipAddress.getIpv4Address().getValue(), "32"));
514 public static MatchInfoBase buildRemoteAclTagMetadataMatch(Integer remoteAclTag) {
515 return new MatchMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
516 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
519 public static BigInteger getRemoteAclTagMetadata(BigInteger remoteAclTag) {
520 return remoteAclTag.shiftLeft(4);
523 public static BigInteger getDropFlowCookie(int lport) {
524 return MetaDataUtil.getLportTagMetaData(lport).or(AclConstants.COOKIE_ACL_DROP_FLOW);
528 * Does IPv4 address exists in the list of allowed address pair.
530 * @param aaps the allowed address pairs
531 * @return true, if successful
533 public static boolean doesIpv4AddressExists(List<AllowedAddressPairs> aaps) {
537 for (AllowedAddressPairs aap : aaps) {
538 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
539 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
540 if (ipPrefix != null) {
541 if (ipPrefix.getIpv4Prefix() != null) {
545 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
546 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
555 * Does IPv6 address exists in the list of allowed address pair.
557 * @param aaps the allowed address pairs
558 * @return true, if successful
560 public static boolean doesIpv6AddressExists(List<AllowedAddressPairs> aaps) {
564 for (AllowedAddressPairs aap : aaps) {
565 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
566 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
567 if (ipPrefix != null) {
568 if (ipPrefix.getIpv6Prefix() != null) {
572 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
573 if (ipAddress != null && ipAddress.getIpv6Address() != null) {
582 * Gets the lport tag match.
583 * Ingress match is based on metadata and egress match is based on masked reg6
585 * @param lportTag the lport tag
586 * @param serviceMode ingress or egress service mode
587 * @return the lport tag match
589 public static MatchInfoBase buildLPortTagMatch(int lportTag, Class<? extends ServiceModeBase> serviceMode) {
590 if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
591 return new NxMatchRegister(NxmNxReg6.class, MetaDataUtil.getLportTagForReg6(lportTag).longValue(),
592 MetaDataUtil.getLportTagMaskForReg6());
594 return new MatchMetadata(MetaDataUtil.getLportTagMetaData(lportTag), MetaDataUtil.METADATA_MASK_LPORT_TAG);
598 public static List<MatchInfoBase> buildMatchesForLPortTagAndRemoteAclTag(Integer lportTag, Integer remoteAclTag,
599 Class<? extends ServiceModeBase> serviceMode) {
600 List<MatchInfoBase> matches = new ArrayList<>();
601 if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
602 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
603 matches.add(AclServiceUtils.buildRemoteAclTagMetadataMatch(remoteAclTag));
605 // In case of ingress service mode, only metadata is used for
606 // matching both lportTag and aclTag. Hence performing "or"
607 // operation on both lportTag and aclTag metadata.
608 BigInteger metaData = MetaDataUtil.getLportTagMetaData(lportTag)
609 .or(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)));
610 BigInteger metaDataMask =
611 MetaDataUtil.METADATA_MASK_LPORT_TAG.or(MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
612 matches.add(new MatchMetadata(metaData, metaDataMask));
617 public static Collection<? extends MatchInfoBase> buildMatchesForLPortTagAndConntrackClassifierType(int lportTag,
618 AclConntrackClassifierType conntrackClassifierType, Class<? extends ServiceModeBase> serviceMode) {
619 List<MatchInfoBase> matches = new ArrayList<>();
620 if (serviceMode != null && serviceMode.isAssignableFrom(ServiceModeEgress.class)) {
621 matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
622 matches.add(AclServiceUtils.buildAclConntrackClassifierTypeMatch(conntrackClassifierType));
624 // In case of ingress service mode, only metadata is used for
625 // matching both lportTag and conntrackClassifierType. Hence performing "or"
626 // operation on both lportTag and conntrackClassifierType metadata.
627 BigInteger metaData = MetaDataUtil.getLportTagMetaData(lportTag)
628 .or(MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(conntrackClassifierType.getValue()));
629 BigInteger metaDataMask =
630 MetaDataUtil.METADATA_MASK_LPORT_TAG.or(MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
631 matches.add(new MatchMetadata(metaData, metaDataMask));
636 public static InstructionWriteMetadata getWriteMetadataForAclClassifierType(
637 AclConntrackClassifierType conntrackClassifierType) {
638 return new InstructionWriteMetadata(
639 MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(conntrackClassifierType.getValue()),
640 MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
643 public static InstructionWriteMetadata getWriteMetadataForDropFlag() {
644 return new InstructionWriteMetadata(MetaDataUtil.getAclDropMetaData(AclConstants.METADATA_DROP_FLAG),
645 MetaDataUtil.METADATA_MASK_ACL_DROP);
648 public static InstructionWriteMetadata getWriteMetadataForRemoteAclTag(Integer remoteAclTag) {
649 return new InstructionWriteMetadata(getRemoteAclTagMetadata(BigInteger.valueOf(remoteAclTag)),
650 MetaDataUtil.METADATA_MASK_REMOTE_ACL_TAG);
653 public static MatchInfoBase buildAclConntrackClassifierTypeMatch(
654 AclConntrackClassifierType conntrackSupportedType) {
655 return new MatchMetadata(
656 MetaDataUtil.getAclConntrackClassifierTypeFromMetaData(conntrackSupportedType.getValue()),
657 MetaDataUtil.METADATA_MASK_ACL_CONNTRACK_CLASSIFIER_TYPE);
660 public AclserviceConfig getConfig() {
664 public static boolean isIPv4Address(AllowedAddressPairs aap) {
665 IpPrefixOrAddress ipPrefixOrAddress = aap.getIpAddress();
666 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
667 if (ipPrefix != null) {
668 if (ipPrefix.getIpv4Prefix() != null) {
672 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
673 if (ipAddress != null && ipAddress.getIpv4Address() != null) {
680 public static boolean isNotIpv4AllNetwork(AllowedAddressPairs aap) {
681 IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
682 if (ipPrefix != null && ipPrefix.getIpv4Prefix() != null
683 && ipPrefix.getIpv4Prefix().getValue().equals(AclConstants.IPV4_ALL_NETWORK)) {
689 protected static boolean isNotIpv6AllNetwork(AllowedAddressPairs aap) {
690 IpPrefix ipPrefix = aap.getIpAddress().getIpPrefix();
691 if (ipPrefix != null && ipPrefix.getIpv6Prefix() != null
692 && ipPrefix.getIpv6Prefix().getValue().equals(AclConstants.IPV6_ALL_NETWORK)) {
698 public static boolean isNotIpAllNetwork(AllowedAddressPairs aap) {
699 return isNotIpv4AllNetwork(aap) && isNotIpv6AllNetwork(aap);
703 public static Long getElanIdFromInterface(String elanInterfaceName, DataBroker broker) {
704 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(elanInterfaceName, broker);
705 if (null != elanInterface) {
706 ElanInstance elanInfo = getElanInstanceByName(elanInterface.getElanInstanceName(), broker);
707 return elanInfo.getElanTag();
713 public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName,DataBroker broker) {
714 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
715 return read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
718 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
719 return InstanceIdentifier.builder(ElanInterfaces.class)
720 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
723 // elan-instances config container
725 public static ElanInstance getElanInstanceByName(String elanInstanceName, DataBroker broker) {
726 InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
727 return read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
730 public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
731 return InstanceIdentifier.builder(ElanInstances.class)
732 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
735 public void deleteAcesFromConfigDS(String aclName, List<Ace> deletedAceRules) {
736 List<List<Ace>> acesParts = Lists.partition(deletedAceRules, AclConstants.ACES_PER_TRANSACTION);
737 for (List<Ace> acePart : acesParts) {
738 jobCoordinator.enqueueJob(aclName,
739 () -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
741 for (Ace ace: acePart) {
742 InstanceIdentifier<Ace> id = InstanceIdentifier.builder(AccessLists.class)
743 .child(Acl.class, new AclKey(aclName, Ipv4Acl.class)).child(AccessListEntries.class)
744 .child(Ace.class, ace.key()).build();
747 })), AclConstants.ACEDELETE_MAX_RETRIES);
751 public static Integer allocateId(IdManagerService idManager, String poolName, String idKey, Integer defaultId) {
752 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
754 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
755 RpcResult<AllocateIdOutput> rpcResult = result.get();
756 if (rpcResult.isSuccessful()) {
757 Integer allocatedId = rpcResult.getResult().getIdValue().intValue();
758 LOG.debug("Allocated ACL ID: {} with key: {} into pool: {}", allocatedId, idKey, poolName);
761 LOG.error("RPC Call to Get Unique Id for key {} from pool {} returned with Errors {}",
762 idKey, poolName, rpcResult.getErrors());
764 } catch (InterruptedException | ExecutionException e) {
765 LOG.error("Exception when getting Unique Id for key {} from pool {} ", idKey, poolName, e);
770 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
771 ReleaseIdInput idInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
773 RpcResult<ReleaseIdOutput> rpcResult = idManager.releaseId(idInput).get();
774 if (!rpcResult.isSuccessful()) {
775 LOG.error("RPC Call to release Id with Key {} from pool {} returned with Errors {}",
776 idKey, poolName, rpcResult.getErrors());
778 LOG.debug("Released ACL ID with key: {} from pool: {}", idKey, poolName);
780 } catch (InterruptedException | ExecutionException e) {
781 LOG.error("Exception when releasing Id for key {} from pool {} ", idKey, poolName, e);
786 * Gets the ACL tag from cache. If not found in cache, tries to allocate and
789 * @param aclId the acl id
790 * @return the acl tag
793 public Integer getAclTag(final Uuid aclId) {
794 String aclName = aclId.getValue();
795 Integer aclTag = this.aclDataUtil.getAclTag(aclName);
796 if (aclTag == null) {
797 LOG.debug("ACL tag not found in cache for ACL={}, trying to allocate again.", aclName);
798 aclTag = allocateAclTag(aclName);
799 if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
800 this.aclDataUtil.addAclTag(aclName, aclTag);
809 * @param aclName the ACL name
810 * @return the integer
812 public Integer allocateAclTag(String aclName) {
813 return AclServiceUtils.allocateId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName,
814 AclConstants.INVALID_ACL_TAG);
820 * @param aclName the ACL name
822 public void releaseAclTag(String aclName) {
823 AclServiceUtils.releaseId(this.idManager, AclConstants.ACL_TAG_POOL_NAME, aclName);
827 * Indicates whether the interface has port security enabled.
829 * @param aclInterface the interface.
830 * @return true if port is security enabled.
832 public static boolean isOfInterest(AclInterface aclInterface) {
833 return aclInterface != null && aclInterface.isPortSecurityEnabled();
837 * Creates the id pool for ACL tag.
839 * @param poolName the pool name
841 private void createIdPoolForAclTag(String poolName) {
842 CreateIdPoolInput createPool = new CreateIdPoolInputBuilder()
843 .setPoolName(poolName).setLow(AclConstants.ACL_TAG_POOL_START)
844 .setHigh(AclConstants.ACL_TAG_POOL_END).build();
846 Future<RpcResult<CreateIdPoolOutput>> result = this.idManager.createIdPool(createPool);
847 if (result != null && result.get().isSuccessful()) {
848 LOG.debug("Created IdPool for {}", poolName);
850 } catch (InterruptedException | ExecutionException e) {
851 LOG.error("Failed to create ID pool [{}] for remote ACL ids", poolName, e);
852 throw new RuntimeException("Failed to create ID pool [{}] for remote ACL ids", e);
859 * @param poolName the pool name
861 public void deleteIdPool(String poolName) {
862 DeleteIdPoolInput deletePool = new DeleteIdPoolInputBuilder().setPoolName(poolName).build();
864 Future<RpcResult<DeleteIdPoolOutput>> result = this.idManager.deleteIdPool(deletePool);
865 if (result != null && result.get().isSuccessful()) {
866 LOG.debug("Deleted IdPool for {}", poolName);
868 } catch (InterruptedException | ExecutionException e) {
869 LOG.error("Failed to delete ID pool [{}]", poolName, e);
870 throw new RuntimeException("Failed to delete ID pool [" + poolName + "]", e);
875 * Creates remote the acl id pools.
877 public void createRemoteAclIdPool() {
878 createIdPoolForAclTag(AclConstants.ACL_TAG_POOL_NAME);
882 * Delete remote the acl id pools.
884 public void deleteRemoteAclIdPool() {
885 deleteIdPool(AclConstants.ACL_TAG_POOL_NAME);
888 public static List<? extends MatchInfoBase> buildIpAndSrcServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
889 List<MatchInfoBase> flowMatches = new ArrayList<>();
890 flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
891 if (aap.getIpAddress().getIpAddress() != null) {
892 if (aap.getIpAddress().getIpAddress().getIpv4Address() != null) {
893 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
894 flowMatches.add(ipv4EthMatch);
895 MatchIpv4Source srcMatch = new MatchIpv4Source(
896 new Ipv4Prefix(aap.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
897 flowMatches.add(srcMatch);
898 } else if (aap.getIpAddress().getIpAddress().getIpv6Address() != null) {
899 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
900 flowMatches.add(ipv6EthMatch);
901 MatchIpv6Source srcMatch = new MatchIpv6Source(
902 new Ipv6Prefix(aap.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
903 flowMatches.add(srcMatch);
905 } else if (aap.getIpAddress().getIpPrefix() != null) {
906 if (aap.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
907 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
908 flowMatches.add(ipv4EthMatch);
909 MatchIpv4Source srcMatch = new MatchIpv4Source(aap.getIpAddress().getIpPrefix().getIpv4Prefix());
910 flowMatches.add(srcMatch);
911 } else if (aap.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
912 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
913 flowMatches.add(ipv6EthMatch);
914 MatchIpv6Source srcMatch = new MatchIpv6Source(aap.getIpAddress().getIpPrefix().getIpv6Prefix());
915 flowMatches.add(srcMatch);
921 public static List<? extends MatchInfoBase> buildIpAndDstServiceMatch(Integer aclTag, AllowedAddressPairs aap) {
922 List<MatchInfoBase> flowMatches = new ArrayList<>();
923 flowMatches.add(buildRemoteAclTagMetadataMatch(aclTag));
925 if (aap.getIpAddress().getIpAddress() != null) {
926 if (aap.getIpAddress().getIpAddress().getIpv4Address() != null) {
927 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
928 flowMatches.add(ipv4EthMatch);
929 MatchIpv4Destination dstMatch = new MatchIpv4Destination(
930 new Ipv4Prefix(aap.getIpAddress().getIpAddress().getIpv4Address().getValue() + "/32"));
931 flowMatches.add(dstMatch);
932 } else if (aap.getIpAddress().getIpAddress().getIpv6Address() != null) {
933 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
934 flowMatches.add(ipv6EthMatch);
935 MatchIpv6Destination dstMatch = new MatchIpv6Destination(
936 new Ipv6Prefix(aap.getIpAddress().getIpAddress().getIpv6Address().getValue() + "/128"));
937 flowMatches.add(dstMatch);
939 } else if (aap.getIpAddress().getIpPrefix() != null) {
940 if (aap.getIpAddress().getIpPrefix().getIpv4Prefix() != null) {
941 MatchEthernetType ipv4EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV4);
942 flowMatches.add(ipv4EthMatch);
943 MatchIpv4Destination dstMatch =
944 new MatchIpv4Destination(aap.getIpAddress().getIpPrefix().getIpv4Prefix());
945 flowMatches.add(dstMatch);
946 } else if (aap.getIpAddress().getIpPrefix().getIpv6Prefix() != null) {
947 MatchEthernetType ipv6EthMatch = new MatchEthernetType(NwConstants.ETHTYPE_IPV6);
948 flowMatches.add(ipv6EthMatch);
949 MatchIpv6Destination dstMatch =
950 new MatchIpv6Destination(aap.getIpAddress().getIpPrefix().getIpv6Prefix());
951 flowMatches.add(dstMatch);
957 public static boolean isOfAclInterest(Acl acl) {
958 if (acl.getAccessListEntries() != null) {
959 List<Ace> aceList = acl.getAccessListEntries().getAce();
960 if (aceList != null && !aceList.isEmpty()) {
961 return aceList.get(0).augmentation(SecurityRuleAttr.class) != null;
968 * Builds the ip protocol matches.
970 * @param etherType the ether type
971 * @param protocol the protocol
972 * @return the list of matches.
974 public static List<MatchInfoBase> buildIpProtocolMatches(MatchEthernetType etherType, IPProtocols protocol) {
975 return Lists.newArrayList(etherType, new MatchIpProtocol(protocol.shortValue()));
979 * Does ACE have remote group id.
981 * @param aceAttr the ace attr
982 * @return true, if successful
984 public static boolean doesAceHaveRemoteGroupId(final SecurityRuleAttr aceAttr) {
985 return aceAttr != null && aceAttr.getRemoteGroupId() != null;
988 public SortedSet<Integer> getRemoteAclTags(@Nullable List<Uuid> aclIds, Class<? extends DirectionBase> direction) {
989 SortedSet<Integer> remoteAclTags = new TreeSet<>();
990 Set<Uuid> remoteAclIds = getRemoteAclIdsByDirection(aclIds, direction);
991 for (Uuid remoteAclId : remoteAclIds) {
992 Integer remoteAclTag = getAclTag(remoteAclId);
993 if (remoteAclTag != null && remoteAclTag != AclConstants.INVALID_ACL_TAG) {
994 remoteAclTags.add(remoteAclTag);
997 return remoteAclTags;
1000 public Set<Uuid> getRemoteAclIdsByDirection(@Nullable List<Uuid> aclIds, Class<? extends DirectionBase> direction) {
1001 Set<Uuid> remoteAclIds = new HashSet<>();
1002 if (aclIds == null || aclIds.isEmpty()) {
1003 return remoteAclIds;
1006 for (Uuid aclId : aclIds) {
1007 Acl acl = this.aclDataUtil.getAcl(aclId.getValue());
1009 LOG.warn("ACL {} not found in cache.", aclId.getValue());
1012 remoteAclIds.addAll(getRemoteAclIdsByDirection(acl, direction));
1014 return remoteAclIds;
1017 public static Set<Uuid> getRemoteAclIdsByDirection(Acl acl, Class<? extends DirectionBase> direction) {
1018 Set<Uuid> remoteAclIds = new HashSet<>();
1019 AccessListEntries accessListEntries = acl.getAccessListEntries();
1020 if (accessListEntries != null && accessListEntries.getAce() != null) {
1021 for (Ace ace : accessListEntries.getAce()) {
1022 SecurityRuleAttr aceAttr = AclServiceUtils.getAccessListAttributes(ace);
1023 if (Objects.equals(aceAttr.getDirection(), direction) && doesAceHaveRemoteGroupId(aceAttr)) {
1024 remoteAclIds.add(aceAttr.getRemoteGroupId());
1028 return remoteAclIds;
1032 * Skip delete in case of overlapping IP.
1035 * When there are multiple ports (e.g., p1, p2, p3) having same AAP (e.g.,
1036 * 224.0.0.5) configured which are part of single SG, there would be single
1037 * flow in remote ACL table. When one of these ports (say p1) is deleted,
1038 * the single flow which is configured in remote ACL table shouldn't be
1039 * deleted. It should be deleted only when there are no more references to
1042 * @param portId the port id
1043 * @param remoteAclId the remote Acl Id
1044 * @param ipPrefix the ip prefix
1045 * @param addOrRemove the add or remove
1046 * @return true, if successful
1048 public boolean skipDeleteInCaseOfOverlappingIP(String portId, Uuid remoteAclId, IpPrefixOrAddress ipPrefix,
1050 boolean skipDelete = false;
1051 if (addOrRemove != NwConstants.DEL_FLOW) {
1054 AclIpPrefixes aclIpPrefixes = getAclIpPrefixesFromOperDs(remoteAclId.getValue(), ipPrefix);
1055 if (aclIpPrefixes != null && aclIpPrefixes.getPortIds() != null) {
1056 List<String> ignorePorts = Lists.newArrayList(portId);
1057 List<PortIds> portIds = new ArrayList<>(aclIpPrefixes.getPortIds());
1058 // Checking if there are any other ports excluding ignorePorts
1059 long noOfRemotePorts =
1060 portIds.stream().map(PortIds::getPortId).filter(y -> !ignorePorts.contains(y)).count();
1061 if (noOfRemotePorts > 0) {
1068 public static InstanceIdentifier<AclPortsByIp> aclPortsByIpPath(String aclName) {
1069 return InstanceIdentifier.builder(AclPortsLookup.class)
1070 .child(AclPortsByIp.class, new AclPortsByIpKey(aclName)).build();
1073 public static InstanceIdentifier<AclIpPrefixes> getAclIpPrefixesPath(String aclName, IpPrefixOrAddress ipPrefix) {
1074 return InstanceIdentifier.builder(AclPortsLookup.class).child(AclPortsByIp.class, new AclPortsByIpKey(aclName))
1075 .child(AclIpPrefixes.class, new AclIpPrefixesKey(ipPrefix)).build();
1078 public static InstanceIdentifier<PortIds> getPortIdsPathInAclPortsLookup(String ruleName,
1079 IpPrefixOrAddress ipPrefix, String portId) {
1080 return InstanceIdentifier.builder(AclPortsLookup.class).child(AclPortsByIp.class, new AclPortsByIpKey(ruleName))
1081 .child(AclIpPrefixes.class, new AclIpPrefixesKey(ipPrefix)).child(PortIds.class, new PortIdsKey(portId))
1085 public void addAclPortsLookupForInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
1086 LOG.debug("Processing interface additions for port {}", portAfter.getInterfaceId());
1087 List<AllowedAddressPairs> addedAllowedAddressPairs = getUpdatedAllowedAddressPairs(
1088 portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
1089 if (addedAllowedAddressPairs != null && !addedAllowedAddressPairs.isEmpty()) {
1090 addAclPortsLookup(portAfter, portAfter.getSecurityGroups(), addedAllowedAddressPairs);
1093 List<Uuid> addedAcls = getUpdatedAclList(portAfter.getSecurityGroups(), portBefore.getSecurityGroups());
1094 if (addedAcls != null && !addedAcls.isEmpty()) {
1095 addAclPortsLookup(portAfter, addedAcls, portAfter.getAllowedAddressPairs());
1099 public void deleteAclPortsLookupForInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
1100 LOG.debug("Processing interface removals for port {}", portAfter.getInterfaceId());
1101 List<AllowedAddressPairs> deletedAllowedAddressPairs = getUpdatedAllowedAddressPairs(
1102 portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
1103 if (deletedAllowedAddressPairs != null && !deletedAllowedAddressPairs.isEmpty()) {
1104 deleteAclPortsLookup(portAfter, portAfter.getSecurityGroups(), deletedAllowedAddressPairs);
1107 List<Uuid> deletedAcls = getUpdatedAclList(portBefore.getSecurityGroups(), portAfter.getSecurityGroups());
1108 if (deletedAcls != null && !deletedAcls.isEmpty()) {
1109 deleteAclPortsLookup(portAfter, deletedAcls, portAfter.getAllowedAddressPairs());
1113 public void addAclPortsLookup(AclInterface port, List<Uuid> aclList,
1114 List<AllowedAddressPairs> allowedAddresses) {
1115 String portId = port.getInterfaceId();
1116 LOG.trace("Adding AclPortsLookup for port={}, acls={}, AAPs={}", portId, aclList, allowedAddresses);
1118 if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1119 LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
1124 for (Uuid aclId : aclList) {
1125 String aclName = aclId.getValue();
1126 jobCoordinator.enqueueJob(aclName, () -> {
1127 List<ListenableFuture<Void>> futures = new ArrayList<>();
1128 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1129 for (AllowedAddressPairs aap : allowedAddresses) {
1131 new PortIdsBuilder().withKey(new PortIdsKey(portId)).setPortId(portId).build();
1132 InstanceIdentifier<PortIds> path =
1133 AclServiceUtils.getPortIdsPathInAclPortsLookup(aclName, aap.getIpAddress(), portId);
1134 tx.put(path, portIdObj, CREATE_MISSING_PARENTS);
1142 public void deleteAclPortsLookup(AclInterface port, List<Uuid> aclList,
1143 List<AllowedAddressPairs> allowedAddresses) {
1144 String portId = port.getInterfaceId();
1145 LOG.trace("Deleting AclPortsLookup for port={}, acls={}, AAPs={}", portId, aclList, allowedAddresses);
1147 if (aclList == null || allowedAddresses == null || allowedAddresses.isEmpty()) {
1148 LOG.warn("aclList or allowedAddresses is null. port={}, acls={}, AAPs={}", portId, aclList,
1153 for (Uuid aclId : aclList) {
1154 String aclName = aclId.getValue();
1155 jobCoordinator.enqueueJob(aclName, () -> {
1156 List<ListenableFuture<Void>> futures = new ArrayList<>();
1157 futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(OPERATIONAL, tx -> {
1158 for (AllowedAddressPairs aap : allowedAddresses) {
1159 InstanceIdentifier<PortIds> path =
1160 AclServiceUtils.getPortIdsPathInAclPortsLookup(aclName, aap.getIpAddress(), portId);
1164 cleanUpStaleEntriesInAclPortsLookup(aclName, tx);
1171 private void cleanUpStaleEntriesInAclPortsLookup(String aclName, TypedWriteTransaction<Operational> tx) {
1172 AclPortsByIp aclPortsByIp = getAclPortsByIpFromOperDs(aclName);
1173 if (aclPortsByIp == null) {
1176 boolean deleteEntireAcl;
1177 List<AclIpPrefixes> ipPrefixes = aclPortsByIp.getAclIpPrefixes();
1178 if (ipPrefixes == null || ipPrefixes.isEmpty()) {
1179 deleteEntireAcl = true;
1181 boolean deleteMap = true;
1182 for (AclIpPrefixes ipPrefix : ipPrefixes) {
1183 if (ipPrefix.getPortIds() != null && !ipPrefix.getPortIds().isEmpty()) {
1188 deleteEntireAcl = deleteMap;
1190 if (deleteEntireAcl) {
1191 tx.delete(AclServiceUtils.aclPortsByIpPath(aclName));
1193 for (AclIpPrefixes ipPrefix : ipPrefixes) {
1194 if (ipPrefix.getPortIds() == null || ipPrefix.getPortIds().isEmpty()) {
1195 InstanceIdentifier<AclIpPrefixes> delPath =
1196 AclServiceUtils.getAclIpPrefixesPath(aclName, ipPrefix.getIpPrefix());
1204 private AclPortsByIp getAclPortsByIpFromOperDs(String aclName) {
1205 InstanceIdentifier<AclPortsByIp> path = aclPortsByIpPath(aclName);
1206 try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1207 return tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet().orNull();
1208 } catch (ReadFailedException e) {
1209 LOG.error("Failed to read ACL ports {}", path, e);
1215 private AclIpPrefixes getAclIpPrefixesFromOperDs(String aclName, IpPrefixOrAddress ipPrefix) {
1216 InstanceIdentifier<AclIpPrefixes> path = getAclIpPrefixesPath(aclName, ipPrefix);
1217 try (ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
1218 return tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet().orNull();
1219 } catch (ReadFailedException e) {
1220 LOG.error("Failed to read ACL IP prefixes {}", path, e);
1226 * Gets the ace flow priority.
1228 * @param aclName the acl name
1229 * @return the ace flow priority
1231 public Integer getAceFlowPriority(String aclName) {
1232 Integer priority = AclConstants.ACE_DEFAULT_PRIORITY;
1233 Integer aclTag = getAclTag(new Uuid(aclName));
1234 if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
1235 // To handle overlapping rules, aclTag is added to priority
1238 LOG.warn("aclTag={} is null or invalid for aclName={}", aclTag, aclName);
1244 * Returns the hard timeout based on the protocol when a ACL rule removed from the instance.
1245 * It will returns the timeout configured in the {@link AclserviceConfig} class.
1247 * @param ace the ace
1248 * @param aclServiceUtils acl service utils
1249 * @return the hard time out
1251 public static Integer getHardTimoutForApplyStatefulChangeOnExistingTraffic(Ace ace,
1252 AclServiceUtils aclServiceUtils) {
1253 int hardTimeout = AclConstants.SECURITY_GROUP_ICMP_IDLE_TIME_OUT;
1254 Matches matches = ace.getMatches();
1255 AceIp acl = (AceIp) matches.getAceType();
1256 Short protocol = acl.getProtocol();
1257 if (protocol == null) {
1259 } else if (protocol == NwConstants.IP_PROT_TCP) {
1260 hardTimeout = aclServiceUtils.getConfig().getSecurityGroupTcpIdleTimeout();
1261 } else if (protocol == NwConstants.IP_PROT_UDP) {
1262 hardTimeout = aclServiceUtils.getConfig().getSecurityGroupUdpIdleTimeout();
1268 * This method creates and returns the ct_mark instruction when a ACL rule removed from the
1269 * instance. This instruction will reset the ct_mark value and stops the existing traffics.
1271 * @param filterTable the filterTable
1272 * @param elanId the Elan id
1273 * @return list of instruction
1275 public static List<InstructionInfo> createCtMarkInstructionForNewState(Short filterTable, Long elanId) {
1277 List<InstructionInfo> instructions = new ArrayList<>();
1278 List<ActionInfo> actionsInfos = new ArrayList<>();
1279 List<NxCtAction> ctActionsList = new ArrayList<>();
1280 NxCtAction nxCtMarkClearAction = new ActionNxConntrack.NxCtMark(AclConstants.CT_MARK_NEW_STATE);
1281 ctActionsList.add(nxCtMarkClearAction);
1283 ActionNxConntrack actionNxConntrack = new ActionNxConntrack(2, 1, 0, elanId.intValue(),
1284 (short) 255, ctActionsList);
1285 actionsInfos.add(actionNxConntrack);
1286 instructions.add(new InstructionApplyActions(actionsInfos));
1287 instructions.add(new InstructionGotoTable(filterTable));
1289 return instructions;
1292 public static List<AllowedAddressPairs> excludeMulticastAAPs(@Nullable List<AllowedAddressPairs> allowedAddresses) {
1293 List<AllowedAddressPairs> filteredAAPs = new ArrayList<>();
1294 if (allowedAddresses != null) {
1295 for (AllowedAddressPairs allowedAddress : allowedAddresses) {
1296 InetAddress inetAddr = getInetAddress(allowedAddress.getIpAddress());
1297 if (inetAddr != null && !inetAddr.isMulticastAddress()) {
1298 filteredAAPs.add(allowedAddress);
1302 return filteredAAPs;
1305 public static String getRecoverServiceRegistryKey() {
1306 return NetvirtAcl.class.toString();
1310 private static InetAddress getInetAddress(IpPrefixOrAddress ipPrefixOrAddress) {
1313 IpPrefix ipPrefix = ipPrefixOrAddress.getIpPrefix();
1314 if (ipPrefix != null) {
1315 addr = ipPrefix.stringValue().split("/")[0];
1317 IpAddress ipAddress = ipPrefixOrAddress.getIpAddress();
1318 if (ipAddress == null) {
1319 LOG.error("Invalid address : {}", ipPrefixOrAddress);
1322 addr = ipAddress.stringValue();
1326 return InetAddress.getByName(addr);
1327 } catch (UnknownHostException e) {
1328 LOG.error("Invalid address : {}", addr, e);
1333 public static Boolean isIpv6Subnet(List<SubnetInfo> subnetInfoList) {
1334 if (subnetInfoList != null && !subnetInfoList.isEmpty()) {
1335 for (SubnetInfo subnetInfo : subnetInfoList) {
1336 if (subnetInfo != null && IpVersionV6.class.equals(subnetInfo.getIpVersion())) {
1345 * Gets the subnet difference by performing (subnetInfo1 - subnetInfo2).
1347 * @param subnetInfo1 the subnet info 1
1348 * @param subnetInfo2 the subnet info 2
1349 * @return the subnet diff
1351 public static List<SubnetInfo> getSubnetDiff(List<SubnetInfo> subnetInfo1, List<SubnetInfo> subnetInfo2) {
1352 if (subnetInfo1 == null) {
1353 return Collections.emptyList();
1355 List<SubnetInfo> newSubnetList = new ArrayList<>(subnetInfo1);
1356 if (subnetInfo2 == null) {
1357 return newSubnetList;
1359 newSubnetList.removeAll(subnetInfo2);
1360 return newSubnetList;