2 * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. 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
8 package org.opendaylight.netvirt.elan.utils;
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.Lists;
16 import com.google.common.primitives.Ints;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
23 import java.math.BigInteger;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.Future;
31 import javax.annotation.CheckReturnValue;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
37 import org.apache.commons.lang3.StringUtils;
38 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
39 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
40 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
41 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
42 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
43 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
44 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
45 import org.opendaylight.genius.infra.Datastore.Configuration;
46 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
47 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
48 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
49 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
50 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
51 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
52 import org.opendaylight.genius.itm.api.IITMProvider;
53 import org.opendaylight.genius.itm.globals.ITMConstants;
54 import org.opendaylight.genius.mdsalutil.ActionInfo;
55 import org.opendaylight.genius.mdsalutil.FlowEntity;
56 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
57 import org.opendaylight.genius.mdsalutil.InstructionInfo;
58 import org.opendaylight.genius.mdsalutil.MDSALUtil;
59 import org.opendaylight.genius.mdsalutil.MatchInfo;
60 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
61 import org.opendaylight.genius.mdsalutil.NWUtil;
62 import org.opendaylight.genius.mdsalutil.NwConstants;
63 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
64 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
65 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
66 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
67 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
68 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
69 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
70 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
71 import org.opendaylight.genius.mdsalutil.packet.ARP;
72 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
73 import org.opendaylight.genius.mdsalutil.packet.IPv4;
74 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
75 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
76 import org.opendaylight.netvirt.elan.ElanException;
77 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
78 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
79 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
176 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
177 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
178 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
179 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
180 import org.opendaylight.yangtools.yang.binding.DataObject;
181 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
182 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
183 import org.opendaylight.yangtools.yang.common.RpcResult;
184 import org.slf4j.Logger;
185 import org.slf4j.LoggerFactory;
188 public class ElanUtils {
190 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
192 private final DataBroker broker;
193 private final ManagedNewTransactionRunner txRunner;
194 private final IMdsalApiManager mdsalManager;
195 private final OdlInterfaceRpcService interfaceManagerRpcService;
196 private final ItmRpcService itmRpcService;
197 private final IInterfaceManager interfaceManager;
198 private final ElanConfig elanConfig;
199 private final ElanItmUtils elanItmUtils;
200 private final ElanEtreeUtils elanEtreeUtils;
201 private final ElanInterfaceCache elanInterfaceCache;
202 private final IITMProvider iitmProvider;
204 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
206 public void onSuccess(Void result) {
207 LOG.debug("Success in Datastore operation");
211 public void onFailure(Throwable error) {
212 LOG.error("Error in Datastore operation", error);
217 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
218 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
219 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
220 ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider) {
221 this.broker = dataBroker;
222 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
223 this.mdsalManager = mdsalManager;
224 this.interfaceManagerRpcService = interfaceManagerRpcService;
225 this.itmRpcService = itmRpcService;
226 this.interfaceManager = interfaceManager;
227 this.elanConfig = elanConfig;
228 this.elanEtreeUtils = elanEtreeUtils;
229 this.elanItmUtils = elanItmUtils;
230 this.elanInterfaceCache = elanInterfaceCache;
231 this.iitmProvider = iitmProvider;
234 public final Boolean isOpenstackVniSemanticsEnforced() {
235 return elanConfig.isOpenstackVniSemanticsEnforced() != null
236 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
240 * Uses the IdManager to retrieve a brand new ElanTag.
246 * @return the integer
248 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
250 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
251 .setIdKey(idKey).build();
254 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
255 RpcResult<AllocateIdOutput> rpcResult = result.get();
256 if (rpcResult.isSuccessful()) {
257 return rpcResult.getResult().getIdValue();
259 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
261 } catch (InterruptedException | ExecutionException e) {
262 LOG.warn("Exception when Allocating Id", e);
267 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
268 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
269 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
275 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
277 * @param broker dataBroker
278 * @param datastoreType Logical DataStore type
279 * @param path IID to read
280 * @param <T> T extends DataObject
281 * @return the read value T
284 @SuppressWarnings("checkstyle:IllegalCatch")
285 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
286 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
287 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
288 return tx.read(datastoreType, path).get();
289 } catch (Exception e) {
290 throw new RuntimeException(e);
294 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
295 throws ReadFailedException {
296 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
297 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
298 return checkedFuture.checkedGet();
302 @SuppressWarnings("checkstyle:ForbidCertainMethod")
303 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
304 InstanceIdentifier<T> path) {
305 WriteTransaction tx = broker.newWriteOnlyTransaction();
306 tx.delete(datastoreType, path);
307 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
310 @SuppressWarnings("checkstyle:ForbidCertainMethod")
311 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
312 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
313 WriteTransaction tx = broker.newWriteOnlyTransaction();
314 tx.delete(datastoreType, path);
315 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
318 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
319 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
322 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
323 return InstanceIdentifier.builder(ElanInterfaces.class)
324 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
327 // elan-state Operational container
328 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
329 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
330 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
334 public static Elan getElanByName(ReadTransaction tx, String elanInstanceName) throws ReadFailedException {
335 return tx.read(LogicalDatastoreType.OPERATIONAL,
336 getElanInstanceOperationalDataPath(elanInstanceName)).checkedGet().orNull();
339 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
340 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
343 // grouping of forwarding-entries
344 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
345 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
346 interfaceName, physAddress);
347 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
350 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
351 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
352 LogicalDatastoreType.OPERATIONAL, identifier);
353 return existingInterfaceMacEntry.orNull();
356 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
357 PhysAddress physAddress) {
358 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
359 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
360 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
364 // elan-forwarding-tables Operational container
365 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
366 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
367 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
370 public Optional<MacEntry> getMacEntryForElanInstance(ReadTransaction tx, String elanName, PhysAddress physAddress)
371 throws ReadFailedException {
372 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
373 return tx.read(LogicalDatastoreType.OPERATIONAL, macId).checkedGet();
376 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
377 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
378 LogicalDatastoreType.OPERATIONAL, identifier);
379 return existingInterfaceMacEntry.orNull();
382 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
383 PhysAddress physAddress) {
384 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
385 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
388 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
389 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
393 // elan-interface-forwarding-entries Operational container
394 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
395 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
399 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
400 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
402 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
406 * Gets the elan interface mac addresses.
408 * @param interfaceName
410 * @return the elan interface mac addresses
412 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
413 List<PhysAddress> macAddresses = new ArrayList<>();
414 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
415 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
416 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
417 for (MacEntry macEntry : macEntries) {
418 macAddresses.add(macEntry.getMacAddress());
424 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
425 String interfaceName) {
426 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
427 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
431 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
432 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
434 * @param elanInstanceName
435 * name of the Elan to which the interfaces must belong to
437 * Id of the DPN where the interfaces are located
438 * @return the elan interface Info
440 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
441 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
443 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
447 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
448 * in a given DPN in the Operational DS. Data retrieved from Elans's
449 * operational DS: dpn-interfaces list
451 * @param elanInstanceName
452 * name of the Elan to which the interfaces must belong to
454 * Id of the DPN where the interfaces are located
455 * @return the elan dpn interface
457 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
459 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
460 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
461 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
464 // elan-tag-name-map Operational Container
465 public ElanTagName getElanInfoByElanTag(long elanTag) {
466 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
467 Optional<ElanTagName> existingElanInfo = read(broker,
468 LogicalDatastoreType.OPERATIONAL, elanId);
469 return existingElanInfo.orNull();
472 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
473 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
477 // interface-index-tag operational container
478 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
479 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
480 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
483 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
484 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
485 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
488 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
489 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
490 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
493 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
494 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
495 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
498 public ElanDpnInterfaces getElanDpnInterfacesList() {
499 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
501 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
505 * This method is useful get all ELAN participating CSS dpIds to install
506 * program remote dmac entries and updating remote bc groups for tor
509 * @param elanInstanceName
510 * the elan instance name
511 * @return list of dpIds
514 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
515 List<BigInteger> dpIds = new ArrayList<>();
516 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
517 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
518 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
519 if (!existingElanDpnInterfaces.isPresent()) {
522 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
523 for (DpnInterfaces dpnInterface : dpnInterfaces) {
524 dpIds.add(dpnInterface.getDpId());
530 * To check given dpId is already present in Elan instance. This can be used
531 * to program flow entry in external tunnel table when a new access port
532 * added for first time into the ELAN instance
536 * @param elanInstanceName
537 * the elan instance name
538 * @return true if dpId is already present, otherwise return false
540 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
541 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
542 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
543 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
544 if (!existingElanDpnInterfaces.isPresent()) {
547 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
548 for (DpnInterfaces dpnInterface : dpnInterfaces) {
549 if (dpnInterface.getDpId().equals(dpId)) {
556 public ElanForwardingTables getElanForwardingList() {
557 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
558 .builder(ElanForwardingTables.class).build();
559 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
562 public static long getElanRemoteBroadCastGroupID(long elanTag) {
563 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
567 * Gets the elan mac table.
571 * @return the elan mac table
573 public MacTable getElanMacTable(String elanName) {
574 return getElanMacTable(broker, elanName);
578 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
579 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
580 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
583 public static long getElanLocalBCGId(long elanTag) {
584 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
587 public static long getElanRemoteBCGId(long elanTag) {
588 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
591 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
592 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
595 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
596 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
599 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
600 int shBit = isSHFlagSet ? 1 : 0;
601 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
605 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
609 * @param interfaceInfo
615 * @param configureRemoteFlows
616 * true if remote dmac flows should be configured as well
617 * @param writeFlowGroupTx
619 * @throws ElanException in case of issues creating the flow objects
621 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
622 long macTimeout, String macAddress, boolean configureRemoteFlows,
623 WriteTransaction writeFlowGroupTx) throws ElanException {
624 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
625 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
627 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
632 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
633 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
634 String elanInstanceName = elanInfo.getElanInstanceName();
635 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
636 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
637 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
638 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
639 macAddress, dstDpId);
643 * Inserts a Flow in SMAC table to state that the MAC has already been
646 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
647 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
648 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
649 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
650 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
651 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
654 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
656 int lportTag = interfaceInfo.getInterfaceTag();
657 // Matching metadata and eth_src fields
658 List<MatchInfo> mkMatches = new ArrayList<>();
659 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
660 ElanHelper.getElanMetadataMask()));
661 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
662 List<InstructionInfo> mkInstructions = new ArrayList<>();
663 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
664 BigInteger dpId = interfaceInfo.getDpId();
665 long elanTag = getElanTag(elanInfo, interfaceInfo);
666 return new FlowEntityBuilder()
668 .setTableId(NwConstants.ELAN_SMAC_TABLE)
669 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
671 .setFlowName(elanInfo.getDescription())
672 .setIdleTimeOut((int) macTimeout)
674 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
675 .setMatchInfoList(mkMatches)
676 .setInstructionInfoList(mkInstructions)
678 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
679 .setSendFlowRemFlag(macTimeout != 0)
683 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
684 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
685 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
686 return elanInfo.getElanTag();
688 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
689 if (etreeInstance == null) {
690 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
691 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
692 return elanInfo.getElanTag();
694 return etreeInstance.getEtreeLeafTagVal().getValue();
700 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
701 * the packet through the specified interface if the tunnel_id matches the
702 * interface's lportTag.
704 * @param interfaceInfo
706 * @param mdsalApiManager
707 * the mdsal API manager
708 * @param writeFlowGroupTx
709 * the writeFLowGroup tx
711 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
712 WriteTransaction writeFlowGroupTx) {
713 BigInteger dpId = interfaceInfo.getDpId();
714 int lportTag = interfaceInfo.getInterfaceTag();
715 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
716 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
717 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
718 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
719 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
720 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
721 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
722 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
723 interfaceInfo.getPortName());
727 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
728 * consisting in tableId + elanTag.
734 * @return the Internal tunnel
736 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
737 return new StringBuffer().append(tableId).append(elanTag).toString();
741 * Constructs the Matches that checks that the tunnel_id field contains a
745 * lportTag that must be checked against the tunnel_id field
746 * @return the list of match Info
748 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
749 List<MatchInfo> mkMatches = new ArrayList<>();
751 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
756 * Constructs the Instructions that take the packet over a given interface.
759 * Name of the interface where the packet must be sent over. It
760 * can be a local interface or a tunnel interface (internal or
762 * @return the Instruction
764 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
765 List<Instruction> mkInstructions = new ArrayList<>();
766 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
768 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
769 return mkInstructions;
773 * Returns the list of Actions to be taken when sending the packet through
774 * an Elan interface. Note that this interface can refer to an ElanInterface
775 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
776 * Elan traffic can be sent through. In this latter case, the tunnelKey is
777 * mandatory and it can hold serviceId for internal tunnels or the VNI for
784 * @return the egress actions for interface
786 @SuppressWarnings("checkstyle:IllegalCatch")
787 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
788 List<Action> listAction = new ArrayList<>();
790 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
791 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
792 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
793 .getEgressActionsForInterface(getEgressActionInput);
794 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
795 if (!rpcResult.isSuccessful()) {
796 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
797 rpcResult.getErrors());
799 List<Action> actions = rpcResult.getResult().getAction();
800 listAction = actions;
802 } catch (Exception e) {
803 LOG.warn("Exception when egress actions for interface {}", ifName, e);
808 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
809 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
810 WriteTransaction writeFlowGroupTx)
811 throws ElanException {
812 BigInteger dpId = interfaceInfo.getDpId();
813 String ifName = interfaceInfo.getInterfaceName();
814 long ifTag = interfaceInfo.getInterfaceTag();
815 String elanInstanceName = elanInfo.getElanInstanceName();
817 Long elanTag = elanInfo.getElanTag();
819 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
821 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
822 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
824 if (!configureRemoteFlows) {
828 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
829 for (DpnInterfaces elanDpn : elanDpns) {
831 if (elanDpn.getDpId().equals(dpId)) {
835 // Check for the Remote DPN present in Inventory Manager
836 if (!isDpnPresent(elanDpn.getDpId())) {
840 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
841 // forwarded through the appropriate ITM tunnel
842 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
843 dpId, // dstDpn (the local DPN)
844 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
845 elanTag, // identifier of the Elan
846 macAddress, // MAC to be programmed in remote DPN
847 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
849 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
850 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
853 // TODO: Make sure that the same is performed against the ElanDevices.
857 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
858 return getElanDPNByName(elanName);
862 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
863 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
864 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
865 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
868 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
869 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
870 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
871 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
872 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
873 ifTag, writeFlowGroupTx);
876 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
877 ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
878 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
879 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
880 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
881 if (etreeTagName == null) {
882 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
885 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
886 macAddress, elanInfo, ifTag);
887 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
892 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
894 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
897 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
898 String macAddress, long elanTag) {
899 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
902 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
903 return String.valueOf(tableId) + elanTag + dpId + macAddress;
906 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
907 String dstMacAddress, long elanTag, boolean shFlag) {
908 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
912 * Builds the flow to be programmed in the DMAC table of the local DPN (that
913 * is, where the MAC is attached to). This flow consists in:
915 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
916 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
933 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
934 ElanInstance elanInfo, long ifTag) {
936 List<MatchInfo> mkMatches = new ArrayList<>();
937 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
938 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
940 List<Instruction> mkInstructions = new ArrayList<>();
941 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
942 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
943 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
944 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
945 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
946 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
951 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
952 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
953 elanInstance) throws ElanException {
954 if (interfaceManager.isExternalInterface(interfaceName)) {
955 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
956 macAddress, interfaceName, elanInstance.getElanInstanceName());
960 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
961 // networks, 0 otherwise
962 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
963 ? getVxlanSegmentationId(elanInstance) : 0;
964 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
966 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
967 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
968 writeFlowGroupTx, elanInstance);
971 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
972 String macAddress, String displayName, String interfaceName,
973 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) {
975 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
976 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
977 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
978 if (etreeTagName == null) {
979 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
980 interfaceName, elanTag);
982 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
983 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
984 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
990 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
991 * consists in: Match: + elanTag in packet's metadata + packet going to a
992 * MAC known to be located in another DPN Actions: + set_tunnel_id
993 * + output ITM internal tunnel interface with the other DPN
999 * @param lportTagOrVni
1000 * lportTag or network VNI
1005 * @param displayName
1007 * @param elanInstance
1009 * @return the flow remote Dmac
1011 @SuppressWarnings("checkstyle:IllegalCatch")
1012 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1013 String macAddress, String displayName, ElanInstance elanInstance) {
1014 List<MatchInfo> mkMatches = new ArrayList<>();
1015 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1016 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1018 List<Instruction> mkInstructions = new ArrayList<>();
1020 // List of Action for the provided Source and Destination DPIDs
1022 List<Action> actions = null;
1023 if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1024 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1025 } else if (isVlan(elanInstance) || isFlat(elanInstance)) {
1026 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1027 if (null == interfaceName) {
1028 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1031 actions = getEgressActionsForInterface(interfaceName, null);
1033 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1034 } catch (Exception e) {
1035 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1036 srcDpId, destDpId, lportTagOrVni, e);
1039 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1040 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1042 displayName, 0, /* idleTimeout */
1043 0, /* hardTimeout */
1044 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1050 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1051 MacEntry macEntry, TypedReadWriteTransaction<Configuration> flowTx) {
1052 if (elanInfo == null || interfaceInfo == null) {
1055 String macAddress = macEntry.getMacAddress().getValue();
1056 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1057 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
1061 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1062 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx) {
1063 String elanInstanceName = elanInfo.getElanInstanceName();
1064 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1065 BigInteger srcdpId = interfaceInfo.getDpId();
1066 boolean isFlowsRemovedInSrcDpn = false;
1067 for (DpnInterfaces dpnInterface : remoteFEs) {
1068 Long elanTag = elanInfo.getElanTag();
1069 BigInteger dstDpId = dpnInterface.getDpId();
1070 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1071 elanTag, dstDpId, flowTx)) {
1072 isFlowsRemovedInSrcDpn = true;
1074 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1075 elanTag, dstDpId, flowTx);
1077 if (!isFlowsRemovedInSrcDpn) {
1078 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1082 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1083 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1084 TypedReadWriteTransaction<Configuration> flowTx) {
1085 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1086 if (etreeLeafTag != null) {
1087 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1088 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, flowTx);
1092 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1093 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1094 TypedReadWriteTransaction<Configuration> flowTx) {
1095 boolean isFlowsRemovedInSrcDpn = false;
1096 if (dstDpId.equals(srcdpId)) {
1097 isFlowsRemovedInSrcDpn = true;
1098 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, flowTx);
1099 } else if (isDpnPresent(dstDpId)) {
1101 .removeFlow(flowTx, dstDpId,
1102 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1103 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
1104 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1105 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1107 return isFlowsRemovedInSrcDpn;
1110 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1111 boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx) {
1112 String elanInstanceName = elanInfo.getElanInstanceName();
1113 long ifTag = interfaceInfo.getInterfaceTag();
1114 BigInteger srcdpId = interfaceInfo.getDpId();
1115 Long elanTag = elanInfo.getElanTag();
1118 .removeFlow(flowTx, srcdpId,
1119 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1120 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1122 mdsalManager.removeFlow(flowTx, srcdpId,
1123 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1124 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
1125 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1126 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1130 * Updates the Elan information in the Operational DS. It also updates the
1131 * ElanInstance in the Config DS by setting the adquired elanTag.
1135 * @param elanInstanceAdded
1136 * the elan instance added
1137 * @param elanInterfaces
1138 * the elan interfaces
1142 * @return the updated ELAN instance.
1144 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1145 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1146 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1147 Long elanTag = elanInstanceAdded.getElanTag();
1148 if (elanTag == null || elanTag == 0L) {
1149 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1151 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1152 .withKey(new ElanKey(elanInstanceName)).build();
1154 // Add the ElanState in the elan-state operational data-store
1155 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1156 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1158 // Add the ElanMacTable in the elan-mac-table operational data-store
1159 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1160 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1161 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1163 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1164 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1165 long etreeLeafTag = -1;
1166 if (isEtreeInstance(elanInstanceAdded)) {
1167 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1169 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1170 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1171 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1172 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, tx);
1174 ElanTagName elanTagName = elanTagNameBuilder.build();
1176 // Add the ElanTag to ElanName in the elan-tag-name Operational
1178 tx.put(LogicalDatastoreType.OPERATIONAL,
1179 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1181 // Updates the ElanInstance Config DS by setting the just acquired
1183 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1184 .setDescription(elanInstanceAdded.getDescription())
1185 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1186 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1187 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1188 if (isEtreeInstance(elanInstanceAdded)) {
1189 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1191 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1193 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1194 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1195 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1196 return elanInstanceWithTag;
1199 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag, WriteTransaction tx) {
1200 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1201 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1202 tx.put(LogicalDatastoreType.OPERATIONAL,
1203 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1206 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1207 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1210 public boolean isDpnPresent(BigInteger dpnId) {
1211 String dpn = String.format("%s:%s", "openflow", dpnId);
1212 NodeId nodeId = new NodeId(dpn);
1214 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1216 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1219 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1220 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1221 ElanConstants.ELAN_SERVICE_PRIORITY);
1224 public static String getElanServiceName(String elanName, String interfaceName) {
1225 return "elan." + elanName + interfaceName;
1228 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1229 BigInteger cookie, List<Instruction> instructions) {
1230 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1231 .setInstruction(instructions);
1232 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1233 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1234 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1237 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1238 return InstanceIdentifier.builder(ServiceBindings.class)
1239 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1240 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1243 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1244 List<MatchInfo> mkMatches = new ArrayList<>();
1245 // Matching metadata
1246 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1251 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1252 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1253 .setDpnId(destDpId).setServiceId(serviceId).build();
1254 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1255 itmRpcService.removeTerminatingServiceActions(input);
1257 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1258 if (result.isSuccessful()) {
1259 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1260 + "dpn {}", serviceId, destDpId);
1262 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1263 + "dpn {}", serviceId, destDpId);
1265 } catch (InterruptedException | ExecutionException e) {
1266 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1267 + "dpn {}", serviceId, destDpId, e);
1272 * Gets the external tunnel.
1274 * @param sourceDevice
1276 * @param destinationDevice
1277 * the destination device
1278 * @param datastoreType
1279 * the datastore type
1280 * @return the external tunnel
1282 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1283 LogicalDatastoreType datastoreType) {
1284 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1285 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1286 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1287 return read(broker, datastoreType, iid).orNull();
1291 * Gets the external tunnel.
1293 * @param interfaceName
1294 * the interface name
1295 * @param datastoreType
1296 * the datastore type
1297 * @return the external tunnel
1299 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1300 ExternalTunnel externalTunnel = null;
1301 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1302 for (ExternalTunnel tunnel : externalTunnels) {
1303 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1304 externalTunnel = tunnel;
1308 return externalTunnel;
1312 * Gets the all external tunnels.
1314 * @param datastoreType
1315 * the data store type
1316 * @return the all external tunnels
1318 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1319 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1320 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1321 Collections.emptyList());
1324 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1325 List<MatchInfo> mkMatches = new ArrayList<>();
1327 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1328 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1333 * Checks if is interface operational.
1335 * @param interfaceName
1336 * the interface name
1339 * @return true, if is interface operational
1341 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1342 if (StringUtils.isBlank(interfaceName)) {
1345 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1346 if (ifState == null) {
1349 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1353 * Gets the interface state from operational ds.
1355 * @param interfaceName
1356 * the interface name
1359 * @return the interface state from oper ds
1361 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1362 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1363 String interfaceName, DataBroker dataBroker) {
1364 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1365 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1367 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1371 * Creates the interface state instance identifier.
1373 * @param interfaceName
1374 * the interface name
1375 * @return the instance identifier
1377 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1378 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1379 String interfaceName) {
1380 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1381 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1382 .builder(InterfacesState.class)
1383 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1384 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1385 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1386 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1388 return idBuilder.build();
1392 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1393 WriteTransaction tx) {
1394 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1397 } catch (InterruptedException | ExecutionException e) {
1398 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1399 LOG.debug("Error writing to datastore", e);
1404 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1405 return elanInstance != null && elanInstance.getSegmentType() != null
1406 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1407 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1410 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1411 if (elanInstance != null) {
1412 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1413 if (elanSegments != null) {
1414 for (ElanSegments segment : elanSegments) {
1415 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1416 && segment.getSegmentationId() != null
1417 && segment.getSegmentationId().longValue() != 0) {
1426 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1427 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1430 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1431 Long segmentationId = 0L;
1432 if (elanInstance == null) {
1433 return segmentationId;
1436 if (elanInstance.getSegmentType() != null
1437 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1438 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1439 segmentationId = elanInstance.getSegmentationId();
1441 for (ElanSegments segment: elanInstance.getElanSegments()) {
1442 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1443 && segment.getSegmentationId() != null
1444 && segment.getSegmentationId().longValue() != 0) {
1445 segmentationId = segment.getSegmentationId();
1449 return segmentationId;
1452 public static boolean isVlan(ElanInstance elanInstance) {
1453 return elanInstance != null && elanInstance.getSegmentType() != null
1454 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1455 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1458 public static boolean isFlat(ElanInstance elanInstance) {
1459 return elanInstance != null && elanInstance.getSegmentType() != null
1460 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1463 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1464 String macAddress, List<BigInteger> dpnIds) {
1465 for (BigInteger dpId : dpnIds) {
1466 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
1467 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
1469 "Error adding DMAC redirect to dispatcher flows");
1473 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1474 for (BigInteger dpId : dpnIds) {
1475 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1476 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1480 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1481 String displayName, long elanTag) {
1482 List<MatchInfo> matches = new ArrayList<>();
1483 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1484 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1485 List<InstructionInfo> instructions = new ArrayList<>();
1486 List<ActionInfo> actions = new ArrayList<>();
1487 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1489 instructions.add(new InstructionApplyActions(actions));
1490 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1491 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1492 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1493 matches, instructions);
1496 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1497 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1498 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1499 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1503 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1504 if (interfaceManager.isExternalInterface(dpnInterface)) {
1505 return dpnInterface;
1509 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1513 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1514 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1515 return elanMacDmacDpnKey.intern();
1518 public static String getElanMacKey(long elanTag, String macAddress) {
1519 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1520 return elanMacKey.intern();
1523 public static List<ListenableFuture<Void>>
1524 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1526 Throwable cause = exception.getCause();
1527 if (cause != null && cause instanceof TransactionCommitFailedException) {
1528 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1534 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1535 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1536 List<PhysAddress> physAddresses = new ArrayList<>();
1537 for (String mac : macAddress) {
1538 physAddresses.add(new PhysAddress(mac));
1540 return physAddresses;
1543 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1544 if (isEmpty(staticMacAddresses)) {
1545 return Collections.EMPTY_LIST;
1547 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1548 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1549 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1550 for (PhysAddress physAddress : physAddressList) {
1551 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1553 return staticMacEntries;
1556 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1557 String macAddress) {
1558 return InstanceIdentifier.builder(ElanInterfaces.class)
1559 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1560 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1563 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1564 List<StaticMacEntries> updatedStaticMacEntries) {
1565 if (isEmpty(originalStaticMacEntries)) {
1566 return Collections.EMPTY_LIST;
1568 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1569 if (isNotEmpty(updatedStaticMacEntries)) {
1570 deleted.removeAll(updatedStaticMacEntries);
1575 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1576 if (isEmpty(orig)) {
1577 return Collections.EMPTY_LIST;
1579 List<T> diff = Lists.newArrayList(orig);
1580 if (isNotEmpty(updated)) {
1581 diff.removeAll(updated);
1586 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1587 List<StaticMacEntries> updatedStaticMacEntries) {
1588 if (isNotEmpty(updatedStaticMacEntries)) {
1589 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1590 if (isNotEmpty(originalStaticMacEntries)) {
1591 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1592 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1593 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1598 public static boolean isEmpty(Collection collection) {
1599 return collection == null || collection.isEmpty();
1602 public static boolean isNotEmpty(Collection collection) {
1603 return !isEmpty(collection);
1606 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1607 Optional<IpAddress> srcIpAddress = Optional.absent();
1608 if (ethernet.getPayload() == null) {
1609 return srcIpAddress;
1611 byte[] ipAddrBytes = null;
1612 if (ethernet.getPayload() instanceof IPv4) {
1613 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1614 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1615 } else if (ethernet.getPayload() instanceof ARP) {
1616 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1618 if (ipAddrBytes != null) {
1619 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1620 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1622 return srcIpAddress;
1625 public List<MacEntry> getElanMacEntries(String elanName) {
1626 MacTable macTable = getElanMacTable(elanName);
1627 if (macTable == null) {
1628 return Collections.emptyList();
1630 return macTable.getMacEntry();
1633 public boolean isTunnelInLogicalGroup(String interfaceName) {
1634 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1635 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1636 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1637 if (configIface == null) {
1638 configIface = iitmProvider.getInterface(interfaceName);
1640 if (configIface == null) {
1643 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1644 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1645 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1646 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1647 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1653 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1654 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1655 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1656 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1657 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1658 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1659 return InstanceIdentifier.builder(Nodes.class)
1660 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1661 nodeDpn.key()).augmentation(FlowCapableNode.class)
1662 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1665 public static String getElanInterfaceJobKey(String interfaceName) {
1666 return "elaninterface-" + interfaceName;
1669 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1671 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1673 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1676 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1677 Optional<Subnetmaps> subnetMapsData =
1678 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1679 if (subnetMapsData.isPresent()) {
1680 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1681 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1682 for (Subnetmap subnet : subnetMapList) {
1683 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1684 if (subnet.getRouterInterfacePortId() != null) {
1685 return subnet.getRouterInterfacePortId().getValue();
1694 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1695 return InstanceIdentifier.create(Subnetmaps.class);