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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Lists;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.Future;
27 import javax.annotation.CheckReturnValue;
28 import javax.annotation.Nonnull;
29 import javax.annotation.Nullable;
30 import javax.inject.Inject;
31 import javax.inject.Singleton;
32 import org.apache.commons.lang3.StringUtils;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
35 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
36 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
41 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
43 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
44 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
45 import org.opendaylight.genius.itm.globals.ITMConstants;
46 import org.opendaylight.genius.mdsalutil.ActionInfo;
47 import org.opendaylight.genius.mdsalutil.FlowEntity;
48 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
49 import org.opendaylight.genius.mdsalutil.InstructionInfo;
50 import org.opendaylight.genius.mdsalutil.MDSALUtil;
51 import org.opendaylight.genius.mdsalutil.MatchInfo;
52 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
53 import org.opendaylight.genius.mdsalutil.NWUtil;
54 import org.opendaylight.genius.mdsalutil.NwConstants;
55 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
56 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
57 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
58 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
59 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
60 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
61 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
62 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
63 import org.opendaylight.genius.mdsalutil.packet.ARP;
64 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
65 import org.opendaylight.genius.mdsalutil.packet.IPv4;
66 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
67 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
68 import org.opendaylight.netvirt.elan.ElanException;
69 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
70 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
71 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
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.genius.itm.op.rev160406.ExternalTunnelList;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
172 import org.opendaylight.yangtools.yang.binding.DataObject;
173 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
174 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
175 import org.opendaylight.yangtools.yang.common.RpcResult;
176 import org.slf4j.Logger;
177 import org.slf4j.LoggerFactory;
180 public class ElanUtils {
182 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
184 private final DataBroker broker;
185 private final ManagedNewTransactionRunner txRunner;
186 private final IMdsalApiManager mdsalManager;
187 private final OdlInterfaceRpcService interfaceManagerRpcService;
188 private final ItmRpcService itmRpcService;
189 private final IInterfaceManager interfaceManager;
190 private final ElanConfig elanConfig;
191 private final ElanItmUtils elanItmUtils;
192 private final ElanEtreeUtils elanEtreeUtils;
193 private final ElanInterfaceCache elanInterfaceCache;
195 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
197 public void onSuccess(Void result) {
198 LOG.debug("Success in Datastore operation");
202 public void onFailure(Throwable error) {
203 LOG.error("Error in Datastore operation", error);
208 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
209 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
210 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
211 ElanInterfaceCache elanInterfaceCache) {
212 this.broker = dataBroker;
213 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
214 this.mdsalManager = mdsalManager;
215 this.interfaceManagerRpcService = interfaceManagerRpcService;
216 this.itmRpcService = itmRpcService;
217 this.interfaceManager = interfaceManager;
218 this.elanConfig = elanConfig;
219 this.elanEtreeUtils = elanEtreeUtils;
220 this.elanItmUtils = elanItmUtils;
221 this.elanInterfaceCache = elanInterfaceCache;
224 public final Boolean isOpenstackVniSemanticsEnforced() {
225 return elanConfig.isOpenstackVniSemanticsEnforced() != null
226 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
230 * Uses the IdManager to retrieve a brand new ElanTag.
236 * @return the integer
238 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
240 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
241 .setIdKey(idKey).build();
244 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
245 RpcResult<AllocateIdOutput> rpcResult = result.get();
246 if (rpcResult.isSuccessful()) {
247 return rpcResult.getResult().getIdValue();
249 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
251 } catch (InterruptedException | ExecutionException e) {
252 LOG.warn("Exception when Allocating Id", e);
257 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
258 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
259 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
265 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
267 * @param broker dataBroker
268 * @param datastoreType Logical DataStore type
269 * @param path IID to read
270 * @param <T> T extends DataObject
271 * @return the read value T
274 @SuppressWarnings("checkstyle:IllegalCatch")
275 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
276 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
277 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
278 return tx.read(datastoreType, path).get();
279 } catch (Exception e) {
280 throw new RuntimeException(e);
284 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
285 throws ReadFailedException {
286 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
287 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
288 return checkedFuture.checkedGet();
292 @SuppressWarnings("checkstyle:ForbiddenMethod")
293 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
294 InstanceIdentifier<T> path) {
295 WriteTransaction tx = broker.newWriteOnlyTransaction();
296 tx.delete(datastoreType, path);
297 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
300 @SuppressWarnings("checkstyle:ForbiddenMethod")
301 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
302 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
303 WriteTransaction tx = broker.newWriteOnlyTransaction();
304 tx.delete(datastoreType, path);
305 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
308 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
309 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
312 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
313 return InstanceIdentifier.builder(ElanInterfaces.class)
314 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
317 // elan-state Operational container
318 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
319 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
320 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
324 public static Elan getElanByName(ReadTransaction tx, String elanInstanceName) throws ReadFailedException {
325 return tx.read(LogicalDatastoreType.OPERATIONAL,
326 getElanInstanceOperationalDataPath(elanInstanceName)).checkedGet().orNull();
329 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
330 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
333 // grouping of forwarding-entries
334 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
335 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
336 interfaceName, physAddress);
337 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
340 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
341 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
342 LogicalDatastoreType.OPERATIONAL, identifier);
343 return existingInterfaceMacEntry.orNull();
346 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
347 PhysAddress physAddress) {
348 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
349 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
350 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
354 // elan-forwarding-tables Operational container
355 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
356 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
357 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
360 public Optional<MacEntry> getMacEntryForElanInstance(ReadTransaction tx, String elanName, PhysAddress physAddress)
361 throws ReadFailedException {
362 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
363 return tx.read(LogicalDatastoreType.OPERATIONAL, macId).checkedGet();
366 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
367 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
368 LogicalDatastoreType.OPERATIONAL, identifier);
369 return existingInterfaceMacEntry.orNull();
372 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
373 PhysAddress physAddress) {
374 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
375 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
378 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
379 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
383 // elan-interface-forwarding-entries Operational container
384 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
385 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
389 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
390 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
392 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
396 * Gets the elan interface mac addresses.
398 * @param interfaceName
400 * @return the elan interface mac addresses
402 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
403 List<PhysAddress> macAddresses = new ArrayList<>();
404 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
405 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
406 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
407 for (MacEntry macEntry : macEntries) {
408 macAddresses.add(macEntry.getMacAddress());
414 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
415 String interfaceName) {
416 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
417 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
421 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
422 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
424 * @param elanInstanceName
425 * name of the Elan to which the interfaces must belong to
427 * Id of the DPN where the interfaces are located
428 * @return the elan interface Info
430 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
431 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
433 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
437 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
438 * in a given DPN in the Operational DS. Data retrieved from Elans's
439 * operational DS: dpn-interfaces list
441 * @param elanInstanceName
442 * name of the Elan to which the interfaces must belong to
444 * Id of the DPN where the interfaces are located
445 * @return the elan dpn interface
447 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
449 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
450 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
451 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
454 // elan-tag-name-map Operational Container
455 public ElanTagName getElanInfoByElanTag(long elanTag) {
456 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
457 Optional<ElanTagName> existingElanInfo = read(broker,
458 LogicalDatastoreType.OPERATIONAL, elanId);
459 return existingElanInfo.orNull();
462 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
463 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
467 // interface-index-tag operational container
468 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
469 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
470 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
473 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
474 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
475 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
478 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
479 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
480 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
483 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
484 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
485 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
488 public ElanDpnInterfaces getElanDpnInterfacesList() {
489 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
491 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
495 * This method is useful get all ELAN participating CSS dpIds to install
496 * program remote dmac entries and updating remote bc groups for tor
499 * @param elanInstanceName
500 * the elan instance name
501 * @return list of dpIds
504 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
505 List<BigInteger> dpIds = new ArrayList<>();
506 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
507 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
508 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
509 if (!existingElanDpnInterfaces.isPresent()) {
512 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
513 for (DpnInterfaces dpnInterface : dpnInterfaces) {
514 dpIds.add(dpnInterface.getDpId());
520 * To check given dpId is already present in Elan instance. This can be used
521 * to program flow entry in external tunnel table when a new access port
522 * added for first time into the ELAN instance
526 * @param elanInstanceName
527 * the elan instance name
528 * @return true if dpId is already present, otherwise return false
530 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
531 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
532 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
533 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
534 if (!existingElanDpnInterfaces.isPresent()) {
537 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
538 for (DpnInterfaces dpnInterface : dpnInterfaces) {
539 if (dpnInterface.getDpId().equals(dpId)) {
546 public ElanForwardingTables getElanForwardingList() {
547 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
548 .builder(ElanForwardingTables.class).build();
549 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
552 public static long getElanRemoteBroadCastGroupID(long elanTag) {
553 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
557 * Gets the elan mac table.
561 * @return the elan mac table
563 public MacTable getElanMacTable(String elanName) {
564 return getElanMacTable(broker, elanName);
568 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
569 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
570 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
573 public static long getElanLocalBCGId(long elanTag) {
574 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
577 public static long getElanRemoteBCGId(long elanTag) {
578 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
581 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
582 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
585 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
586 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
589 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
590 int shBit = isSHFlagSet ? 1 : 0;
591 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
595 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
599 * @param interfaceInfo
605 * @param configureRemoteFlows
606 * true if remote dmac flows should be configured as well
607 * @param writeFlowGroupTx
609 * @throws ElanException in case of issues creating the flow objects
611 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
612 long macTimeout, String macAddress, boolean configureRemoteFlows,
613 WriteTransaction writeFlowGroupTx) throws ElanException {
614 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
615 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
617 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
622 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
623 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
624 String elanInstanceName = elanInfo.getElanInstanceName();
625 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
626 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
627 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
628 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
629 macAddress, dstDpId);
633 * Inserts a Flow in SMAC table to state that the MAC has already been
636 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
637 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
638 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
639 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
640 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
641 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
644 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
646 int lportTag = interfaceInfo.getInterfaceTag();
647 // Matching metadata and eth_src fields
648 List<MatchInfo> mkMatches = new ArrayList<>();
649 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
650 ElanHelper.getElanMetadataMask()));
651 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
652 List<InstructionInfo> mkInstructions = new ArrayList<>();
653 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
654 BigInteger dpId = interfaceInfo.getDpId();
655 long elanTag = getElanTag(elanInfo, interfaceInfo);
656 return new FlowEntityBuilder()
658 .setTableId(NwConstants.ELAN_SMAC_TABLE)
659 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
661 .setFlowName(elanInfo.getDescription())
662 .setIdleTimeOut((int) macTimeout)
664 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
665 .setMatchInfoList(mkMatches)
666 .setInstructionInfoList(mkInstructions)
668 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
669 .setSendFlowRemFlag(macTimeout != 0)
673 private Long getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
674 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
675 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
676 return elanInfo.getElanTag();
678 EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
679 if (etreeInstance == null) {
680 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
681 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
682 return elanInfo.getElanTag();
684 return etreeInstance.getEtreeLeafTagVal().getValue();
690 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
691 * the packet through the specified interface if the tunnel_id matches the
692 * interface's lportTag.
694 * @param interfaceInfo
696 * @param mdsalApiManager
697 * the mdsal API manager
698 * @param writeFlowGroupTx
699 * the writeFLowGroup tx
701 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
702 WriteTransaction writeFlowGroupTx) {
703 BigInteger dpId = interfaceInfo.getDpId();
704 int lportTag = interfaceInfo.getInterfaceTag();
705 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
706 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
707 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
708 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
709 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
710 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
711 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
712 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
713 interfaceInfo.getPortName());
717 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
718 * consisting in tableId + elanTag.
724 * @return the Internal tunnel
726 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
727 return new StringBuffer().append(tableId).append(elanTag).toString();
731 * Constructs the Matches that checks that the tunnel_id field contains a
735 * lportTag that must be checked against the tunnel_id field
736 * @return the list of match Info
738 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
739 List<MatchInfo> mkMatches = new ArrayList<>();
741 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
746 * Constructs the Instructions that take the packet over a given interface.
749 * Name of the interface where the packet must be sent over. It
750 * can be a local interface or a tunnel interface (internal or
752 * @return the Instruction
754 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
755 List<Instruction> mkInstructions = new ArrayList<>();
756 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
758 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
759 return mkInstructions;
763 * Returns the list of Actions to be taken when sending the packet through
764 * an Elan interface. Note that this interface can refer to an ElanInterface
765 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
766 * Elan traffic can be sent through. In this latter case, the tunnelKey is
767 * mandatory and it can hold serviceId for internal tunnels or the VNI for
774 * @return the egress actions for interface
776 @SuppressWarnings("checkstyle:IllegalCatch")
777 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
778 List<Action> listAction = new ArrayList<>();
780 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
781 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
782 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
783 .getEgressActionsForInterface(getEgressActionInput);
784 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
785 if (!rpcResult.isSuccessful()) {
786 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
787 rpcResult.getErrors());
789 List<Action> actions = rpcResult.getResult().getAction();
790 listAction = actions;
792 } catch (Exception e) {
793 LOG.warn("Exception when egress actions for interface {}", ifName, e);
798 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
799 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
800 WriteTransaction writeFlowGroupTx)
801 throws ElanException {
802 BigInteger dpId = interfaceInfo.getDpId();
803 String ifName = interfaceInfo.getInterfaceName();
804 long ifTag = interfaceInfo.getInterfaceTag();
805 String elanInstanceName = elanInfo.getElanInstanceName();
807 Long elanTag = elanInfo.getElanTag();
809 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
811 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
812 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
814 if (!configureRemoteFlows) {
818 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
819 for (DpnInterfaces elanDpn : elanDpns) {
821 if (elanDpn.getDpId().equals(dpId)) {
825 // Check for the Remote DPN present in Inventory Manager
826 if (!isDpnPresent(elanDpn.getDpId())) {
830 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
831 // forwarded through the appropriate ITM tunnel
832 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
833 dpId, // dstDpn (the local DPN)
834 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
835 elanTag, // identifier of the Elan
836 macAddress, // MAC to be programmed in remote DPN
837 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
839 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
840 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
843 // TODO: Make sure that the same is performed against the ElanDevices.
847 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
848 return getElanDPNByName(elanName);
852 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
853 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
854 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
855 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
858 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
859 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
860 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
861 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
862 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
863 ifTag, writeFlowGroupTx);
866 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
867 ElanInstance elanInfo, long ifTag, WriteTransaction writeFlowGroupTx) {
868 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
869 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
870 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
871 if (etreeTagName == null) {
872 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
875 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
876 macAddress, elanInfo, ifTag);
877 mdsalManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
882 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
884 return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
887 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
888 String macAddress, long elanTag) {
889 return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
892 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
893 return String.valueOf(tableId) + elanTag + dpId + macAddress;
896 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
897 String dstMacAddress, long elanTag, boolean shFlag) {
898 return String.valueOf(elanDmacTable) + elanTag + dpId + extDeviceNodeId + dstMacAddress + shFlag;
902 * Builds the flow to be programmed in the DMAC table of the local DPN (that
903 * is, where the MAC is attached to). This flow consists in:
905 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
906 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
923 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
924 ElanInstance elanInfo, long ifTag) {
926 List<MatchInfo> mkMatches = new ArrayList<>();
927 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
928 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
930 List<Instruction> mkInstructions = new ArrayList<>();
931 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
932 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
933 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
934 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
935 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
936 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
941 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
942 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
943 elanInstance) throws ElanException {
944 if (interfaceManager.isExternalInterface(interfaceName)) {
945 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
946 macAddress, interfaceName, elanInstance.getElanInstanceName());
950 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
951 // networks, 0 otherwise
952 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
953 ? getVxlanSegmentationId(elanInstance) : 0;
954 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
956 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
957 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
958 writeFlowGroupTx, elanInstance);
961 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
962 String macAddress, String displayName, String interfaceName,
963 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) {
965 EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
966 if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
967 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
968 if (etreeTagName == null) {
969 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null.",
970 interfaceName, elanTag);
972 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
973 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
974 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
980 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
981 * consists in: Match: + elanTag in packet's metadata + packet going to a
982 * MAC known to be located in another DPN Actions: + set_tunnel_id
983 * + output ITM internal tunnel interface with the other DPN
989 * @param lportTagOrVni
990 * lportTag or network VNI
997 * @param elanInstance
999 * @return the flow remote Dmac
1001 @SuppressWarnings("checkstyle:IllegalCatch")
1002 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1003 String macAddress, String displayName, ElanInstance elanInstance) {
1004 List<MatchInfo> mkMatches = new ArrayList<>();
1005 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1006 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1008 List<Instruction> mkInstructions = new ArrayList<>();
1010 // List of Action for the provided Source and Destination DPIDs
1012 List<Action> actions = null;
1013 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1014 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1015 if (null == interfaceName) {
1016 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1019 actions = getEgressActionsForInterface(interfaceName, null);
1020 } else if (isVxlanNetworkOrVxlanSegment(elanInstance)) {
1021 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1023 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1024 } catch (Exception e) {
1025 LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
1026 srcDpId, destDpId, lportTagOrVni, e);
1029 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1030 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1032 displayName, 0, /* idleTimeout */
1033 0, /* hardTimeout */
1034 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1040 public void deleteMacFlows(@Nullable ElanInstance elanInfo, @Nullable InterfaceInfo interfaceInfo,
1041 MacEntry macEntry, WriteTransaction deleteFlowGroupTx) {
1042 if (elanInfo == null || interfaceInfo == null) {
1045 String macAddress = macEntry.getMacAddress().getValue();
1046 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1047 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1051 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1052 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1053 String elanInstanceName = elanInfo.getElanInstanceName();
1054 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1055 BigInteger srcdpId = interfaceInfo.getDpId();
1056 boolean isFlowsRemovedInSrcDpn = false;
1057 for (DpnInterfaces dpnInterface : remoteFEs) {
1058 Long elanTag = elanInfo.getElanTag();
1059 BigInteger dstDpId = dpnInterface.getDpId();
1060 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1061 elanTag, dstDpId, deleteFlowGroupTx)) {
1062 isFlowsRemovedInSrcDpn = true;
1064 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1065 elanTag, dstDpId, deleteFlowGroupTx);
1067 if (!isFlowsRemovedInSrcDpn) {
1068 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1072 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1073 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1074 WriteTransaction deleteFlowGroupTx) {
1075 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1076 if (etreeLeafTag != null) {
1077 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1078 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1082 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1083 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1084 WriteTransaction deleteFlowGroupTx) {
1085 boolean isFlowsRemovedInSrcDpn = false;
1086 if (dstDpId.equals(srcdpId)) {
1087 isFlowsRemovedInSrcDpn = true;
1088 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1089 } else if (isDpnPresent(dstDpId)) {
1091 .removeFlowToTx(dstDpId,
1092 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1093 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1095 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1096 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1098 return isFlowsRemovedInSrcDpn;
1101 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1102 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1103 String elanInstanceName = elanInfo.getElanInstanceName();
1104 long ifTag = interfaceInfo.getInterfaceTag();
1105 BigInteger srcdpId = interfaceInfo.getDpId();
1106 Long elanTag = elanInfo.getElanTag();
1109 .removeFlowToTx(srcdpId,
1110 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1111 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1114 mdsalManager.removeFlowToTx(srcdpId,
1115 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1116 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1118 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1119 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1123 * Updates the Elan information in the Operational DS. It also updates the
1124 * ElanInstance in the Config DS by setting the adquired elanTag.
1128 * @param elanInstanceAdded
1129 * the elan instance added
1130 * @param elanInterfaces
1131 * the elan interfaces
1135 * @return the updated ELAN instance.
1137 public static ElanInstance updateOperationalDataStore(IdManagerService idManager,
1138 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1139 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1140 Long elanTag = elanInstanceAdded.getElanTag();
1141 if (elanTag == null || elanTag == 0L) {
1142 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1144 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1145 .withKey(new ElanKey(elanInstanceName)).build();
1147 // Add the ElanState in the elan-state operational data-store
1148 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1149 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1151 // Add the ElanMacTable in the elan-mac-table operational data-store
1152 MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
1153 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1154 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1156 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1157 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1158 long etreeLeafTag = -1;
1159 if (isEtreeInstance(elanInstanceAdded)) {
1160 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1162 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1163 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1164 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1165 addTheLeafTagAsElanTag(elanInstanceName, etreeLeafTag, tx);
1167 ElanTagName elanTagName = elanTagNameBuilder.build();
1169 // Add the ElanTag to ElanName in the elan-tag-name Operational
1171 tx.put(LogicalDatastoreType.OPERATIONAL,
1172 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1174 // Updates the ElanInstance Config DS by setting the just acquired
1176 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1177 .setDescription(elanInstanceAdded.getDescription())
1178 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1179 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1180 .withKey(elanInstanceAdded.key()).setElanTag(elanTag);
1181 if (isEtreeInstance(elanInstanceAdded)) {
1182 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1184 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1186 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1187 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1188 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1189 return elanInstanceWithTag;
1192 private static void addTheLeafTagAsElanTag(String elanInstanceName, long etreeLeafTag, WriteTransaction tx) {
1193 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1194 .withKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1195 tx.put(LogicalDatastoreType.OPERATIONAL,
1196 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1199 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1200 return elanInstanceAdded.augmentation(EtreeInstance.class) != null;
1203 public boolean isDpnPresent(BigInteger dpnId) {
1204 String dpn = String.format("%s:%s", "openflow", dpnId);
1205 NodeId nodeId = new NodeId(dpn);
1207 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1209 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1212 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1213 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1214 ElanConstants.ELAN_SERVICE_PRIORITY);
1217 public static String getElanServiceName(String elanName, String interfaceName) {
1218 return "elan." + elanName + interfaceName;
1221 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1222 BigInteger cookie, List<Instruction> instructions) {
1223 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1224 .setInstruction(instructions);
1225 return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1226 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1227 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1230 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1231 return InstanceIdentifier.builder(ServiceBindings.class)
1232 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1233 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1236 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1237 List<MatchInfo> mkMatches = new ArrayList<>();
1238 // Matching metadata
1239 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1244 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1245 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1246 .setDpnId(destDpId).setServiceId(serviceId).build();
1247 Future<RpcResult<RemoveTerminatingServiceActionsOutput>> futureObject =
1248 itmRpcService.removeTerminatingServiceActions(input);
1250 RpcResult<RemoveTerminatingServiceActionsOutput> result = futureObject.get();
1251 if (result.isSuccessful()) {
1252 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1253 + "dpn {}", serviceId, destDpId);
1255 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1256 + "dpn {}", serviceId, destDpId);
1258 } catch (InterruptedException | ExecutionException e) {
1259 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1260 + "dpn {}", serviceId, destDpId, e);
1265 * Gets the external tunnel.
1267 * @param sourceDevice
1269 * @param destinationDevice
1270 * the destination device
1271 * @param datastoreType
1272 * the datastore type
1273 * @return the external tunnel
1275 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1276 LogicalDatastoreType datastoreType) {
1277 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1278 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1279 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1280 return read(broker, datastoreType, iid).orNull();
1284 * Gets the external tunnel.
1286 * @param interfaceName
1287 * the interface name
1288 * @param datastoreType
1289 * the datastore type
1290 * @return the external tunnel
1292 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1293 ExternalTunnel externalTunnel = null;
1294 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1295 for (ExternalTunnel tunnel : externalTunnels) {
1296 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1297 externalTunnel = tunnel;
1301 return externalTunnel;
1305 * Gets the all external tunnels.
1307 * @param datastoreType
1308 * the data store type
1309 * @return the all external tunnels
1311 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1312 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1313 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1314 Collections.emptyList());
1317 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1318 List<MatchInfo> mkMatches = new ArrayList<>();
1320 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1321 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1326 * Checks if is interface operational.
1328 * @param interfaceName
1329 * the interface name
1332 * @return true, if is interface operational
1334 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1335 if (StringUtils.isBlank(interfaceName)) {
1338 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1339 if (ifState == null) {
1342 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1346 * Gets the interface state from operational ds.
1348 * @param interfaceName
1349 * the interface name
1352 * @return the interface state from oper ds
1354 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1355 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1356 String interfaceName, DataBroker dataBroker) {
1357 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1358 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1360 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1364 * Creates the interface state instance identifier.
1366 * @param interfaceName
1367 * the interface name
1368 * @return the instance identifier
1370 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1371 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1372 String interfaceName) {
1373 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1374 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1375 .builder(InterfacesState.class)
1376 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1377 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1378 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1379 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1381 return idBuilder.build();
1385 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1386 WriteTransaction tx) {
1387 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1390 } catch (InterruptedException | ExecutionException e) {
1391 // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
1392 LOG.debug("Error writing to datastore", e);
1397 public static boolean isVxlan(@Nullable ElanInstance elanInstance) {
1398 return elanInstance != null && elanInstance.getSegmentType() != null
1399 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1400 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1403 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1404 if (elanInstance != null) {
1405 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1406 if (elanSegments != null) {
1407 for (ElanSegments segment : elanSegments) {
1408 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1409 && segment.getSegmentationId() != null
1410 && segment.getSegmentationId().longValue() != 0) {
1419 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1420 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1423 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1424 Long segmentationId = 0L;
1425 if (elanInstance == null) {
1426 return segmentationId;
1429 if (elanInstance.getSegmentType() != null
1430 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1431 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1432 segmentationId = elanInstance.getSegmentationId();
1434 for (ElanSegments segment: elanInstance.getElanSegments()) {
1435 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1436 && segment.getSegmentationId() != null
1437 && segment.getSegmentationId().longValue() != 0) {
1438 segmentationId = segment.getSegmentationId();
1442 return segmentationId;
1445 public static boolean isVlan(ElanInstance elanInstance) {
1446 return elanInstance != null && elanInstance.getSegmentType() != null
1447 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1448 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1451 public static boolean isFlat(ElanInstance elanInstance) {
1452 return elanInstance != null && elanInstance.getSegmentType() != null
1453 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1456 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1457 String macAddress, List<BigInteger> dpnIds) {
1458 for (BigInteger dpId : dpnIds) {
1459 ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
1460 tx -> mdsalManager.addFlowToTx(
1461 buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag), tx)), LOG,
1462 "Error adding DMAC redirect to dispatcher flows");
1466 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1467 for (BigInteger dpId : dpnIds) {
1468 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1469 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1473 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1474 String displayName, long elanTag) {
1475 List<MatchInfo> matches = new ArrayList<>();
1476 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1477 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1478 List<InstructionInfo> instructions = new ArrayList<>();
1479 List<ActionInfo> actions = new ArrayList<>();
1480 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1482 instructions.add(new InstructionApplyActions(actions));
1483 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1484 return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1485 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1486 matches, instructions);
1489 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1490 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1491 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1492 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1496 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1497 if (interfaceManager.isExternalInterface(dpnInterface)) {
1498 return dpnInterface;
1502 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1506 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1507 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1508 return elanMacDmacDpnKey.intern();
1511 public static String getElanMacKey(long elanTag, String macAddress) {
1512 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1513 return elanMacKey.intern();
1516 public static List<ListenableFuture<Void>>
1517 returnFailedListenableFutureIfTransactionCommitFailedExceptionCauseOrElseThrow(RuntimeException exception) {
1519 Throwable cause = exception.getCause();
1520 if (cause != null && cause instanceof TransactionCommitFailedException) {
1521 return Collections.singletonList(Futures.immediateFailedFuture(cause));
1527 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1528 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1529 List<PhysAddress> physAddresses = new ArrayList<>();
1530 for (String mac : macAddress) {
1531 physAddresses.add(new PhysAddress(mac));
1533 return physAddresses;
1536 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1537 if (isEmpty(staticMacAddresses)) {
1538 return Collections.EMPTY_LIST;
1540 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1541 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1542 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1543 for (PhysAddress physAddress : physAddressList) {
1544 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1546 return staticMacEntries;
1549 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1550 String macAddress) {
1551 return InstanceIdentifier.builder(ElanInterfaces.class)
1552 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1553 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1556 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1557 List<StaticMacEntries> updatedStaticMacEntries) {
1558 if (isEmpty(originalStaticMacEntries)) {
1559 return Collections.EMPTY_LIST;
1561 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1562 if (isNotEmpty(updatedStaticMacEntries)) {
1563 deleted.removeAll(updatedStaticMacEntries);
1568 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1569 if (isEmpty(orig)) {
1570 return Collections.EMPTY_LIST;
1572 List<T> diff = Lists.newArrayList(orig);
1573 if (isNotEmpty(updated)) {
1574 diff.removeAll(updated);
1579 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1580 List<StaticMacEntries> updatedStaticMacEntries) {
1581 if (isNotEmpty(updatedStaticMacEntries)) {
1582 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1583 if (isNotEmpty(originalStaticMacEntries)) {
1584 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1585 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1586 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1591 public static boolean isEmpty(Collection collection) {
1592 return collection == null || collection.isEmpty();
1595 public static boolean isNotEmpty(Collection collection) {
1596 return !isEmpty(collection);
1599 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1600 Optional<IpAddress> srcIpAddress = Optional.absent();
1601 if (ethernet.getPayload() == null) {
1602 return srcIpAddress;
1604 byte[] ipAddrBytes = null;
1605 if (ethernet.getPayload() instanceof IPv4) {
1606 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1607 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1608 } else if (ethernet.getPayload() instanceof ARP) {
1609 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1611 if (ipAddrBytes != null) {
1612 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1613 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1615 return srcIpAddress;
1618 public List<MacEntry> getElanMacEntries(String elanName) {
1619 MacTable macTable = getElanMacTable(elanName);
1620 if (macTable == null) {
1621 return Collections.emptyList();
1623 return macTable.getMacEntry();
1626 public boolean isTunnelInLogicalGroup(String interfaceName) {
1627 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1628 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1629 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1630 IfTunnel ifTunnel = configIface.augmentation(IfTunnel.class);
1631 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1632 ParentRefs refs = configIface.augmentation(ParentRefs.class);
1633 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1634 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1640 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1641 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1642 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1643 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1644 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1645 new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
1646 return InstanceIdentifier.builder(Nodes.class)
1647 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1648 nodeDpn.key()).augmentation(FlowCapableNode.class)
1649 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1652 public static String getElanInterfaceJobKey(String interfaceName) {
1653 return "elaninterface-" + interfaceName;
1656 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1658 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1660 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1663 public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
1664 Optional<Subnetmaps> subnetMapsData =
1665 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
1666 if (subnetMapsData.isPresent()) {
1667 List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
1668 if (subnetMapList != null && !subnetMapList.isEmpty()) {
1669 for (Subnetmap subnet : subnetMapList) {
1670 if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
1671 if (subnet.getRouterInterfacePortId() != null) {
1672 return subnet.getRouterInterfacePortId().getValue();
1681 static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
1682 return InstanceIdentifier.create(Subnetmaps.class);