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.HashSet;
25 import java.util.List;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.Future;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import javax.inject.Inject;
34 import javax.inject.Singleton;
35 import org.apache.commons.lang3.StringUtils;
36 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
37 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
38 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
41 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
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.netvirt.elan.ElanException;
68 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
69 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
168 import org.opendaylight.yangtools.yang.binding.DataObject;
169 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
170 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
171 import org.opendaylight.yangtools.yang.common.RpcResult;
172 import org.slf4j.Logger;
173 import org.slf4j.LoggerFactory;
176 public class ElanUtils {
178 private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
180 private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
181 private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
182 private static Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache = new ConcurrentHashMap<>();
183 private static Map<String, Set<String>> elanInstanceToInterfacesCache = new ConcurrentHashMap<>();
185 private final DataBroker broker;
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;
194 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
196 public void onSuccess(Void result) {
197 LOG.debug("Success in Datastore operation");
201 public void onFailure(Throwable error) {
202 LOG.error("Error in Datastore operation", error);
207 public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
208 OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
209 IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils) {
210 this.broker = dataBroker;
211 this.mdsalManager = mdsalManager;
212 this.interfaceManagerRpcService = interfaceManagerRpcService;
213 this.itmRpcService = itmRpcService;
214 this.interfaceManager = interfaceManager;
215 this.elanConfig = elanConfig;
216 this.elanEtreeUtils = elanEtreeUtils;
217 this.elanItmUtils = elanItmUtils;
220 public final Boolean isOpenstackVniSemanticsEnforced() {
221 return elanConfig.isOpenstackVniSemanticsEnforced() != null
222 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
225 public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
226 elanInstanceLocalCache.put(elanInstanceName, elanInstance);
229 public static void removeElanInstanceFromCache(String elanInstanceName) {
230 elanInstanceLocalCache.remove(elanInstanceName);
233 public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
234 return elanInstanceLocalCache.get(elanInstanceName);
237 public static Set<String> getAllElanNames() {
238 return elanInstanceLocalCache.keySet();
241 public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
242 elanInterfaceLocalCache.put(interfaceName, elanInterface);
245 public static void removeElanInterfaceFromCache(String interfaceName) {
246 elanInterfaceLocalCache.remove(interfaceName);
249 public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
250 return elanInterfaceLocalCache.get(interfaceName);
254 * Uses the IdManager to retrieve a brand new ElanTag.
260 * @return the integer
262 public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
264 AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
265 .setIdKey(idKey).build();
268 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
269 RpcResult<AllocateIdOutput> rpcResult = result.get();
270 if (rpcResult.isSuccessful()) {
271 return rpcResult.getResult().getIdValue();
273 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
275 } catch (InterruptedException | ExecutionException e) {
276 LOG.warn("Exception when Allocating Id", e);
281 public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
282 ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
283 JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
289 * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
291 * @param broker dataBroker
292 * @param datastoreType Logical DataStore type
293 * @param path IID to read
294 * @param <T> T extends DataObject
295 * @return the read value T
298 @SuppressWarnings("checkstyle:IllegalCatch")
299 public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
300 LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
301 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
302 return tx.read(datastoreType, path).get();
303 } catch (Exception e) {
304 throw new RuntimeException(e);
308 public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
309 throws ReadFailedException {
310 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
311 CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
312 return checkedFuture.checkedGet();
316 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
317 InstanceIdentifier<T> path) {
318 WriteTransaction tx = broker.newWriteOnlyTransaction();
319 tx.delete(datastoreType, path);
320 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
323 public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
324 InstanceIdentifier<T> path, FutureCallback<Void> callback) {
325 WriteTransaction tx = broker.newWriteOnlyTransaction();
326 tx.delete(datastoreType, path);
327 Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
330 public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
331 return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
334 // elan-instances config container
336 public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
337 ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
338 if (elanObj != null) {
341 InstanceIdentifier<ElanInstance> elanIdentifierId =
342 ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName);
343 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
346 // elan-interfaces Config Container
347 public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
348 ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
349 if (elanInterfaceObj != null) {
350 return elanInterfaceObj;
352 InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
353 return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
356 public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
357 ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
358 if (elanInterface == null) {
361 return elanInterface.getAugmentation(EtreeInterface.class);
365 public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
366 return InstanceIdentifier.builder(ElanInterfaces.class)
367 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
370 // elan-state Operational container
371 public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
372 InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
373 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
376 public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
377 return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
380 // grouping of forwarding-entries
381 public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
382 InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
383 interfaceName, physAddress);
384 return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
387 public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
388 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
389 LogicalDatastoreType.OPERATIONAL, identifier);
390 return existingInterfaceMacEntry.orNull();
393 public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
394 PhysAddress physAddress) {
395 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
396 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
397 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
401 // elan-forwarding-tables Operational container
402 public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
403 InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
404 return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
407 public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
408 Optional<MacEntry> existingInterfaceMacEntry = read(broker,
409 LogicalDatastoreType.OPERATIONAL, identifier);
410 return existingInterfaceMacEntry.orNull();
413 public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
414 PhysAddress physAddress) {
415 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
416 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
419 public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
420 return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
424 // elan-interface-forwarding-entries Operational container
425 public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
426 return getElanInterfaceMacByInterfaceName(broker, interfaceName);
430 public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
431 InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
433 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
437 * Gets the elan interface mac addresses.
439 * @param interfaceName
441 * @return the elan interface mac addresses
443 public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
444 List<PhysAddress> macAddresses = new ArrayList<>();
445 ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
446 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
447 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
448 for (MacEntry macEntry : macEntries) {
449 macAddresses.add(macEntry.getMacAddress());
455 public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
456 String interfaceName) {
457 return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
458 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
462 * Returns the list of Interfaces that belong to an Elan on an specific DPN.
463 * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
465 * @param elanInstanceName
466 * name of the Elan to which the interfaces must belong to
468 * Id of the DPN where the interfaces are located
469 * @return the elan interface Info
471 public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
472 InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
474 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
478 * Returns the InstanceIdentifier that points to the Interfaces of an Elan
479 * in a given DPN in the Operational DS. Data retrieved from Elans's
480 * operational DS: dpn-interfaces list
482 * @param elanInstanceName
483 * name of the Elan to which the interfaces must belong to
485 * Id of the DPN where the interfaces are located
486 * @return the elan dpn interface
488 public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
490 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
491 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
492 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
495 // elan-tag-name-map Operational Container
496 public ElanTagName getElanInfoByElanTag(long elanTag) {
497 InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
498 Optional<ElanTagName> existingElanInfo = read(broker,
499 LogicalDatastoreType.OPERATIONAL, elanId);
500 return existingElanInfo.orNull();
503 public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
504 return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
508 // interface-index-tag operational container
509 public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
510 InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
511 return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
514 public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
515 return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
516 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
519 public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
520 return InstanceIdentifier.builder(ElanDpnInterfaces.class)
521 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
524 public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
525 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
526 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
529 public ElanDpnInterfaces getElanDpnInterfacesList() {
530 InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
532 return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
536 * This method is useful get all ELAN participating CSS dpIds to install
537 * program remote dmac entries and updating remote bc groups for tor
540 * @param elanInstanceName
541 * the elan instance name
542 * @return list of dpIds
545 public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
546 List<BigInteger> dpIds = new ArrayList<>();
547 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
548 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
549 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
550 if (!existingElanDpnInterfaces.isPresent()) {
553 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
554 for (DpnInterfaces dpnInterface : dpnInterfaces) {
555 dpIds.add(dpnInterface.getDpId());
561 * To check given dpId is already present in Elan instance. This can be used
562 * to program flow entry in external tunnel table when a new access port
563 * added for first time into the ELAN instance
567 * @param elanInstanceName
568 * the elan instance name
569 * @return true if dpId is already present, otherwise return false
571 public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
572 InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
573 Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
574 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
575 if (!existingElanDpnInterfaces.isPresent()) {
578 List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
579 for (DpnInterfaces dpnInterface : dpnInterfaces) {
580 if (dpnInterface.getDpId().equals(dpId)) {
587 public ElanForwardingTables getElanForwardingList() {
588 InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
589 .builder(ElanForwardingTables.class).build();
590 return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
593 public static long getElanRemoteBroadCastGroupID(long elanTag) {
594 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
598 * Gets the elan mac table.
602 * @return the elan mac table
604 public MacTable getElanMacTable(String elanName) {
605 return getElanMacTable(broker, elanName);
609 public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
610 InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
611 return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
614 public static long getElanLocalBCGId(long elanTag) {
615 return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
618 public static long getElanRemoteBCGId(long elanTag) {
619 return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
622 public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
623 return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
626 public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
627 return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
630 public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
631 int shBit = isSHFlagSet ? 1 : 0;
632 return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
636 * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
640 * @param interfaceInfo
646 * @param configureRemoteFlows
647 * true if remote dmac flows should be configured as well
648 * @param writeFlowGroupTx
650 * @throws ElanException in case of issues creating the flow objects
652 public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
653 long macTimeout, String macAddress, boolean configureRemoteFlows,
654 WriteTransaction writeFlowGroupTx) throws ElanException {
655 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
656 setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
658 setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
663 public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
664 String macAddress, WriteTransaction writeFlowTx) throws ElanException {
665 String elanInstanceName = elanInfo.getElanInstanceName();
666 setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
667 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
668 LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
669 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
670 macAddress, dstDpId);
674 * Inserts a Flow in SMAC table to state that the MAC has already been
677 private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
678 String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
679 FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
680 mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
681 LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
682 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
685 public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
687 int lportTag = interfaceInfo.getInterfaceTag();
688 // Matching metadata and eth_src fields
689 List<MatchInfo> mkMatches = new ArrayList<>();
690 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
691 ElanHelper.getElanMetadataMask()));
692 mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
693 List<InstructionInfo> mkInstructions = new ArrayList<>();
694 mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
695 BigInteger dpId = interfaceInfo.getDpId();
696 long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
697 return new FlowEntityBuilder()
699 .setTableId(NwConstants.ELAN_SMAC_TABLE)
700 .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
702 .setFlowName(elanInfo.getDescription())
703 .setIdleTimeOut((int) macTimeout)
705 .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
706 .setMatchInfoList(mkMatches)
707 .setInstructionInfoList(mkInstructions)
709 // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
710 .setSendFlowRemFlag(macTimeout != 0)
714 private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
715 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
716 if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
717 return elanInfo.getElanTag();
719 EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
720 if (etreeInstance == null) {
721 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
722 interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
723 return elanInfo.getElanTag();
725 return etreeInstance.getEtreeLeafTagVal().getValue();
731 * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
732 * the packet through the specified interface if the tunnel_id matches the
733 * interface's lportTag.
735 * @param interfaceInfo
737 * @param mdsalApiManager
738 * the mdsal API manager
739 * @param writeFlowGroupTx
740 * the writeFLowGroup tx
742 public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
743 WriteTransaction writeFlowGroupTx) {
744 BigInteger dpId = interfaceInfo.getDpId();
745 int lportTag = interfaceInfo.getInterfaceTag();
746 Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
747 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
748 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
749 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
750 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
751 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
752 mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
753 LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
754 interfaceInfo.getPortName());
758 * Constructs the FlowName for flows installed in the Internal Tunnel Table,
759 * consisting in tableId + elanTag.
765 * @return the Internal tunnel
767 public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
768 return new StringBuffer().append(tableId).append(elanTag).toString();
772 * Constructs the Matches that checks that the tunnel_id field contains a
776 * lportTag that must be checked against the tunnel_id field
777 * @return the list of match Info
779 public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
780 List<MatchInfo> mkMatches = new ArrayList<>();
782 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
787 * Constructs the Instructions that take the packet over a given interface.
790 * Name of the interface where the packet must be sent over. It
791 * can be a local interface or a tunnel interface (internal or
793 * @return the Instruction
795 public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
796 List<Instruction> mkInstructions = new ArrayList<>();
797 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
799 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
800 return mkInstructions;
804 * Returns the list of Actions to be taken when sending the packet through
805 * an Elan interface. Note that this interface can refer to an ElanInterface
806 * where the Elan VM is attached to a DPN or an ITM tunnel interface where
807 * Elan traffic can be sent through. In this latter case, the tunnelKey is
808 * mandatory and it can hold serviceId for internal tunnels or the VNI for
815 * @return the egress actions for interface
817 @SuppressWarnings("checkstyle:IllegalCatch")
818 public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
819 List<Action> listAction = new ArrayList<>();
821 GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
822 .setIntfName(ifName).setTunnelKey(tunnelKey).build();
823 Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
824 .getEgressActionsForInterface(getEgressActionInput);
825 RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
826 if (!rpcResult.isSuccessful()) {
827 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
828 rpcResult.getErrors());
830 List<Action> actions = rpcResult.getResult().getAction();
831 listAction = actions;
833 } catch (Exception e) {
834 LOG.warn("Exception when egress actions for interface {}", ifName, e);
839 private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
840 boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
841 WriteTransaction writeFlowGroupTx)
842 throws ElanException {
843 BigInteger dpId = interfaceInfo.getDpId();
844 String ifName = interfaceInfo.getInterfaceName();
845 long ifTag = interfaceInfo.getInterfaceTag();
846 String elanInstanceName = elanInfo.getElanInstanceName();
848 Long elanTag = elanInfo.getElanTag();
850 setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
852 LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
853 + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
855 if (!configureRemoteFlows) {
859 List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
860 for (DpnInterfaces elanDpn : elanDpns) {
862 if (elanDpn.getDpId().equals(dpId)) {
866 // Check for the Remote DPN present in Inventory Manager
867 if (!isDpnPresent(elanDpn.getDpId())) {
871 // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
872 // forwarded through the appropriate ITM tunnel
873 setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
874 dpId, // dstDpn (the local DPN)
875 interfaceInfo.getInterfaceTag(), // lportTag of the local interface
876 elanTag, // identifier of the Elan
877 macAddress, // MAC to be programmed in remote DPN
878 elanInstanceName, writeFlowGroupTx, ifName, elanInfo
880 LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
881 + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
884 // TODO: Make sure that the same is performed against the ElanDevices.
888 public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
889 return getElanDPNByName(elanName);
893 public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
894 InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
895 return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
896 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
899 private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
900 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
901 Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
902 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
903 installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
904 mdsalApiManager, ifTag, writeFlowGroupTx);
907 private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
908 ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
909 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
910 if (etreeInterface != null) {
911 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
912 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
913 if (etreeTagName == null) {
914 LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
917 Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
918 macAddress, elanInfo, ifTag);
919 mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
925 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
927 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
931 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
932 String macAddress, long elanTag) {
933 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
937 public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
938 return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
941 public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
942 String dstMacAddress, long elanTag, boolean shFlag) {
943 return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
944 .append(dstMacAddress).append(shFlag).toString();
948 * Builds the flow to be programmed in the DMAC table of the local DPN (that
949 * is, where the MAC is attached to). This flow consists in:
951 * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
952 * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
969 public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
970 ElanInstance elanInfo, long ifTag) {
972 List<MatchInfo> mkMatches = new ArrayList<>();
973 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
974 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
976 List<Instruction> mkInstructions = new ArrayList<>();
977 List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
978 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
979 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
980 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
981 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
982 BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
987 public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
988 macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
989 elanInstance) throws ElanException {
990 if (interfaceManager.isExternalInterface(interfaceName)) {
991 LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
992 macAddress, interfaceName, elanInstance.getElanInstanceName());
996 // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
997 // networks, 0 otherwise
998 long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
999 ? elanInstance.getSegmentationId() : 0;
1000 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
1002 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1003 setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
1004 writeFlowGroupTx, elanInstance);
1007 private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1008 String macAddress, String displayName, String interfaceName,
1009 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
1010 throws ElanException {
1012 EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1013 if (etreeInterface != null) {
1014 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1015 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1016 if (etreeTagName == null) {
1017 LOG.warn("Interface " + interfaceName
1018 + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
1020 flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
1021 etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1022 mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1029 * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1030 * consists in: Match: + elanTag in packet's metadata + packet going to a
1031 * MAC known to be located in another DPN Actions: + set_tunnel_id
1032 * + output ITM internal tunnel interface with the other DPN
1038 * @param lportTagOrVni
1039 * lportTag or network VNI
1044 * @param displayName
1046 * @param elanInstance
1048 * @return the flow remote Dmac
1049 * @throws ElanException in case of issues creating the flow objects
1051 @SuppressWarnings("checkstyle:IllegalCatch")
1052 public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1053 String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1054 List<MatchInfo> mkMatches = new ArrayList<>();
1055 mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1056 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1058 List<Instruction> mkInstructions = new ArrayList<>();
1060 // List of Action for the provided Source and Destination DPIDs
1062 List<Action> actions = null;
1063 if (isVlan(elanInstance) || isFlat(elanInstance)) {
1064 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1065 if (null == interfaceName) {
1066 LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1069 actions = getEgressActionsForInterface(interfaceName, null);
1070 } else if (isVxlan(elanInstance)) {
1071 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1073 mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1074 } catch (Exception e) {
1075 LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1076 + ", lportTag/VNI=" + lportTagOrVni, e);
1079 Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1080 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1082 displayName, 0, /* idleTimeout */
1083 0, /* hardTimeout */
1084 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1090 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1091 WriteTransaction deleteFlowGroupTx) {
1092 if (elanInfo == null || interfaceInfo == null) {
1095 String macAddress = macEntry.getMacAddress().getValue();
1096 synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1097 deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1101 public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1102 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1103 String elanInstanceName = elanInfo.getElanInstanceName();
1104 List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1105 BigInteger srcdpId = interfaceInfo.getDpId();
1106 boolean isFlowsRemovedInSrcDpn = false;
1107 for (DpnInterfaces dpnInterface : remoteFEs) {
1108 Long elanTag = elanInfo.getElanTag();
1109 BigInteger dstDpId = dpnInterface.getDpId();
1110 if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1111 elanTag, dstDpId, deleteFlowGroupTx)) {
1112 isFlowsRemovedInSrcDpn = true;
1114 executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1115 elanTag, dstDpId, deleteFlowGroupTx);
1117 if (!isFlowsRemovedInSrcDpn) {
1118 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1122 private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1123 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1124 WriteTransaction deleteFlowGroupTx) {
1125 EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1126 if (etreeLeafTag != null) {
1127 executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1128 etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1132 private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1133 boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1134 WriteTransaction deleteFlowGroupTx) {
1135 boolean isFlowsRemovedInSrcDpn = false;
1136 if (dstDpId.equals(srcdpId)) {
1137 isFlowsRemovedInSrcDpn = true;
1138 deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1139 } else if (isDpnPresent(dstDpId)) {
1141 .removeFlowToTx(dstDpId,
1142 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1143 NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1145 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1146 elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1148 return isFlowsRemovedInSrcDpn;
1151 private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1152 boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1153 String elanInstanceName = elanInfo.getElanInstanceName();
1154 long ifTag = interfaceInfo.getInterfaceTag();
1155 BigInteger srcdpId = interfaceInfo.getDpId();
1156 Long elanTag = elanInfo.getElanTag();
1159 .removeFlowToTx(srcdpId,
1160 MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1161 NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1164 mdsalManager.removeFlowToTx(srcdpId,
1165 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1166 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1168 LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1169 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1173 * Updates the Elan information in the Operational DS. It also updates the
1174 * ElanInstance in the Config DS by setting the adquired elanTag.
1180 * @param elanInstanceAdded
1181 * the elan instance added
1182 * @param elanInterfaces
1183 * the elan interfaces
1187 * @return the updated ELAN instance.
1189 public static ElanInstance updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1190 ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1191 String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1192 Long elanTag = elanInstanceAdded.getElanTag();
1193 if (elanTag == null || elanTag == 0L) {
1194 elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1196 Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1197 .setKey(new ElanKey(elanInstanceName)).build();
1199 // Add the ElanState in the elan-state operational data-store
1200 tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1201 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1203 // Add the ElanMacTable in the elan-mac-table operational data-store
1204 MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1205 tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1206 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1208 ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1209 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1210 long etreeLeafTag = -1;
1211 if (isEtreeInstance(elanInstanceAdded)) {
1212 etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1214 EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1215 .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1216 elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1217 addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1219 ElanTagName elanTagName = elanTagNameBuilder.build();
1221 // Add the ElanTag to ElanName in the elan-tag-name Operational
1223 tx.put(LogicalDatastoreType.OPERATIONAL,
1224 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1226 // Updates the ElanInstance Config DS by setting the just acquired
1228 ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1229 .setDescription(elanInstanceAdded.getDescription())
1230 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1231 ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1232 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1233 if (isEtreeInstance(elanInstanceAdded)) {
1234 EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1236 elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1238 ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1239 tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1240 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1241 return elanInstanceWithTag;
1244 private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1245 WriteTransaction tx) {
1246 ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1247 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1248 tx.put(LogicalDatastoreType.OPERATIONAL,
1249 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1252 private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1253 return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1256 public boolean isDpnPresent(BigInteger dpnId) {
1257 String dpn = String.format("%s:%s", "openflow", dpnId);
1258 NodeId nodeId = new NodeId(dpn);
1260 InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1262 return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1265 public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1266 return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1267 ElanConstants.ELAN_SERVICE_PRIORITY);
1270 public static String getElanServiceName(String elanName, String interfaceName) {
1271 return "elan." + elanName + interfaceName;
1274 public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1275 BigInteger cookie, List<Instruction> instructions) {
1276 StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1277 .setInstruction(instructions);
1278 return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1279 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1280 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1283 public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1284 return InstanceIdentifier.builder(ServiceBindings.class)
1285 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1286 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1289 public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1290 List<MatchInfo> mkMatches = new ArrayList<>();
1291 // Matching metadata
1292 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1297 public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1298 RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1299 .setDpnId(destDpId).setServiceId(serviceId).build();
1300 Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1302 RpcResult<Void> result = futureObject.get();
1303 if (result.isSuccessful()) {
1304 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1305 + "dpn {}", serviceId, destDpId);
1307 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1308 + "dpn {}", serviceId, destDpId);
1310 } catch (InterruptedException | ExecutionException e) {
1311 LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1312 + "dpn {}: {}", serviceId, destDpId, e);
1317 * Gets the external tunnel.
1319 * @param sourceDevice
1321 * @param destinationDevice
1322 * the destination device
1323 * @param datastoreType
1324 * the datastore type
1325 * @return the external tunnel
1327 public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1328 LogicalDatastoreType datastoreType) {
1329 Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1330 InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1331 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1332 return read(broker, datastoreType, iid).orNull();
1336 * Gets the external tunnel.
1338 * @param interfaceName
1339 * the interface name
1340 * @param datastoreType
1341 * the datastore type
1342 * @return the external tunnel
1344 public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1345 ExternalTunnel externalTunnel = null;
1346 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1347 for (ExternalTunnel tunnel : externalTunnels) {
1348 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1349 externalTunnel = tunnel;
1353 return externalTunnel;
1357 * Gets the all external tunnels.
1359 * @param datastoreType
1360 * the data store type
1361 * @return the all external tunnels
1363 public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1364 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1365 return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1366 Collections.emptyList());
1369 public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1370 List<MatchInfo> mkMatches = new ArrayList<>();
1372 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1373 mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1378 * Checks if is interface operational.
1380 * @param interfaceName
1381 * the interface name
1384 * @return true, if is interface operational
1386 public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1387 if (StringUtils.isBlank(interfaceName)) {
1390 Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1391 if (ifState == null) {
1394 return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1398 * Gets the interface state from operational ds.
1400 * @param interfaceName
1401 * the interface name
1404 * @return the interface state from oper ds
1406 public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1407 .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1408 String interfaceName, DataBroker dataBroker) {
1409 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1410 .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1412 return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1416 * Creates the interface state instance identifier.
1418 * @param interfaceName
1419 * the interface name
1420 * @return the instance identifier
1422 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1423 .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1424 String interfaceName) {
1425 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1426 .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1427 .builder(InterfacesState.class)
1428 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1429 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1430 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1431 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1433 return idBuilder.build();
1436 public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1437 WriteTransaction tx) {
1438 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1441 } catch (InterruptedException | ExecutionException e) {
1442 LOG.error("Error writing to datastore {}", e);
1447 public static boolean isVxlanNetwork(DataBroker broker, String elanInstanceName) {
1448 ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1449 return elanInstance != null && isVxlan(elanInstance);
1452 public static boolean isVxlan(ElanInstance elanInstance) {
1453 return elanInstance != null && elanInstance.getSegmentType() != null
1454 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1455 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1458 private static boolean isVxlanSegment(ElanInstance elanInstance) {
1459 if (elanInstance != null) {
1460 List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1461 if (elanSegments != null) {
1462 for (ElanSegments segment : elanSegments) {
1463 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1464 && segment.getSegmentationId() != null
1465 && segment.getSegmentationId().longValue() != 0) {
1474 public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1475 return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1478 public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1479 Long segmentationId = 0L;
1480 if (elanInstance == null) {
1481 return segmentationId;
1484 if (elanInstance.getSegmentType() != null
1485 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1486 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1487 segmentationId = elanInstance.getSegmentationId();
1489 for (ElanSegments segment: elanInstance.getElanSegments()) {
1490 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1491 && segment.getSegmentationId() != null
1492 && segment.getSegmentationId().longValue() != 0) {
1493 segmentationId = segment.getSegmentationId();
1497 return segmentationId;
1500 public static boolean isVlan(ElanInstance elanInstance) {
1501 return elanInstance != null && elanInstance.getSegmentType() != null
1502 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1503 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1506 public static boolean isFlat(ElanInstance elanInstance) {
1507 return elanInstance != null && elanInstance.getSegmentType() != null
1508 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1511 public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1512 String macAddress, List<BigInteger> dpnIds) {
1513 for (BigInteger dpId : dpnIds) {
1514 WriteTransaction writeTx = broker.newWriteOnlyTransaction();
1515 mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
1521 public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1522 for (BigInteger dpId : dpnIds) {
1523 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1524 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1528 public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1529 String displayName, long elanTag) {
1530 List<MatchInfo> matches = new ArrayList<>();
1531 matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1532 matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1533 List<InstructionInfo> instructions = new ArrayList<>();
1534 List<ActionInfo> actions = new ArrayList<>();
1535 actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1537 instructions.add(new InstructionApplyActions(actions));
1538 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1539 FlowEntity flow = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1540 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1541 matches, instructions);
1546 * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
1547 * Install SMAC and DMAC flows.
1548 * @param interfaceName interface name
1549 * @param macAddress mac addresses
1550 * @param elanName elan Name
1551 * @param interfaceTx write transaction
1552 * @param flowTx flow write transaction
1553 * @param macTimeOut timeout value
1554 * @throws ElanException elan exception is thrown upon write failure
1556 public void addMacEntryToDsAndSetupFlows(String interfaceName,
1557 String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx, int macTimeOut)
1558 throws ElanException {
1559 LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
1560 + "ElanForwardingTables DS", macAddress, interfaceName);
1561 BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
1562 PhysAddress physAddress = new PhysAddress(macAddress);
1563 MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
1564 .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
1565 .setIsStaticAddress(false).build();
1566 InstanceIdentifier<MacEntry> macEntryId = ElanUtils
1567 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
1568 interfaceTx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
1569 InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
1570 interfaceTx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
1571 ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
1572 setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
1577 * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
1578 * Remove SMAC and DMAC flows.
1579 * @param interfaceName interface name
1580 * @param macAddress mac addresses
1581 * @param elanName elan name
1582 * @param interfaceTx write transaction
1583 * @param flowTx flow write transaction
1585 public void deleteMacEntryFromDsAndRemoveFlows(String interfaceName,
1586 String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx) {
1587 LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
1588 + "and ElanForwardingTables DS", macAddress, interfaceName);
1589 PhysAddress physAddress = new PhysAddress(macAddress);
1590 MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
1591 InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
1592 if (macEntry != null && interfaceInfo != null) {
1593 deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, flowTx);
1595 interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
1596 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
1597 interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
1598 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
1601 public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1602 DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1603 if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1604 LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1608 for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1609 if (interfaceManager.isExternalInterface(dpnInterface)) {
1610 return dpnInterface;
1614 LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1618 public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1619 String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1620 return elanMacDmacDpnKey.intern();
1623 public static String getElanMacKey(long elanTag, String macAddress) {
1624 String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1625 return elanMacKey.intern();
1628 // TODO This should return a collection of futures
1629 public static void addToListenableFutureIfTxException(RuntimeException exception,
1630 List<ListenableFuture<Void>> futures) {
1631 Throwable cause = exception.getCause();
1632 if (cause != null && cause instanceof TransactionCommitFailedException) {
1633 futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1637 public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1638 Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1639 List<PhysAddress> physAddresses = new ArrayList<>();
1640 for (String mac : macAddress) {
1641 physAddresses.add(new PhysAddress(mac));
1643 return physAddresses;
1646 public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1647 if (isEmpty(staticMacAddresses)) {
1648 return Collections.EMPTY_LIST;
1650 StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1651 List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1652 List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1653 for (PhysAddress physAddress : physAddressList) {
1654 staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1656 return staticMacEntries;
1659 public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1660 String macAddress) {
1661 return InstanceIdentifier.builder(ElanInterfaces.class)
1662 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1663 new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1666 public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1667 List<StaticMacEntries> updatedStaticMacEntries) {
1668 if (isEmpty(originalStaticMacEntries)) {
1669 return Collections.EMPTY_LIST;
1671 List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1672 if (isNotEmpty(updatedStaticMacEntries)) {
1673 deleted.removeAll(updatedStaticMacEntries);
1678 public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1679 if (isEmpty(orig)) {
1680 return Collections.EMPTY_LIST;
1682 List<T> diff = Lists.newArrayList(orig);
1683 if (isNotEmpty(updated)) {
1684 diff.removeAll(updated);
1689 public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1690 List<StaticMacEntries> updatedStaticMacEntries) {
1691 if (isNotEmpty(updatedStaticMacEntries)) {
1692 List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1693 if (isNotEmpty(originalStaticMacEntries)) {
1694 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1695 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1696 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1701 public static boolean isEmpty(Collection collection) {
1702 return collection == null || collection.isEmpty();
1705 public static boolean isNotEmpty(Collection collection) {
1706 return !isEmpty(collection);
1709 public static void setElanInstancToDpnsCache(Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache) {
1710 ElanUtils.elanInstancToDpnsCache = elanInstancToDpnsCache;
1713 public static Set<DpnInterfaces> getElanInvolvedDPNsFromCache(String elanName) {
1714 return elanInstancToDpnsCache.get(elanName);
1717 public static void addDPNInterfaceToElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1718 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).add(dpnInterfaces);
1721 public static void removeDPNInterfaceFromElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1722 elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).remove(dpnInterfaces);
1725 public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1726 Optional<IpAddress> srcIpAddress = Optional.absent();
1727 if (ethernet.getPayload() == null) {
1728 return srcIpAddress;
1730 byte[] ipAddrBytes = null;
1731 if (ethernet.getPayload() instanceof IPv4) {
1732 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1733 ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1734 } else if (ethernet.getPayload() instanceof ARP) {
1735 ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1737 if (ipAddrBytes != null) {
1738 String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1739 return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1741 return srcIpAddress;
1744 public List<MacEntry> getElanMacEntries(String elanName) {
1745 MacTable macTable = getElanMacTable(elanName);
1746 if (macTable == null) {
1747 return Collections.emptyList();
1749 return macTable.getMacEntry();
1752 public boolean isTunnelInLogicalGroup(String interfaceName) {
1753 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1754 .ietf.interfaces.rev140508.interfaces.Interface configIface =
1755 interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1756 IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1757 if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1758 ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1759 if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1760 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1766 public static void addElanInterfaceToElanInstanceCache(String elanInstanceName, String elanInterfaceName) {
1767 elanInstanceToInterfacesCache.computeIfAbsent(elanInstanceName, key -> new HashSet<>()).add(elanInterfaceName);
1770 public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
1771 Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
1772 if (elanInterfaces == null || elanInterfaces.isEmpty()) {
1775 elanInterfaces.remove(interfaceName);
1778 @Nonnull public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
1779 Set<String> removed = elanInstanceToInterfacesCache.remove(elanInstanceName);
1780 return removed != null ? removed : Collections.emptySet();
1783 public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1784 FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1785 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1786 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1787 org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1788 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1789 return InstanceIdentifier.builder(Nodes.class)
1790 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1791 nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1792 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1795 public static String getElanInterfaceJobKey(String interfaceName) {
1796 return "elaninterface-" + interfaceName;
1799 public void addArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress, String macAddress,
1800 int lportTag, List<Instruction> instructions) {
1801 LOG.info("Installing the ARP responder flow on DPN {} for Interface {} with MAC {} & IP {}", dpnId,
1802 ingressInterfaceName, macAddress, ipAddress);
1803 ElanInterface elanIface = getElanInterfaceByElanInterfaceName(broker, ingressInterfaceName);
1804 ElanInstance elanInstance = getElanInstanceByName(broker, elanIface.getElanInstanceName());
1805 if (elanInstance == null) {
1806 LOG.debug("addArpResponderFlow: elanInstance is null, Failed to install arp responder flow for Interface {}"
1807 + " with MAC {} & IP {}", dpnId,
1808 ingressInterfaceName, macAddress, ipAddress);
1811 String flowId = ArpResponderUtil.getFlowId(lportTag, ipAddress);
1812 ArpResponderUtil.installFlow(mdsalManager, dpnId, flowId, flowId, NwConstants.DEFAULT_ARP_FLOW_PRIORITY,
1813 ArpResponderUtil.generateCookie(lportTag, ipAddress),
1814 ArpResponderUtil.getMatchCriteria(lportTag, elanInstance, ipAddress), instructions);
1815 LOG.info("Installed the ARP Responder flow for Interface {}", ingressInterfaceName);
1818 public void addExternalTunnelArpResponderFlow(BigInteger dpnId, String ipAddress, String macAddress,
1819 int lportTag, List<Instruction> instructions, String elanInstanceName) {
1820 LOG.trace("Installing the ExternalTunnel ARP responder flow on DPN {} for ElanInstance {} with MAC {} & IP {}",
1821 dpnId, elanInstanceName, macAddress, ipAddress);
1822 ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1823 String flowId = ArpResponderUtil.getFlowId(lportTag, ipAddress);
1824 ArpResponderUtil.installFlow(mdsalManager, dpnId, flowId, flowId, NwConstants.DEFAULT_ARP_FLOW_PRIORITY,
1825 ArpResponderUtil.generateCookie(lportTag, ipAddress),
1826 ArpResponderUtil.getMatchCriteria(lportTag, elanInstance, ipAddress), instructions);
1827 LOG.trace("Installed the ExternalTunnel ARP Responder flow for ElanInstance {}", elanInstanceName);
1830 public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1832 LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1834 ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));